<?php
/**
 * Lightweight healthcheck untuk staging/production.
 * Jalankan via browser atau CLI:
 *   php scripts/healthcheck.php
 *
 * Untuk keamanan, browser access dibatasi dengan token HEALTHCHECK_TOKEN di .env.
 * Contoh URL: /scripts/healthcheck.php?token=ISI_TOKEN
 */

require_once __DIR__ . '/../config/env.php';

$isCli = PHP_SAPI === 'cli';
$token = env('HEALTHCHECK_TOKEN', '');

if (!$isCli) {
    header('Content-Type: application/json; charset=utf-8');
    if ($token !== '') {
        $given = $_GET['token'] ?? '';
        if (!hash_equals($token, $given)) {
            http_response_code(403);
            echo json_encode(['ok' => false, 'error' => 'Forbidden'], JSON_PRETTY_PRINT);
            exit;
        }
    }
}

$result = [
    'ok' => true,
    'app_env' => env('APP_ENV', 'unknown'),
    'app_url' => env('APP_URL', ''),
    'php_version' => PHP_VERSION,
    'checks' => [],
];

function add_check(array &$result, string $name, bool $ok, string $message = ''): void
{
    $result['checks'][$name] = [
        'ok' => $ok,
        'message' => $message,
    ];
    if (!$ok) {
        $result['ok'] = false;
    }
}

add_check($result, 'env_file', file_exists(__DIR__ . '/../.env'), '.env harus ada di staging/production');
add_check($result, 'mysqli_extension', extension_loaded('mysqli'), 'Extension mysqli diperlukan');
add_check($result, 'pdo_mysql_extension', extension_loaded('pdo_mysql'), 'Extension pdo_mysql diperlukan untuk migration');
add_check($result, 'storage_writable', is_writable(__DIR__ . '/../storage'), 'Folder storage harus writable');
add_check($result, 'uploads_writable', is_writable(__DIR__ . '/../uploads'), 'Folder uploads harus writable');

$dbHost = env('DB_HOST', '');
$dbName = env('DB_NAME', '');
$dbUser = env('DB_USER', '');
$dbPass = env('DB_PASS', '');

if ($dbHost && $dbName && $dbUser) {
    try {
        $mysqli = @new mysqli($dbHost, $dbUser, $dbPass, $dbName);
        if ($mysqli->connect_errno) {
            add_check($result, 'database_connection', false, $mysqli->connect_error);
        } else {
            add_check($result, 'database_connection', true, 'Connected');
            $mysqli->close();
        }
    } catch (Throwable $e) {
        add_check($result, 'database_connection', false, $e->getMessage());
    }
} else {
    add_check($result, 'database_connection', false, 'DB_HOST/DB_NAME/DB_USER belum lengkap');
}

$output = json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
if ($isCli) {
    echo $output . PHP_EOL;
    exit($result['ok'] ? 0 : 1);
}

echo $output;
