<?php
declare(strict_types=1);

/**
 * Lightweight smoke test after deploy.
 * This intentionally checks boot/runtime pieces only, not business data.
 *
 * Usage:
 *   php scripts/step7_smoke_test.php
 */

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

$root = dirname(__DIR__);
$failed = false;

function smoke(bool $ok, string $message): void
{
    global $failed;
    echo '[' . ($ok ? 'OK' : 'FAIL') . '] ' . $message . PHP_EOL;
    if (!$ok) {
        $failed = true;
    }
}

smoke(is_file($root . '/index.php'), 'index.php exists');
smoke(is_file($root . '/login.php'), 'login.php exists');
smoke(is_file($root . '/logout.php'), 'logout.php exists');
smoke(is_file($root . '/config/env.php'), 'config/env.php exists');
smoke(is_file($root . '/config/database.php'), 'config/database.php exists');
smoke(is_file($root . '/app/core/bootstrap.php'), 'app/core/bootstrap.php exists');
smoke(is_file($root . '/modules/logbook_kpi/index.php'), 'logbook_kpi module entry exists');
smoke(is_file($root . '/modules/jadwal_jaga_poin/index.php'), 'jadwal_jaga_poin module entry exists');
smoke(is_file($root . '/modules/kegiatan_harian/index.php'), 'kegiatan_harian module entry exists');
smoke(is_file($root . '/modules/kumpulan_dokumen_laporan/index.php'), 'kumpulan_dokumen_laporan module entry exists');
smoke(is_file($root . '/modules/distribusi_alat/index.php'), 'distribusi_alat module entry exists');
smoke(is_file($root . '/uploads/.htaccess'), 'uploads protection exists');
smoke(is_file($root . '/storage/.htaccess'), 'storage protection exists');

$phpFiles = [
    'index.php',
    'login.php',
    'logout.php',
    'config/env.php',
    'config/database.php',
    'scripts/preflight.php',
    'scripts/deploy_ready.php',
];

foreach ($phpFiles as $relativePath) {
    $cmd = 'php -l ' . escapeshellarg($root . '/' . $relativePath) . ' 2>&1';
    exec($cmd, $output, $code);
    smoke($code === 0, "PHP lint {$relativePath}");
}

if ($failed) {
    echo PHP_EOL . "Smoke test FAILED.\n";
    exit(1);
}

echo PHP_EOL . "Smoke test PASS.\n";
