<?php
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;
use App\Core\Database;

Auth::requireRole(['admin', 'staff']);
$pageTitle = 'Control Panel Health Check | Admin';

$checks = [];
$add = static function (string $name, bool $ok, string $detail, bool $critical = false) use (&$checks): void {
    $checks[] = compact('name', 'ok', 'detail', 'critical');
};

$add('PHP version', version_compare(PHP_VERSION, '8.2.0', '>='), 'Detected PHP ' . PHP_VERSION . '; PHP 8.2+ is required.', true);
foreach (['pdo_mysql', 'mbstring', 'fileinfo', 'json'] as $extension) {
    $add('PHP extension: ' . $extension, extension_loaded($extension), extension_loaded($extension) ? 'Loaded.' : 'Missing.', true);
}
$add('PHP extension: curl', extension_loaded('curl'), extension_loaded('curl') ? 'Loaded for SSLCommerz.' : 'Missing; online gateway calls will fail.', false);
$add('Database configuration', Database::configured(), Database::configured() ? 'Database name and user are configured.' : 'Create app/config.local.php and set DB_NAME, DB_USER and DB_PASS.', true);
$connected = Database::isConnected();
$add('Database connection', $connected, $connected ? 'PDO connection is active.' : 'Connection failed. Review app/config.local.php and the server error log.', true);
$add('Application URL', APP_URL !== '' && filter_var(APP_URL, FILTER_VALIDATE_URL), APP_URL !== '' ? APP_URL : 'APP_URL is empty.', true);
$add('HTTPS production URL', APP_ENV !== 'production' || str_starts_with(strtolower(APP_URL), 'https://'), APP_ENV === 'production' ? 'Production should use HTTPS.' : 'Development mode.', true);
$add('Application key', APP_ENV !== 'production' || strlen(APP_KEY) >= 32, strlen(APP_KEY) >= 32 ? 'APP_KEY length is acceptable.' : 'Set a random APP_KEY of at least 32 characters.', true);
$add('Cron token', strlen(CRON_TOKEN) >= 24, strlen(CRON_TOKEN) >= 24 ? 'CRON_TOKEN length is acceptable.' : 'Set a random CRON_TOKEN of at least 24 characters.', false);
$add('Debug disabled', APP_ENV !== 'production' || !APP_DEBUG, APP_DEBUG ? 'APP_DEBUG is enabled.' : 'Debug output is disabled.', true);
$add('Writable logs', is_dir(ROOT_PATH . '/storage/logs') && is_writable(ROOT_PATH . '/storage/logs'), 'storage/logs must be writable by PHP.', true);
$add('Writable private uploads', is_dir(ROOT_PATH . '/storage/private_uploads') && is_writable(ROOT_PATH . '/storage/private_uploads'), 'storage/private_uploads must be writable by PHP.', true);
$add('Writable public uploads', is_dir(ROOT_PATH . '/public/uploads') && is_writable(ROOT_PATH . '/public/uploads'), 'public/uploads must be writable by PHP.', true);
$add('Root access rules', is_file(ROOT_PATH . '/.htaccess'), '.htaccess is present; confirm Apache AllowOverride permits it.', true);
$add('Upload execution block', is_file(ROOT_PATH . '/public/uploads/.htaccess'), 'The upload directory contains script-execution protection.', true);
$add('Dynamic PWA manifest', is_file(ROOT_PATH . '/public/manifest.php'), 'Manifest supports root and subfolder installations.', false);
$add('Service worker', is_file(ROOT_PATH . '/service-worker.js'), 'Root service worker is present.', false);

if ($connected) {
    foreach (['security_rate_limits', 'permissions', 'role_permissions', 'password_reset_tokens'] as $table) {
        $add('Database table: ' . $table, Database::tableExists($table), Database::tableExists($table) ? 'Present.' : 'Import install/database_updates_v2.sql.', true);
    }
    $userColumns = Database::columns('users');
    $add('Session invalidation columns', in_array('auth_version', $userColumns, true) && in_array('password_changed_at', $userColumns, true) && in_array('must_change_password', $userColumns, true), 'users.auth_version, users.password_changed_at and users.must_change_password are required.', true);
}

foreach (['admin', 'vendor', 'customer', 'member', 'pos', 'api'] as $directory) {
    $count = count(glob(ROOT_PATH . '/' . $directory . '/*.php') ?: []);
    $add(ucfirst($directory) . ' pages', $count > 0, $count . ' PHP files found.');
}

$warnings = config_warnings();
$criticalFailures = count(array_filter($checks, static fn(array $check): bool => $check['critical'] && !$check['ok']));
require_once ROOT_PATH . '/app/Layouts/admin_header.php';
?>
<div class="d-flex justify-content-between align-items-start flex-wrap gap-3 mb-3"><div><h1 class="h3 mb-1">Control Panel Health Check</h1><p class="text-muted mb-0">Production configuration, security and server compatibility diagnostics.</p></div><span class="badge <?= $criticalFailures ? 'bg-danger' : 'bg-success' ?> fs-6"><?= $criticalFailures ? $criticalFailures . ' critical issue(s)' : 'Ready for workflow testing' ?></span></div>
<?php if ($warnings): ?><div class="alert alert-warning"><strong>Configuration warnings</strong><ul class="mb-0 mt-2"><?php foreach ($warnings as $warning): ?><li><?= e($warning) ?></li><?php endforeach; ?></ul></div><?php endif; ?>
<div class="card module-card"><div class="table-responsive"><table class="table mb-0 align-middle"><thead><tr><th>Check</th><th>Status</th><th>Detail</th></tr></thead><tbody><?php foreach ($checks as $check): ?><tr><td><?= e($check['name']) ?><?= $check['critical'] ? ' <span class="text-danger" title="Critical">*</span>' : '' ?></td><td><?= $check['ok'] ? '<span class="badge bg-success">OK</span>' : '<span class="badge bg-' . ($check['critical'] ? 'danger' : 'warning text-dark') . '">Needs attention</span>' ?></td><td><?= e($check['detail']) ?></td></tr><?php endforeach; ?></tbody></table></div></div>
<div class="alert alert-info mt-3 mb-0">Import <code>install/database_updates_v2.sql</code> after the previous migration. Production no longer permits database-offline demo login.</div>
<?php require_once ROOT_PATH . '/app/Layouts/admin_footer.php'; ?>
