<?php
declare(strict_types=1);

/**
 * sync_dashboard.php
 *
 * Dashboard GUI untuk:
 * - jalankan AI mode
 * - lihat log file
 * - lihat status file sync utama
 */

error_reporting(E_ALL);
ini_set('display_errors', '1');
set_time_limit(300);

$baseDir = __DIR__;
$aiModeFile = $baseDir . '/sync_ai_mode.php';
$aiModeUrl = 'https://info-angkajitu.com/sync_ai_mode.php';

$filesToCheck = [
    'sync_ai_mode.php',
    'sync_prediksi_pro.php',
    'sync_result_pro.php',
    'sync_ai_mode.log',
    'sync_ai_mode.lock',
];

function h(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}

function readTail(string $path, int $maxLines = 80): string
{
    if (!file_exists($path)) {
        return 'Log file belum ada.';
    }

    $lines = @file($path, FILE_IGNORE_NEW_LINES);
    if ($lines === false) {
        return 'Gagal membaca log file.';
    }

    $lines = array_slice($lines, -$maxLines);
    return implode("\n", $lines);
}

function getFileStatus(string $baseDir, string $name): array
{
    $full = $baseDir . '/' . $name;
    return [
        'name' => $name,
        'exists' => file_exists($full),
        'size' => file_exists($full) ? filesize($full) : null,
        'mtime' => file_exists($full) ? date('Y-m-d H:i:s', filemtime($full)) : null,
        'path' => $full,
    ];
}

function runAiModeLocally(string $file, bool $purge = true): array
{
    if (!file_exists($file)) {
        return [
            'ok' => false,
            'output' => 'sync_ai_mode.php tidak ditemukan.'
        ];
    }

    $cmd = 'php ' . escapeshellarg($file) . ($purge ? ' --purge=1' : ' --purge=0') . ' 2>&1';
    $output = shell_exec($cmd);

    return [
        'ok' => $output !== null,
        'output' => $output ?? 'Tidak ada output'
    ];
}

$actionOutput = null;
$actionLabel = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'run_ai_mode') {
        $purge = ($_POST['purge'] ?? '1') === '1';
        $res = runAiModeLocally($aiModeFile, $purge);
        $actionLabel = 'Run AI Mode';
        $actionOutput = $res['output'];
    }
}

$statuses = array_map(fn($f) => getFileStatus($baseDir, $f), $filesToCheck);
$logContent = readTail($baseDir . '/sync_ai_mode.log', 100);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sync Dashboard</title>
    <style>
        body{margin:0;font-family:Arial,sans-serif;background:#081226;color:#e5e7eb}
        .wrap{max-width:1200px;margin:0 auto;padding:24px}
        .grid{display:grid;grid-template-columns:1.1fr 0.9fr;gap:20px}
        .card{background:#0d1b34;border:1px solid #27406f;border-radius:16px;padding:20px;margin-bottom:20px}
        h1,h2,h3{margin-top:0}
        .btn{display:inline-block;background:#22c55e;color:#052e16;border:0;border-radius:12px;padding:12px 16px;font-weight:bold;cursor:pointer;text-decoration:none}
        .btn-secondary{background:#1d4ed8;color:#fff}
        .muted{color:#93c5fd;font-size:14px}
        pre{white-space:pre-wrap;word-break:break-word;background:#030712;border:1px solid #334155;padding:14px;border-radius:12px;max-height:420px;overflow:auto}
        table{width:100%;border-collapse:collapse}
        th,td{border-bottom:1px solid #223a6b;padding:10px;text-align:left;vertical-align:top}
        th{color:#93c5fd}
        .pill{display:inline-block;padding:4px 10px;border-radius:999px;font-size:12px;font-weight:bold}
        .ok{background:#14532d;color:#dcfce7}
        .bad{background:#7f1d1d;color:#fee2e2}
        label{display:block;margin-bottom:8px}
        .row{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
        @media (max-width:980px){.grid{grid-template-columns:1fr}}
    </style>
</head>
<body>
<div class="wrap">
    <div class="card">
        <h1>Sync Dashboard</h1>
        <p class="muted">Panel sederhana untuk menjalankan AI Mode, cek file utama, dan lihat log sinkronisasi.</p>
        <div class="row">
            <a class="btn btn-secondary" href="<?= h($aiModeUrl) ?>" target="_blank">Buka AI Mode JSON</a>
            <a class="btn btn-secondary" href="<?= h($aiModeUrl) ?>?force=1&amp;marker=1&amp;purge=1" target="_blank">Buka AI Mode Full</a>
        </div>
    </div>

    <div class="grid">
        <div>
            <div class="card">
                <h2>Run AI Mode</h2>
                <form method="post">
                    <input type="hidden" name="action" value="run_ai_mode">
                    <label>
                        <input type="checkbox" name="purge" value="1" checked>
                        Purge cache setelah sync
                    </label>
                    <button class="btn" type="submit">Jalankan Sekarang</button>
                </form>
            </div>

            <?php if ($actionOutput !== null): ?>
            <div class="card">
                <h2><?= h($actionLabel ?? 'Output') ?></h2>
                <pre><?= h($actionOutput) ?></pre>
            </div>
            <?php endif; ?>

            <div class="card">
                <h2>Log AI Mode</h2>
                <pre><?= h($logContent) ?></pre>
            </div>
        </div>

        <div>
            <div class="card">
                <h2>Status File Utama</h2>
                <table>
                    <thead>
                        <tr>
                            <th>File</th>
                            <th>Status</th>
                            <th>Ukuran</th>
                            <th>Modified</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($statuses as $row): ?>
                        <tr>
                            <td>
                                <strong><?= h($row['name']) ?></strong><br>
                                <span class="muted"><?= h($row['path']) ?></span>
                            </td>
                            <td>
                                <?php if ($row['exists']): ?>
                                    <span class="pill ok">ADA</span>
                                <?php else: ?>
                                    <span class="pill bad">TIDAK ADA</span>
                                <?php endif; ?>
                            </td>
                            <td><?= $row['size'] !== null ? h((string)$row['size']) . ' bytes' : '-' ?></td>
                            <td><?= $row['mtime'] !== null ? h($row['mtime']) : '-' ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="card">
                <h2>Workflow</h2>
                <p class="muted">
                    1. Klik Jalankan Sekarang.<br>
                    2. Cek output JSON atau log.<br>
                    3. Kalau perlu, buka AI Mode Full untuk force sync + marker + purge.
                </p>
            </div>
        </div>
    </div>
</div>
</body>
</html>
