<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/mailer.php';
auth_require_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $do = $_POST['do'] ?? '';
    $id = (int)($_POST['id'] ?? 0);

    if ($do === 'retry' && $id) {
        db_exec("UPDATE email_queue SET status='pending', scheduled_at=NOW(), attempts=0 WHERE id=:id", ['id'=>$id]);
        header('Location: email-queue.php?msg=requeued'); exit;
    }
    if ($do === 'cancel' && $id) {
        db_exec("UPDATE email_queue SET status='cancelled' WHERE id=:id AND status IN ('pending','failed')", ['id'=>$id]);
        header('Location: email-queue.php?msg=cancelled'); exit;
    }
    if ($do === 'process_now') {
        $r = email_process_queue(20);
        header('Location: email-queue.php?msg=processed&sent='.$r['sent'].'&failed='.$r['failed']); exit;
    }
}

$status_filter = $_GET['status'] ?? '';
$where  = '';
$params = [];
if (in_array($status_filter, ['pending','sending','sent','failed','cancelled'], true)) {
    $where = 'WHERE status=:s';
    $params['s'] = $status_filter;
}

$jobs = db_all("SELECT * FROM email_queue $where ORDER BY scheduled_at DESC, id DESC LIMIT 200", $params);
$counts = [];
foreach (db_all("SELECT status, COUNT(*) AS c FROM email_queue GROUP BY status") as $r) {
    $counts[$r['status']] = (int)$r['c'];
}

$page_title = 'Email Queue';
require __DIR__ . '/_guard.php';
?>

<style>
.atbl{width:100%;border-collapse:collapse;font-size:.85rem;}
.atbl th{padding:.55rem 1rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);text-align:left;white-space:nowrap;}
.atbl td{padding:.55rem 1rem;border-bottom:1px solid var(--line);vertical-align:top;}
.q-status{display:inline-block;padding:.15em .55em;border-radius:3px;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;}
.q-status-pending  {background:#fef3c7;color:#92400e;}
.q-status-sending  {background:#dbeafe;color:#1e40af;}
.q-status-sent     {background:#dcfce7;color:#166534;}
.q-status-failed   {background:#fee2e2;color:#991b1b;}
.q-status-cancelled{background:#e5e7eb;color:#374151;}
.ftab{display:inline-flex;align-items:center;gap:.4rem;padding:.3rem .85rem;border-radius:999px;font-size:.82rem;border:1px solid var(--line);text-decoration:none;color:var(--ink);}
.ftab.on{background:var(--brand-primary);color:#fff;border-color:var(--brand-primary);}
.ftab .cnt{background:rgba(0,0,0,.12);border-radius:999px;padding:.05em .45em;font-size:.78em;font-weight:700;}
</style>

<?php
$settings_section = 'email';
require __DIR__ . '/_settings_open.php';
?>

<div class="settings-page-head" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:1rem;">
    <div>
        <h1>Email Queue</h1>
        <p class="crumb">Pending and recent send jobs. Cron processes 20 every minute.</p>
    </div>
    <div style="display:flex;gap:.5rem;">
        <form method="post" style="display:inline;">
            <?= csrf_field() ?>
            <input type="hidden" name="do" value="process_now">
            <button type="submit" class="btn">Process now</button>
        </form>
        <a href="email-templates.php" class="btn btn-outline">Templates</a>
        <a href="email-log.php" class="btn btn-outline">Log</a>
    </div>
</div>

<?php if (isset($_GET['msg'])): ?>
    <?php
    $msgs = [
        'requeued' => 'Job re-queued — will be picked up on next cron run.',
        'cancelled'=> 'Job cancelled.',
        'processed'=> 'Processed: '.((int)($_GET['sent']??0)).' sent, '.((int)($_GET['failed']??0)).' failed.',
    ];
    $m = $msgs[$_GET['msg']] ?? '';
    if ($m): ?>
        <div class="alert alert-success" data-autohide><?= htmlspecialchars($m) ?></div>
    <?php endif; ?>
<?php endif; ?>

<div style="display:flex;gap:.5rem;flex-wrap:wrap;margin-bottom:1rem;">
    <a href="?status=" class="ftab <?= $status_filter===''?'on':'' ?>">All <span class="cnt"><?= array_sum($counts) ?></span></a>
    <?php foreach (['pending','sent','failed','cancelled'] as $st): ?>
        <a href="?status=<?= $st ?>" class="ftab <?= $status_filter===$st?'on':'' ?>">
            <?= ucfirst($st) ?> <span class="cnt"><?= $counts[$st] ?? 0 ?></span>
        </a>
    <?php endforeach; ?>
</div>

<?php if (empty($jobs)): ?>
    <div class="card"><p class="muted" style="margin:0;">No queued jobs.</p></div>
<?php else: ?>
<div class="card" style="padding:0;overflow:auto;">
    <table class="atbl">
        <thead>
            <tr>
                <th>When</th>
                <th>Template</th>
                <th>To</th>
                <th>Status</th>
                <th>Attempts</th>
                <th>Last error</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($jobs as $j): ?>
            <tr>
                <td style="white-space:nowrap;font-size:.78rem;color:var(--ink-muted);">
                    <?= htmlspecialchars(date('j M H:i', strtotime($j['scheduled_at']))) ?>
                </td>
                <td><code style="font-size:.78rem;"><?= htmlspecialchars($j['template_slug']) ?></code></td>
                <td><?= htmlspecialchars($j['to_email']) ?></td>
                <td>
                    <span class="q-status q-status-<?= htmlspecialchars($j['status']) ?>">
                        <?= htmlspecialchars($j['status']) ?>
                    </span>
                </td>
                <td><?= $j['attempts'] ?> / <?= $j['max_attempts'] ?></td>
                <td style="font-size:.78rem;color:var(--ink-muted);max-width:340px;">
                    <?= htmlspecialchars(mb_substr($j['last_error'] ?? '', 0, 200)) ?>
                </td>
                <td style="text-align:right;white-space:nowrap;">
                    <?php if ($j['status'] === 'failed' || $j['status'] === 'cancelled'): ?>
                        <form method="post" style="display:inline;">
                            <?= csrf_field() ?>
                            <input type="hidden" name="do" value="retry">
                            <input type="hidden" name="id" value="<?= $j['id'] ?>">
                            <button type="submit" style="background:none;border:none;color:var(--brand-primary);cursor:pointer;font-size:.85rem;font-family:inherit;">Retry</button>
                        </form>
                    <?php elseif ($j['status'] === 'pending'): ?>
                        <form method="post" style="display:inline;" onsubmit="return confirm('Cancel this email?');">
                            <?= csrf_field() ?>
                            <input type="hidden" name="do" value="cancel">
                            <input type="hidden" name="id" value="<?= $j['id'] ?>">
                            <button type="submit" style="background:none;border:none;color:#b91c1c;cursor:pointer;font-size:.85rem;font-family:inherit;">Cancel</button>
                        </form>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<?php require __DIR__ . '/_settings_close.php'; ?>

<?php require __DIR__ . '/_footer.php'; ?>