<?php
// ─────────────────────────────────────────────
// api/mails.php
// Liste aller versendeten Mails aus mail_log,
// mit JOIN auf clients für Klient-Namen.
//
// GET  /api/mails             → letzte 100 Mails
// GET  /api/mails?status=sent → gefiltert
// ─────────────────────────────────────────────

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';

c2c_cors_headers();
require_api_token();

$pdo = C2CDatabase::get();

$status = $_GET['status'] ?? null;

$sql = "
    SELECT m.id, m.client_id, m.to_email, m.to_name, m.subject,
           m.template, m.status, m.error, m.sent_at, m.created_at,
           c.vorname, c.nachname, c.status AS client_status
      FROM mail_log m
      LEFT JOIN clients c ON c.id = m.client_id
";

$params = [];
if ($status && in_array($status, ['queued','sent','failed'], true)) {
    $sql .= " WHERE m.status = ?";
    $params[] = $status;
}

$sql .= " ORDER BY m.created_at DESC LIMIT 200";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$mails = $stmt->fetchAll();

// Counts für Badge / Übersicht
$countStmt = $pdo->query("
    SELECT status, COUNT(*) AS n FROM mail_log GROUP BY status
");
$counts = ['queued' => 0, 'sent' => 0, 'failed' => 0];
foreach ($countStmt->fetchAll() as $row) {
    $counts[$row['status']] = (int)$row['n'];
}

ok([
    'mails'  => $mails,
    'counts' => $counts,
]);
