<?php
/**
 * Release check Step 6: lint cepat + environment + folder penting.
 * Jalankan sebelum merge develop -> main atau sebelum deploy production.
 */

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

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

check_line(is_file($root . '/.gitignore'), '.gitignore tersedia');
check_line(is_file($root . '/.cpanel.yml'), '.cpanel.yml tersedia');
check_line(is_file($root . '/.env.example'), '.env.example tersedia');
check_line(is_file($root . '/scripts/preflight.php'), 'preflight tersedia');
check_line(is_file($root . '/scripts/backup_database.php'), 'backup_database tersedia');
check_line(is_file($root . '/scripts/backup_files.php'), 'backup_files tersedia');
check_line(is_file($root . '/scripts/create_env.php'), 'create_env tersedia');
check_line(is_file($root . '/scripts/deploy_ready.php'), 'deploy_ready tersedia');
check_line(is_file($root . '/scripts/step7_smoke_test.php'), 'step7 smoke test tersedia');
check_line(is_file($root . '/scripts/setup_deploy_wizard.php'), 'setup deploy wizard tersedia');
check_line(is_file($root . '/scripts/cpanel_first_run.sh'), 'cPanel first run script tersedia');
check_line(is_file($root . '/docs/STAGING_TEST_PLAN.md'), 'staging test plan tersedia');
check_line(is_file($root . '/docs/STEP7_GITHUB_STAGING_IMPLEMENTATION.md'), 'step7 implementation guide tersedia');
check_line(is_file($root . '/docs/STEP8_DEPLOYMENT_KIT.md'), 'step8 deployment kit guide tersedia');
check_line(is_file($root . '/deploy/checklists/github-cpanel-step7.md'), 'github cPanel checklist tersedia');
check_line(is_file($root . '/deploy/checklists/staging-go-live-step8.md'), 'staging go live checklist tersedia');

$writableDirs = ['storage/logs', 'storage/cache', 'storage/exports', 'uploads'];
foreach ($writableDirs as $dir) {
    $path = $root . '/' . $dir;
    check_line(is_dir($path), "Folder {$dir} tersedia");
}

$phpFiles = [];
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS));
foreach ($iterator as $file) {
    $path = $file->getPathname();
    if (substr($path, -4) !== '.php') {
        continue;
    }
    if (strpos($path, DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR) !== false) {
        continue;
    }
    $phpFiles[] = $path;
}

$lintErrors = 0;
foreach ($phpFiles as $file) {
    $cmd = 'php -l ' . escapeshellarg($file) . ' 2>&1';
    exec($cmd, $output, $code);
    if ($code !== 0) {
        $lintErrors++;
        echo '[LINT FAIL] ' . str_replace($root . '/', '', $file) . PHP_EOL;
        echo implode(PHP_EOL, $output) . PHP_EOL;
    }
}
check_line($lintErrors === 0, 'PHP lint semua file source');

if ($failed) {
    echo PHP_EOL . 'Release check gagal. Perbaiki item FAIL sebelum production.' . PHP_EOL;
    exit(1);
}

echo PHP_EOL . 'Release check lulus.' . PHP_EOL;
