<?php
/**
 * Google Sheets Queue Monitor
 * Variables: $stats, $pending, $sent, $dead, $cronToken, $cronLastRun, $spreadsheetId, $sheetName
 */
$baseDir  = ROOT_PATH . '/storage/queue/gsheets';
$pendingDir = $baseDir . '/pending';
$sentDir    = $baseDir . '/sent';
$deadDir    = $baseDir . '/dead';

/* ── جمع الملفات ── */
$pendingFiles = glob($pendingDir . '/*.json') ?: [];
sort($pendingFiles);

$sentFiles = [];
foreach (glob($sentDir . '/*', GLOB_ONLYDIR) ?: [] as $monthDir) {
    foreach (glob($monthDir . '/*.json') ?: [] as $f) {
        $sentFiles[] = $f;
    }
}
rsort($sentFiles); // الأحدث أولاً
$sentFiles = array_slice($sentFiles, 0, 50); // آخر 50

$deadFiles = [];
foreach (glob($deadDir . '/*', GLOB_ONLYDIR) ?: [] as $monthDir) {
    foreach (glob($monthDir . '/*.json') ?: [] as $f) {
        $deadFiles[] = $f;
    }
}
rsort($deadFiles);

/* ── قراءة ملف JSON بأمان ── */
function readJob(string $path): array {
    $raw = @file_get_contents($path);
    return $raw ? (json_decode($raw, true) ?: []) : [];
}

/* ── إحصائيات ── */
$totalPending = count($pendingFiles);
$totalSent    = count($sentFiles);  // آخر 50 فقط للعرض
$totalDead    = count($deadFiles);

/* ── Cron info ── */
$settingsModel = new \Core\App\Models\Settings();
$cronToken   = $settingsModel->get('cron_token', '');
$cronLastRun = (int)$settingsModel->get('cron_last_run', 0);
$cronUrl     = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http')
             . '://' . ($_SERVER['HTTP_HOST'] ?? '') . '/cron/run?token=' . urlencode($cronToken);

$cronAgo   = $cronLastRun ? (time() - $cronLastRun) : null;
$cronOk    = $cronAgo !== null && $cronAgo < 180; // أقل من 3 دقائق = طبيعي
?>
<style>
.qm-page  { max-width:1100px; margin:0 auto; padding:24px 16px 56px; }
.qm-header{ display:flex; align-items:flex-start; justify-content:space-between; gap:16px; margin-bottom:28px; flex-wrap:wrap; }
.qm-title { font-size:20px; font-weight:800; color:#111827; margin:0; }
.qm-title small { font-size:14px; font-weight:500; color:#9ca3af; }

/* KPI cards */
.qm-kpis  { display:grid; grid-template-columns:repeat(auto-fit,minmax(160px,1fr)); gap:16px; margin-bottom:28px; }
.qm-kpi   { background:#fff; border:1.5px solid #e5e7eb; border-radius:14px; padding:18px 20px; position:relative; }
.qm-kpi-label { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.7px; color:#9ca3af; margin-bottom:6px; }
.qm-kpi-val   { font-size:32px; font-weight:900; line-height:1; }
.qm-kpi-sub   { font-size:11px; color:#9ca3af; margin-top:4px; }
.qm-kpi.pending { border-color:#fde68a; background:linear-gradient(135deg,#fffbeb,#fff); }
.qm-kpi.pending .qm-kpi-val { color:#d97706; }
.qm-kpi.sent    { border-color:#bbf7d0; background:linear-gradient(135deg,#f0fdf4,#fff); }
.qm-kpi.sent    .qm-kpi-val { color:#059669; }
.qm-kpi.dead    { border-color:#fecaca; background:linear-gradient(135deg,#fff1f2,#fff); }
.qm-kpi.dead    .qm-kpi-val { color:#dc2626; }
.qm-kpi.cron.ok   { border-color:#bbf7d0; background:linear-gradient(135deg,#f0fdf4,#fff); }
.qm-kpi.cron.late { border-color:#fecaca; background:linear-gradient(135deg,#fff1f2,#fff); }
.qm-kpi.cron.ok   .qm-kpi-val { color:#059669; font-size:20px; }
.qm-kpi.cron.late .qm-kpi-val { color:#dc2626; font-size:20px; }

/* Cron bar */
.qm-cron-bar { background:#fff; border:1.5px solid #e5e7eb; border-radius:14px; padding:16px 20px; margin-bottom:24px; display:flex; align-items:center; gap:16px; flex-wrap:wrap; }
.qm-cron-url { font-family:monospace; font-size:12px; background:#f3f4f6; padding:8px 12px; border-radius:8px; flex:1; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; color:#374151; border:1px solid #e5e7eb; }
.qm-cron-status { display:inline-flex; align-items:center; gap:6px; padding:5px 12px; border-radius:99px; font-size:12px; font-weight:700; white-space:nowrap; }
.qm-cron-ok   { background:#d1fae5; color:#065f46; }
.qm-cron-late { background:#fee2e2; color:#991b1b; }
.qm-cron-never{ background:#fef3c7; color:#92400e; }

/* Sections */
.qm-section { background:#fff; border:1.5px solid #e5e7eb; border-radius:14px; margin-bottom:20px; overflow:hidden; }
.qm-section-head { padding:14px 20px; border-bottom:1px solid #f3f4f6; display:flex; align-items:center; gap:10px; font-size:13px; font-weight:700; color:#374151; text-transform:uppercase; letter-spacing:.6px; }
.qm-section-head .cnt { margin-inline-start:auto; font-size:13px; font-weight:800; }

/* Table */
.qm-table { width:100%; border-collapse:collapse; font-size:13px; }
.qm-table th { padding:9px 16px; background:#f9fafb; color:#6b7280; font-weight:600; font-size:11px; text-transform:uppercase; letter-spacing:.4px; text-align:start; border-bottom:1.5px solid #e5e7eb; }
.qm-table td { padding:11px 16px; border-bottom:1px solid #f3f4f6; vertical-align:middle; color:#374151; }
.qm-table tr:last-child td { border-bottom:none; }
.qm-table tr:hover td { background:#fafafa; }

/* Badges */
.qb { display:inline-flex; align-items:center; gap:4px; padding:3px 9px; border-radius:99px; font-size:11px; font-weight:700; }
.qb-pending { background:#fef3c7; color:#92400e; border:1px solid #fde68a; }
.qb-sent    { background:#d1fae5; color:#065f46; border:1px solid #bbf7d0; }
.qb-dead    { background:#fee2e2; color:#991b1b; border:1px solid #fecaca; }
.qb-retry   { background:#e0e7ff; color:#3730a3; border:1px solid #c7d2fe; }

/* Error accordion */
.qm-err-toggle { cursor:pointer; color:#dc2626; font-size:11px; text-decoration:underline; white-space:nowrap; }
.qm-err-body   { display:none; font-size:11px; font-family:monospace; background:#fff1f2; padding:6px 10px; border-radius:6px; margin-top:6px; color:#991b1b; word-break:break-all; max-width:320px; }

/* Empty state */
.qm-empty { padding:32px; text-align:center; color:#9ca3af; }
.qm-empty i { font-size:36px; display:block; margin-bottom:8px; }

/* Run now button */
.qm-run-btn { position:relative; overflow:hidden; }
.qm-run-btn .spinner-border { width:14px; height:14px; }
</style>

<div class="qm-page">

    <!-- Header -->
    <div class="qm-header">
        <div>
            <h1 class="qm-title">
                <i class="bi bi-activity me-2 text-success"></i>
                <?= __('gsheets.monitor_title', 'Queue Monitor') ?>
                <small>— Google Sheets Export</small>
            </h1>
            <div class="text-muted small mt-1">
                <?= __('gsheets.monitor_subtitle', 'Track every order export — pending, sent, and failed') ?>
            </div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <button type="button" class="btn btn-success btn-sm qm-run-btn" id="runNowBtn" onclick="runCronNow()">
                <i class="bi bi-play-fill me-1"></i><?= __('gsheets.run_now', 'Run Now') ?>
            </button>
            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="location.reload()">
                <i class="bi bi-arrow-clockwise me-1"></i><?= __('actions.refresh', 'Refresh') ?>
            </button>
            <a href="/admin/settings/gsheets" class="btn btn-outline-secondary btn-sm">
                <i class="bi bi-gear me-1"></i><?= __('gsheets.settings', 'Settings') ?>
            </a>
        </div>
    </div>

    <!-- Run result -->
    <div id="runResult" class="d-none mb-3"></div>

    <!-- KPI Cards -->
    <div class="qm-kpis">
        <div class="qm-kpi pending">
            <div class="qm-kpi-label"><?= __('gsheets.mon_pending', 'Pending') ?></div>
            <div class="qm-kpi-val"><?= $totalPending ?></div>
            <div class="qm-kpi-sub"><?= __('gsheets.mon_pending_sub', 'waiting to be sent') ?></div>
        </div>
        <div class="qm-kpi sent">
            <div class="qm-kpi-label"><?= __('gsheets.mon_sent', 'Sent') ?></div>
            <div class="qm-kpi-val"><?= $totalSent ?></div>
            <div class="qm-kpi-sub"><?= __('gsheets.mon_sent_sub', 'last 50 shown') ?></div>
        </div>
        <div class="qm-kpi dead">
            <div class="qm-kpi-label"><?= __('gsheets.mon_failed', 'Failed') ?></div>
            <div class="qm-kpi-val"><?= $totalDead ?></div>
            <div class="qm-kpi-sub"><?= __('gsheets.mon_failed_sub', 'max retries reached') ?></div>
        </div>
        <?php
        $cronCls = $cronAgo === null ? 'cron late' : ($cronOk ? 'cron ok' : 'cron late');
        $cronVal = $cronAgo === null
            ? __('gsheets.mon_cron_never', 'Never')
            : ($cronAgo < 60 ? __('gsheets.mon_cron_now', 'Just now')
               : ($cronAgo < 3600 ? floor($cronAgo/60).'m' : floor($cronAgo/3600).'h'));
        ?>
        <div class="qm-kpi <?= $cronCls ?>">
            <div class="qm-kpi-label"><?= __('gsheets.mon_cron', 'Last Cron') ?></div>
            <div class="qm-kpi-val"><?= $cronVal ?></div>
            <div class="qm-kpi-sub"><?= $cronOk ? '✅ ' . __('gsheets.mon_cron_ok', 'Running normally') : '⚠️ ' . __('gsheets.mon_cron_late', 'Check cron setup') ?></div>
        </div>
        <div class="qm-kpi" style="border-color:#ddd6fe;background:linear-gradient(135deg,#f5f3ff,#fff)">
            <div class="qm-kpi-label"><?= __('gsheets.mon_target', 'Target Sheet') ?></div>
            <div style="font-size:13px;font-weight:700;color:#5b21b6;margin-top:4px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
                <?= $sheetName ?: '—' ?>
            </div>
            <div class="qm-kpi-sub" style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="<?= htmlspecialchars($spreadsheetId) ?>">
                <?= $spreadsheetId ? substr($spreadsheetId,0,20).'…' : __('gsheets.mon_not_set','Not configured') ?>
            </div>
        </div>
    </div>

    <!-- Cron URL bar -->
    <div class="qm-cron-bar">
        <i class="bi bi-clock-fill text-muted flex-shrink-0"></i>
        <div class="flex-grow-1 min-w-0">
            <div class="small fw-semibold mb-1"><?= __('gsheets.mon_cron_url', 'Cron URL — set this in your hosting panel to run every minute:') ?></div>
            <div class="qm-cron-url" id="cronUrlText"><?= htmlspecialchars($cronUrl) ?></div>
        </div>
        <button class="btn btn-outline-secondary btn-sm flex-shrink-0" onclick="copyCronUrl()">
            <i class="bi bi-clipboard me-1"></i><?= __('actions.copy', 'Copy') ?>
        </button>
        <?php if ($cronAgo !== null): ?>
        <div class="flex-shrink-0">
            <span class="qm-cron-status <?= $cronOk ? 'qm-cron-ok' : 'qm-cron-late' ?>">
                <i class="bi <?= $cronOk ? 'bi-check-circle-fill' : 'bi-exclamation-triangle-fill' ?>"></i>
                <?= $cronLastRun ? date('d/m H:i', $cronLastRun) : '—' ?>
            </span>
        </div>
        <?php else: ?>
        <span class="qm-cron-status qm-cron-never"><i class="bi bi-dash-circle"></i> <?= __('gsheets.mon_cron_never','Never ran') ?></span>
        <?php endif; ?>
    </div>

    <!-- ══ PENDING ══ -->
    <div class="qm-section">
        <div class="qm-section-head">
            <i class="bi bi-hourglass-split text-warning"></i>
            <?= __('gsheets.mon_pending', 'Pending') ?>
            <span class="qb qb-pending cnt"><?= $totalPending ?></span>
        </div>
        <?php if (empty($pendingFiles)): ?>
        <div class="qm-empty"><i class="bi bi-check2-circle text-success"></i><?= __('gsheets.mon_empty_pending', 'No pending orders — all sent ✅') ?></div>
        <?php else: ?>
        <div style="overflow-x:auto">
        <table class="qm-table">
            <thead>
                <tr>
                    <th><?= __('orders.id', '#') ?></th>
                    <th><?= __('orders.product_info', 'Product') ?></th>
                    <th><?= __('orders.full_name', 'Customer') ?></th>
                    <th><?= __('orders.phone', 'Phone') ?></th>
                    <th><?= __('orders.total', 'Total') ?></th>
                    <th><?= __('gsheets.mon_attempts', 'Attempts') ?></th>
                    <th><?= __('gsheets.mon_queued_at', 'Queued At') ?></th>
                    <th><?= __('gsheets.mon_last_error', 'Last Error') ?></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($pendingFiles as $file):
                $job = readJob($file);
                if (empty($job)) continue;
                $row = $job['row'] ?? [];
                $attempts = (int)($job['attempts'] ?? 0);
            ?>
            <tr>
                <td><a href="/admin/orders/view/<?= (int)($row['order_id'] ?? 0) ?>" class="fw-bold text-primary">#<?= (int)($row['order_id'] ?? 0) ?></a></td>
                <td><?= htmlspecialchars(mb_strimwidth($row['product_title'] ?? '—', 0, 30, '…')) ?></td>
                <td><?= htmlspecialchars($row['full_name'] ?? '—') ?></td>
                <td class="font-monospace"><?= htmlspecialchars($row['phone'] ?? '—') ?></td>
                <td class="fw-bold"><?= number_format((float)($row['total'] ?? 0)) ?></td>
                <td>
                    <?php if ($attempts === 0): ?>
                        <span class="qb qb-pending"><?= __('gsheets.mon_not_tried', 'Not tried') ?></span>
                    <?php else: ?>
                        <span class="qb qb-retry">↺ <?= $attempts ?></span>
                    <?php endif; ?>
                </td>
                <td class="text-muted"><?= htmlspecialchars($job['created_at'] ?? '—') ?></td>
                <td>
                    <?php if (!empty($job['last_error'])): ?>
                        <span class="qm-err-toggle" onclick="this.nextElementSibling.style.display=this.nextElementSibling.style.display==='none'?'block':'none'">
                            <i class="bi bi-exclamation-triangle me-1"></i><?= __('gsheets.mon_show_error', 'Show error') ?>
                        </span>
                        <div class="qm-err-body"><?= htmlspecialchars($job['last_error']) ?></div>
                    <?php else: ?>
                        <span class="text-muted">—</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>

    <!-- ══ SENT ══ -->
    <div class="qm-section">
        <div class="qm-section-head">
            <i class="bi bi-check-circle-fill text-success"></i>
            <?= __('gsheets.mon_sent', 'Sent Successfully') ?>
            <span class="qb qb-sent cnt"><?= $totalSent ?> <?= $totalSent >= 50 ? '(last 50)' : '' ?></span>
        </div>
        <?php if (empty($sentFiles)): ?>
        <div class="qm-empty"><i class="bi bi-inbox text-muted"></i><?= __('gsheets.mon_empty_sent', 'No sent records yet') ?></div>
        <?php else: ?>
        <div style="overflow-x:auto">
        <table class="qm-table">
            <thead>
                <tr>
                    <th><?= __('orders.id', '#') ?></th>
                    <th><?= __('orders.product_info', 'Product') ?></th>
                    <th><?= __('orders.full_name', 'Customer') ?></th>
                    <th><?= __('orders.phone', 'Phone') ?></th>
                    <th><?= __('orders.total', 'Total') ?></th>
                    <th><?= __('gsheets.mon_queued_at', 'Queued At') ?></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($sentFiles as $file):
                $job = readJob($file);
                if (empty($job)) continue;
                $row = $job['row'] ?? [];
            ?>
            <tr>
                <td><a href="/admin/orders/view/<?= (int)($row['order_id'] ?? 0) ?>" class="fw-bold text-success">#<?= (int)($row['order_id'] ?? 0) ?></a></td>
                <td><?= htmlspecialchars(mb_strimwidth($row['product_title'] ?? '—', 0, 30, '…')) ?></td>
                <td><?= htmlspecialchars($row['full_name'] ?? '—') ?></td>
                <td class="font-monospace"><?= htmlspecialchars($row['phone'] ?? '—') ?></td>
                <td class="fw-bold"><?= number_format((float)($row['total'] ?? 0)) ?></td>
                <td class="text-muted"><?= htmlspecialchars($job['created_at'] ?? '—') ?></td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>

    <!-- ══ DEAD / FAILED ══ -->
    <?php if (!empty($deadFiles)): ?>
    <div class="qm-section">
        <div class="qm-section-head" style="background:#fff1f2">
            <i class="bi bi-x-circle-fill text-danger"></i>
            <span style="color:#991b1b"><?= __('gsheets.mon_failed', 'Failed — Max Retries Reached') ?></span>
            <span class="qb qb-dead cnt"><?= $totalDead ?></span>
        </div>
        <div class="px-4 py-3">
            <div class="d-flex gap-2 align-items-center p-3 rounded-3" style="background:#fff1f2;border:1.5px solid #fecaca">
                <i class="bi bi-exclamation-triangle-fill text-danger fs-5 flex-shrink-0"></i>
                <div class="small">
                    <strong><?= __('gsheets.mon_dead_title', 'These orders failed to export after 12 attempts.') ?></strong>
                    <?= __('gsheets.mon_dead_hint', 'Check your Google Sheets connection and re-export them manually.') ?>
                </div>
            </div>
        </div>
        <div style="overflow-x:auto">
        <table class="qm-table">
            <thead>
                <tr>
                    <th><?= __('orders.id', '#') ?></th>
                    <th><?= __('orders.product_info', 'Product') ?></th>
                    <th><?= __('orders.full_name', 'Customer') ?></th>
                    <th><?= __('gsheets.mon_attempts', 'Attempts') ?></th>
                    <th><?= __('gsheets.mon_last_error', 'Last Error') ?></th>
                    <th><?= __('gsheets.mon_queued_at', 'Queued At') ?></th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($deadFiles as $file):
                $job = readJob($file);
                if (empty($job)) continue;
                $row = $job['row'] ?? [];
            ?>
            <tr>
                <td><a href="/admin/orders/view/<?= (int)($row['order_id'] ?? 0) ?>" class="fw-bold text-danger">#<?= (int)($row['order_id'] ?? 0) ?></a></td>
                <td><?= htmlspecialchars(mb_strimwidth($row['product_title'] ?? '—', 0, 28, '…')) ?></td>
                <td><?= htmlspecialchars($row['full_name'] ?? '—') ?></td>
                <td><span class="qb qb-dead">✗ <?= (int)($job['attempts'] ?? 0) ?></span></td>
                <td>
                    <?php if (!empty($job['last_error'])): ?>
                        <span class="qm-err-toggle" onclick="this.nextElementSibling.style.display=this.nextElementSibling.style.display==='none'?'block':'none'">
                            <i class="bi bi-bug me-1"></i><?= htmlspecialchars(mb_strimwidth($job['last_error'], 0, 30, '…')) ?>
                        </span>
                        <div class="qm-err-body"><?= htmlspecialchars($job['last_error']) ?></div>
                    <?php else: ?>—<?php endif; ?>
                </td>
                <td class="text-muted"><?= htmlspecialchars($job['created_at'] ?? '—') ?></td>
                <td>
                    <!-- إعادة المحاولة: نحرك الملف من dead إلى pending -->
                    <form method="POST" action="/admin/settings/gsheets/retry-job" style="display:inline">
                        <?= \Core\System\Csrf::field() ?>
                        <input type="hidden" name="filename" value="<?= htmlspecialchars(basename($file)) ?>">
                        <input type="hidden" name="month" value="<?= htmlspecialchars(basename(dirname($file))) ?>">
                        <button type="submit" class="btn btn-warning btn-sm py-0 px-2">
                            <i class="bi bi-arrow-clockwise me-1"></i><?= __('gsheets.mon_retry', 'Retry') ?>
                        </button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    </div>
    <?php endif; ?>

</div>

<script>
// ── Run Cron Now ──
async function runCronNow() {
    const btn = document.getElementById('runNowBtn');
    const res = document.getElementById('runResult');
    const orig = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span><?= __('gsheets.mon_running','Running...') ?>';
    res.className = 'd-none mb-3';
    try {
        const r = await fetch(<?= json_encode($cronUrl) ?>, { credentials: 'same-origin' });
        const d = await r.json();
        if (d.success) {
            const sent = d.sent ?? 0;
            const failed = d.failed ?? 0;
            res.className = 'mb-3 alert alert-success py-2 small';
            res.innerHTML = '<i class="bi bi-check-circle me-1"></i>'
                + '<?= __('gsheets.mon_run_done','Done') ?> — '
                + '<?= __('gsheets.mon_run_sent','Sent') ?>: <strong>' + sent + '</strong>'
                + (failed > 0 ? ' · <?= __('gsheets.mon_run_failed','Failed') ?>: <strong class="text-danger">' + failed + '</strong>' : '')
                + ' <a href="" class="ms-2 fw-semibold"><?= __('actions.refresh','Refresh') ?></a>';
        } else {
            res.className = 'mb-3 alert alert-warning py-2 small';
            res.innerHTML = '<i class="bi bi-exclamation-triangle me-1"></i>' + (d.error || d.reason || 'Unknown');
        }
    } catch(e) {
        res.className = 'mb-3 alert alert-danger py-2 small';
        res.innerHTML = '<i class="bi bi-x-circle me-1"></i>' + e.message;
    } finally {
        btn.disabled = false;
        btn.innerHTML = orig;
    }
}

// ── Copy Cron URL ──
function copyCronUrl() {
    const text = document.getElementById('cronUrlText').textContent;
    navigator.clipboard.writeText(text).then(() => {
        const btn = event.target.closest('button');
        const orig = btn.innerHTML;
        btn.innerHTML = '<i class="bi bi-check me-1"></i><?= __('actions.copied','Copied') ?>';
        setTimeout(() => btn.innerHTML = orig, 1800);
    });
}
</script>