<?php
$page_title = 'Mailchimp log';
require __DIR__ . '/_guard.php';

$q      = trim($_GET['q'] ?? '');
$event  = $_GET['event'] ?? '';
$status = $_GET['status'] ?? '';
$date   = $_GET['date']   ?? '';

$where  = ['1=1'];
$params = [];
if ($q!=='')       { $where[]="email LIKE :q"; $params['q']='%'.$q.'%'; }
if ($event!=='')   { $where[]="event=:e"; $params['e']=$event; }
if ($status==='ok')   $where[]="success=1";
if ($status==='fail') $where[]="success=0";
if ($date!=='')    { $where[]="DATE(created_at)=:d"; $params['d']=$date; }

$rows = db_all(
    'SELECT * FROM mailchimp_sync_log WHERE '.implode(' AND ',$where).
    ' ORDER BY created_at DESC LIMIT 500',
    $params
);

$event_types = db_all(
    'SELECT event, COUNT(*) AS c, SUM(success) AS ok FROM mailchimp_sync_log GROUP BY event ORDER BY c DESC'
);

$total   = (int)db_value('SELECT COUNT(*) FROM mailchimp_sync_log');
$fails   = (int)db_value('SELECT COUNT(*) FROM mailchimp_sync_log WHERE success=0');
$today   = (int)db_value('SELECT COUNT(*) FROM mailchimp_sync_log WHERE DATE(created_at)=CURDATE()');
?>

<style>
.atbl{width:100%;border-collapse:collapse;font-size:.875rem;}
.atbl th{padding:.55rem .9rem;background:var(--surface-alt);font-size:.72rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);white-space:nowrap;text-align:left;}
.atbl td{padding:.6rem .9rem;border-bottom:1px solid var(--line);vertical-align:middle;}
.atbl tr:last-child td{border-bottom:none;}
.atbl tbody tr:hover td{background:var(--surface-alt);}
.atbl tr.is-fail td{background:#fff8f8;}
.s-stat{background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1rem;text-align:center;}
.s-stat .lbl{font-size:.72rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);margin:0 0 .2rem;}
.s-stat .val{font-size:1.6rem;font-weight:800;line-height:1.1;margin:0;}
</style>

<section class="section">
<div class="container">

<h1 style="margin:0 0 1.25rem;">Mailchimp sync log</h1>

<!-- Stats -->
<div style="display:grid;grid-template-columns:repeat(4,1fr);gap:.9rem;margin-bottom:1.5rem;">
    <div class="s-stat">
        <p class="lbl">Total events</p><p class="val"><?= $total ?></p>
    </div>
    <div class="s-stat">
        <p class="lbl">Today</p><p class="val"><?= $today ?></p>
    </div>
    <div class="s-stat">
        <p class="lbl">Failures</p>
        <p class="val" style="color:<?= $fails>0?'var(--brand-accent)':'inherit' ?>;"><?= $fails ?></p>
    </div>
    <div class="s-stat">
        <p class="lbl">Success rate</p>
        <p class="val" style="color:var(--brand-primary);">
            <?= $total>0 ? round(($total-$fails)/$total*100).'%' : '—' ?>
        </p>
    </div>
</div>

<!-- Filter form -->
<form method="get" style="display:flex;gap:.5rem;margin-bottom:1.1rem;flex-wrap:wrap;">
    <input type="search" name="q" value="<?= htmlspecialchars($q) ?>"
           placeholder="Search email…" style="flex:1;min-width:180px;">
    <select name="event" style="width:180px;">
        <option value="">Any event</option>
        <?php foreach ($event_types as $e): ?>
            <option value="<?= htmlspecialchars($e['event']) ?>" <?= $event===$e['event']?'selected':'' ?>>
                <?= htmlspecialchars($e['event']) ?> (<?= $e['c'] ?>)
            </option>
        <?php endforeach; ?>
    </select>
    <select name="status" style="width:120px;">
        <option value="">Any status</option>
        <option value="ok"   <?= $status==='ok'?'selected':'' ?>>Success only</option>
        <option value="fail" <?= $status==='fail'?'selected':'' ?>>Failures only</option>
    </select>
    <input type="date" name="date" value="<?= htmlspecialchars($date) ?>" style="width:150px;">
    <button type="submit" class="btn">Filter</button>
    <?php if ($q||$event||$status||$date): ?>
        <a href="mailchimp-log.php" class="btn btn-outline">Clear</a>
    <?php endif; ?>
</form>

<?php if (empty($rows)): ?>
    <div class="card"><p class="muted" style="margin:0;">No log entries match your filter.</p></div>
<?php else: ?>
<div class="card" style="padding:0;overflow:auto;">
    <table class="atbl">
        <thead>
            <tr>
                <th>Time</th>
                <th>Email</th>
                <th>Event</th>
                <th>Result</th>
                <th>Detail</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($rows as $r): ?>
            <tr class="<?= $r['success']?'':'is-fail' ?>">
                <td class="muted" style="white-space:nowrap;">
                    <?= date('j M H:i:s', strtotime($r['created_at'])) ?>
                </td>
                <td><?= htmlspecialchars($r['email']??'') ?></td>
                <td><code style="font-size:.8rem;"><?= htmlspecialchars($r['event']) ?></code></td>
                <td>
                    <?php if ($r['success']): ?>
                        <span class="tag tag-ok">ok</span>
                    <?php else: ?>
                        <span class="tag tag-err">fail</span>
                    <?php endif; ?>
                </td>
                <td style="font-size:.8rem;color:var(--ink-muted);">
                    <?= $r['detail'] ? htmlspecialchars($r['detail']) : '' ?>
                </td>
                <td>
                    <?php if ($r['member_id']): ?>
                        <a href="member-edit.php?id=<?= $r['member_id'] ?>" style="font-size:.82rem;">member →</a>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<p class="muted" style="font-size:.8rem;margin:.5rem 0 0;"><?= count($rows) ?> result<?= count($rows)===1?'':'s' ?>.</p>
<?php endif; ?>

</div>
</section>
<?php require __DIR__ . '/_footer.php'; ?>