<?php 
/**
 * admin/smtp_domain_stats.php
 * ------------------------------------------------------------------
 * Live-Versandstatistik für die letzten 20 Minuten
 *  • pro Domain/Sender-Regel und pro SMTP-Global-Limit
 *  • zusätzlich: Gesamt-E-Mails der letzten 20 Minuten
 *  • Filtermöglichkeit nach SMTP-Account
 * ------------------------------------------------------------------
 */

session_start();
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../auth/AuthController.php';

$auth = new AuthController();
if (!$auth->isLoggedIn()) {
    header('Location: ' . $adminLoginPath);
    exit;
}

$db = Database::getInstance();

/* ======================================================================
 * 1) SMTP-Auswahl vorbereiten
 * ==================================================================== */
try {
    $smtpStmt = $db->query("SELECT id, smtp_user FROM smtp_accounts ORDER BY smtp_user");
    $smtpAccounts = $smtpStmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('smtp_domain_stats | file: ' . __FILE__ . ' | message: SMTP-Liste geladen');
} catch (PDOException $e) {
    ErrorLogger::logSqlError('smtp_domain_stats | file: ' . __FILE__ . ' | error: SMTP_LIST_ERR: ' . $e->getMessage());
    $smtpAccounts = [];
}

// Aktuell ausgewählter SMTP (falls gesetzt)
$selectedSmtpId = isset($_GET['smtp_id']) ? (int)$_GET['smtp_id'] : 0;

/* ======================================================================
 * 2) Detail-Statistik (Domains + Global-Limits) mit optionalem Filter
 * ==================================================================== */
try {
    // Bedingung für Filter
    $smtpFilter = $selectedSmtpId > 0 ? "WHERE s.id = :smtp_id" : "";

    $sql = "
        SELECT r.domain, s.smtp_user, COALESCE(COUNT(l.id),0) AS anzahl, r.max_per_20min AS limit_regel
        FROM smtp_domain_rules r
        JOIN smtp_accounts s ON s.id = r.smtp_account_id
        LEFT JOIN smtp_domain_sendlog l
            ON l.domain = r.domain
            AND l.smtp_id = r.smtp_account_id
            AND l.sent_at >= (NOW() - INTERVAL 20 MINUTE)
        $smtpFilter
        GROUP BY r.domain, r.smtp_account_id, s.smtp_user, r.max_per_20min

        UNION ALL

        SELECT '(keine Regel)' AS domain, s.smtp_user, COUNT(l.id) AS anzahl, s.max_global_20min AS limit_regel
        FROM smtp_accounts s
        LEFT JOIN smtp_domain_sendlog l
            ON l.smtp_id = s.id
            AND l.sent_at >= (NOW() - INTERVAL 20 MINUTE)
            AND l.domain NOT IN (SELECT domain FROM smtp_domain_rules)
        " . ($selectedSmtpId > 0 ? "WHERE s.id = :smtp_id" : "") . "
        GROUP BY s.id, s.smtp_user, s.max_global_20min

        ORDER BY domain, smtp_user
    ";

    $stmt = $db->prepare($sql);

    if ($selectedSmtpId > 0) {
        $stmt->bindValue(':smtp_id', $selectedSmtpId, PDO::PARAM_INT);
    }

    $stmt->execute();
    $stats = $stmt->fetchAll(PDO::FETCH_ASSOC);

    ErrorLogger::logSqlSuccess('smtp_domain_stats | file: ' . __FILE__ . ' | message: Detail-Statistik geladen mit Filter SMTP_ID=' . $selectedSmtpId);
} catch (PDOException $e) {
    ErrorLogger::logSqlError('smtp_domain_stats | file: ' . __FILE__ . ' | error: STAT_QUERY_ERR: ' . $e->getMessage());
    $stats = [];
}

/* ======================================================================
 * 3) Gesamtanzahl der E-Mails (ungefiltert)
 * ==================================================================== */
try {
    $totalStmt = $db->prepare("
        SELECT COUNT(*) AS total
        FROM smtp_domain_sendlog
        WHERE sent_at >= (NOW() - INTERVAL 20 MINUTE)
    ");
    $totalStmt->execute();
    $totalSent20 = (int)$totalStmt->fetchColumn();

    ErrorLogger::logSqlSuccess('smtp_domain_stats | file: ' . __FILE__ . ' | message: Gesamt-Versandzahl geladen');
} catch (PDOException $e) {
    ErrorLogger::logSqlError('smtp_domain_stats | file: ' . __FILE__ . ' | error: TOTAL_QUERY_ERR: ' . $e->getMessage());
    $totalSent20 = 0;
}

/* ======================================================================
 * 4) HTML-Ausgabe
 * ==================================================================== */
ob_start();
?>
<div class="container mt-4">
    <h2>
        <i class="bi bi-graph-up"></i>
        Live-Versandstatistik (20 Min)
        <span class="badge bg-primary ms-2" title="Alle SMTPs & Domains">
            <?= number_format($totalSent20, 0, ',', '.') ?> Gesamt
        </span>
    </h2>

    <form method="get" class="mb-3">
        <label for="smtp_id" class="form-label"><i class="bi bi-funnel"></i> SMTP-Account auswählen:</label>
        <div class="input-group">
            <select name="smtp_id" id="smtp_id" class="form-select" onchange="this.form.submit()">
                <option value="0">Alle SMTPs anzeigen</option>
                <?php foreach ($smtpAccounts as $smtp): ?>
                    <option value="<?= $smtp['id'] ?>" <?= $smtp['id'] == $selectedSmtpId ? 'selected' : '' ?>>
                        <?= htmlspecialchars($smtp['smtp_user']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="btn btn-outline-secondary"><i class="bi bi-search"></i> Filtern</button>
        </div>
    </form>

    <?php if (!$stats): ?>
        <div class="alert alert-info">Keine Daten gefunden.</div>
    <?php else: ?>
        <table class="table table-sm table-bordered align-middle">
            <thead class="table-light">
                <tr>
                    <th>Domain</th>
                    <th>SMTP-User</th>
                    <th>Gesendet</th>
                    <th>Limit (20 Min)</th>
                    <th>Auslastung</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($stats as $row):
                $limit   = $row['limit_regel'] ?: '∞';
                $usageP  = (is_numeric($row['limit_regel']) && $row['limit_regel'] > 0)
                           ? round($row['anzahl'] / $row['limit_regel'] * 100)
                           : 0;
                $badge   = $usageP >= 90 ? 'bg-danger'
                          : ($usageP >= 50 ? 'bg-warning' : 'bg-success');
            ?>
                <tr>
                    <td><?= htmlspecialchars($row['domain']) ?></td>
                    <td><?= htmlspecialchars($row['smtp_user']) ?></td>
                    <td><?= (int) $row['anzahl'] ?></td>
                    <td><?= $limit ?></td>
                    <td><span class="badge <?= $badge ?>"><?= $usageP ?> %</span></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<?php
$pageContent = ob_get_clean();
include_once __DIR__ . '/template.php';
?>
