<?php
/**
 * Ops metrics for system dashboard / health: uploads size, backup age, HTTPS/session hints.
 */
declare(strict_types=1);

/**
 * Total size of all regular files under a directory (0 if missing/unreadable).
 */
function nazareth_directory_size_bytes(string $path): int
{
    if (!is_dir($path) || !is_readable($path)) {
        return 0;
    }
    try {
        $total = 0;
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)
        );
        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $total += $file->getSize();
            }
        }

        return $total;
    } catch (Throwable $e) {
        return 0;
    }
}

/**
 * @return array{uploads_root: string, total_bytes: int, members_bytes: int, members_path: string}
 */
function nazareth_uploads_storage_summary(string $projectRoot): array
{
    $uploadsRoot = rtrim($projectRoot, '/') . '/public/uploads';
    $membersPath = $uploadsRoot . '/members';

    return [
        'uploads_root' => $uploadsRoot,
        'total_bytes' => nazareth_directory_size_bytes($uploadsRoot),
        'members_bytes' => is_dir($membersPath) ? nazareth_directory_size_bytes($membersPath) : 0,
        'members_path' => $membersPath,
    ];
}

/**
 * Latest *.sql in backups directory.
 *
 * @return array{
 *   latest_mtime: int|null,
 *   latest_name: string|null,
 *   age_seconds: int|null,
 *   level: 'none'|'ok'|'warn'|'critical',
 *   file_count: int
 * }
 */
function nazareth_backup_freshness_summary(string $backupDir, float $warnAfterDays = 7.0, float $criticalAfterDays = 30.0): array
{
    $out = [
        'latest_mtime' => null,
        'latest_name' => null,
        'age_seconds' => null,
        'level' => 'none',
        'file_count' => 0,
    ];

    if (!is_dir($backupDir)) {
        return $out;
    }

    $files = glob($backupDir . '/*.sql') ?: [];
    $out['file_count'] = count($files);
    $latest = 0;
    $latestName = null;

    foreach ($files as $f) {
        $m = @filemtime($f);
        if ($m !== false && $m > $latest) {
            $latest = $m;
            $latestName = basename($f);
        }
    }

    if ($latest === 0 || $latestName === null) {
        return $out;
    }

    $out['latest_mtime'] = $latest;
    $out['latest_name'] = $latestName;
    $out['age_seconds'] = time() - $latest;
    $days = $out['age_seconds'] / 86400;

    if ($days >= $criticalAfterDays) {
        $out['level'] = 'critical';
    } elseif ($days >= $warnAfterDays) {
        $out['level'] = 'warn';
    } else {
        $out['level'] = 'ok';
    }

    return $out;
}

function nazareth_request_uses_https(): bool
{
    return (!empty($_SERVER['HTTPS']) && strcasecmp((string) $_SERVER['HTTPS'], 'off') !== 0)
        || ((string) ($_SERVER['SERVER_PORT'] ?? '') === '443')
        || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])
            && strtolower((string) $_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https');
}
