<?php
declare(strict_types=1);

require __DIR__ . '/common.php';

$token = trim((string)($_GET['token'] ?? ''));
$env = gobao_load_env();
$adminToken = trim((string)($env['GOBAO_ADMIN_TOKEN'] ?? ''));
$hasAdminToken = $adminToken === '' || hash_equals($adminToken, $token);

$dataDir = gobao_data_dir();
$dbPath = gobao_db_path();
if ($hasAdminToken && !is_dir($dataDir)) {
    @mkdir($dataDir, 0775, true);
}
if ($hasAdminToken) {
    @chmod($dataDir, 0775);
}
if ($hasAdminToken && is_file($dbPath)) {
    @chmod($dbPath, 0664);
}

$probePath = $dataDir . '/write-test-' . bin2hex(random_bytes(4)) . '.tmp';
$dirWritable = is_dir($dataDir) && is_writable($dataDir);
$dirWriteTest = null;
if ($hasAdminToken) {
    $dirWriteTest = @file_put_contents($probePath, 'ok', LOCK_EX) !== false;
    if (is_file($probePath)) {
        @unlink($probePath);
    }
}

$dbWritable = !is_file($dbPath) || is_writable($dbPath);
$db = $hasAdminToken ? gobao_db() : null;
$dbOk = $db instanceof PDO;
$writeOk = null;
$writeError = '';
if ($dbOk) {
    try {
        $db->exec('CREATE TABLE IF NOT EXISTS repair_checks(id INTEGER PRIMARY KEY AUTOINCREMENT, created_at TEXT NOT NULL)');
        $stmt = $db->prepare('INSERT INTO repair_checks(created_at) VALUES(:created_at)');
        $stmt->execute([':created_at' => gmdate('c')]);
        $writeOk = true;
    } catch (Throwable $e) {
        $writeError = $e->getMessage();
    }
}

gobao_ok([
    'repair' => [
        'mode' => $hasAdminToken ? 'admin-repair-and-write-test' : 'public-readonly-check',
        'adminTokenRequiredForWriteTest' => !$hasAdminToken,
        'dataDir' => $dataDir,
        'dataDirWritable' => $dirWritable,
        'dataDirWriteTest' => $dirWriteTest,
        'dbPath' => $dbPath,
        'dbExists' => is_file($dbPath),
        'dbWritable' => $dbWritable,
        'dbConnected' => $dbOk,
        'dbWriteTest' => $writeOk,
        'error' => $writeError !== '' ? $writeError : gobao_db_last_error(),
        'nextStep' => $hasAdminToken
            ? 'If dbWriteTest is false, fix BaoTa owner/permission for api/data and gobao.sqlite.'
            : 'This is readonly diagnosis only. To run write test, open repair.php?token=YOUR_GOBAO_ADMIN_TOKEN or fix BaoTa permissions manually.',
        'baotaFix' => [
            'directory' => '/www/wwwroot/gobao.veigo1.top/api/data',
            'owner' => 'www',
            'directoryPermission' => '755 or 775',
            'sqlitePermission' => '664',
        ],
    ],
]);
