<?php
declare(strict_types=1);

/**
 * Preflight check untuk staging/production.
 * Jalankan dari root project:
 *   php scripts/preflight.php
 */

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    echo "403 Forbidden\n";
    exit(1);
}

$root = dirname(__DIR__);
require_once $root . '/config/env.php';

$checks = [];
$fail = false;

$add = function (string $name, bool $ok, string $message = '') use (&$checks, &$fail): void {
    $checks[] = [$name, $ok, $message];
    if (!$ok) {
        $fail = true;
    }
};

$add('PHP >= 8.0', version_compare(PHP_VERSION, '8.0.0', '>='), PHP_VERSION);
$add('Extension mysqli', extension_loaded('mysqli'));
$add('Extension PDO', extension_loaded('PDO'));
$add('Extension pdo_mysql', extension_loaded('pdo_mysql'));
$add('Extension mbstring', extension_loaded('mbstring'));
$add('File .env tersedia', is_file($root . '/.env'));
$add('storage/logs writable', is_writable($root . '/storage/logs'));
$add('storage/cache writable', is_writable($root . '/storage/cache'));
$add('storage/exports writable', is_writable($root . '/storage/exports'));
$add('uploads writable', is_writable($root . '/uploads'));

$dbReady = false;
$dbMessage = '';
try {
    require_once $root . '/config/database.php';
    $conn = getAppConnection();
    $dbReady = $conn instanceof mysqli;
    $dbMessage = DB_NAME;
} catch (Throwable $e) {
    $dbMessage = $e->getMessage();
}
$add('Koneksi database aplikasi', $dbReady, $dbMessage);

foreach ($checks as [$name, $ok, $message]) {
    echo ($ok ? '[OK]   ' : '[FAIL] ') . $name;
    if ($message !== '') {
        echo ' - ' . $message;
    }
    echo PHP_EOL;
}

exit($fail ? 1 : 0);
