<?php
/**
 * admin/statistics/statistics.php
 *
 * Statistik-Dashboard (UI)
 * - Zeitraumfilter
 * - Filter nach Kampagne/Liste (optional)
 * - KPI-Kacheln
 * - Chart 1: Verlauf pro Tag
 * - Chart 2: Stundenverteilung 00-23
 * - HEATMAP: Wochentag x Stunde (Opens unique / Klicks unique)
 *
 * WICHTIG:
 * - Keine "Delete"-Statistik: Geloeschte Empfaenger existieren nicht mehr -> OK laut Vorgabe.
 * - Chart-Fix: feste Wrapper-Hoehen verhindern endloses "Runterwachsen" (Chart.js Resize Loop).
 */

// ------------------------------------------------------------
// Session / Init / Auth (Standard MR9)
// ------------------------------------------------------------
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();
$title = 'Statistiken';

// ------------------------------------------------------------
// Dropdown-Daten laden (Kampagnen + Listen)
// ------------------------------------------------------------
$campaigns = [];
$lists = [];
$error = '';

try {
    // Kampagnen laden
    $sql = "SELECT id, name FROM campaigns ORDER BY created_at DESC";
    $stmt = $db->prepare($sql);
    $params = [];
    $stmt->execute($params);
    $campaigns = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('statistics.php:load_campaigns | SQL: ' . $sql . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE));

    // Listen laden
    $sql = "SELECT id, name FROM lists ORDER BY name ASC";
    $stmt = $db->prepare($sql);
    $params = [];
    $stmt->execute($params);
    $lists = $stmt->fetchAll(PDO::FETCH_ASSOC);
    ErrorLogger::logSqlSuccess('statistics.php:load_lists | SQL: ' . $sql . ' | params: ' . json_encode($params, JSON_UNESCAPED_UNICODE));

} catch (Exception $e) {
    ErrorLogger::logSqlError('statistics.php:load_dropdowns | SQL: ' . ($sql ?? '-') . ' | params: ' . json_encode(($params ?? []), JSON_UNESCAPED_UNICODE) . ' | error: ' . $e->getMessage());
    $error = "Fehler beim Laden der Filterdaten.";
}

// ------------------------------------------------------------
// Default-Zeitraum: letzte 30 Tage (inkl. heute)
// ------------------------------------------------------------
$today = new DateTime('today');
$defaultFrom = (clone $today)->modify('-29 days')->format('Y-m-d');
$defaultTo   = $today->format('Y-m-d');

// Falls per GET vorbefuellt (z.B. Bookmark)
$dateFrom = $_GET['from'] ?? $defaultFrom;
$dateTo   = $_GET['to'] ?? $defaultTo;

$selectedCampaignId = $_GET['campaign_id'] ?? '';
$selectedListId     = $_GET['list_id'] ?? '';

// ------------------------------------------------------------
// Template Rendering Start
// ------------------------------------------------------------
ob_start();
?>

<style>
/* ------------------------------------------------------------
   Chart-Fix:
   Feste Hoehen fuer Chart-Wrapper, damit Chart.js nicht in eine
   Resize-Schleife geraet (Seite waechst sonst unendlich).
------------------------------------------------------------ */
#statsChartWrap { height: 320px; }
#statsChart { width: 100% !important; height: 100% !important; }

#statsHourChartWrap { height: 260px; }
#statsHourChart { width: 100% !important; height: 100% !important; }

/* ------------------------------------------------------------
   Heatmap Styles
------------------------------------------------------------ */
.heatmap-table th,
.heatmap-table td {
    text-align: center;
    vertical-align: middle;
    font-size: 12px;
    padding: 6px;
    white-space: nowrap;
}

.heatmap-legend {
    display: flex;
    gap: 10px;
    align-items: center;
    flex-wrap: wrap;
}
.heatmap-legend .box {
    width: 18px;
    height: 12px;
    border-radius: 3px;
    display: inline-block;
    border: 1px solid rgba(0,0,0,0.08);
}
</style>

<div class="container-fluid">

    <div class="d-flex align-items-center justify-content-between mb-3">
        <h1 class="h3 m-0">
            <i class="tml tml-chart"></i> Statistiken
        </h1>
    </div>

    <div class="alert alert-info" role="alert">
        Hinweis: Statistiken basieren auf aktuell im System vorhandenen Daten. Durch das L&ouml;schen von Empf&auml;ngern, Kampagnen oder Trackingdaten k&ouml;nnen sich historische Werte r&uuml;ckwirkend &auml;ndern.
    </div>

    <?php if (!empty($error)): ?>
        <div class="alert alert-danger alert-dismissible fade show js-auto-dismiss" role="alert">
            <i class="tml tml-alert"></i> <?= htmlspecialchars($error) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Schließen"></button>
        </div>
    <?php endif; ?>

    <!-- ------------------------------------------------------------
         Filterleiste
         ------------------------------------------------------------ -->
    <div class="card mb-3">
        <div class="card-body">
            <form id="statsFilterForm" class="row g-3">

                <div class="col-12 col-md-3">
                    <label class="form-label">Von</label>
                    <input type="date" class="form-control" name="from" value="<?= htmlspecialchars($dateFrom) ?>">
                </div>

                <div class="col-12 col-md-3">
                    <label class="form-label">Bis</label>
                    <input type="date" class="form-control" name="to" value="<?= htmlspecialchars($dateTo) ?>">
                </div>

                <div class="col-12 col-md-3">
                    <label class="form-label">Kampagne (optional)</label>
                    <select class="form-select" name="campaign_id">
                        <option value="">Alle Kampagnen</option>
                        <?php foreach ($campaigns as $c): ?>
                            <option value="<?= (int)$c['id'] ?>" <?= ((string)$selectedCampaignId === (string)$c['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($c['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12 col-md-3">
                    <label class="form-label">Liste (optional)</label>
                    <select class="form-select" name="list_id">
                        <option value="">Alle Listen</option>
                        <?php foreach ($lists as $l): ?>
                            <option value="<?= (int)$l['id'] ?>" <?= ((string)$selectedListId === (string)$l['id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($l['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12 d-flex gap-2">
                    <button type="submit" class="btn btn-primary">
                        <i class="tml tml-filter"></i> Anzeigen
                    </button>

                    <button type="button" id="btnReset" class="btn btn-outline-secondary">
                        <i class="tml tml-refresh"></i> Zurücksetzen
                    </button>

                    <div class="ms-auto text-muted small d-flex align-items-center">
                        <span id="statsStatusText">Bereit.</span>
                    </div>
                </div>

            </form>
        </div>
    </div>

    <!-- ------------------------------------------------------------
         KPI-Kacheln
         ------------------------------------------------------------ -->
    <div class="row g-3 mb-3" id="kpiRow">
        <?php
        $kpis = [
            ['key' => 'sent',          'label' => 'Versendet',          'icon' => 'tml-send'],
            ['key' => 'errors',        'label' => 'Fehler',             'icon' => 'tml-alert'],
            ['key' => 'opens_unique',  'label' => 'Öffnungen (unique)', 'icon' => 'tml-eye'],
            ['key' => 'opens_total',   'label' => 'Öffnungen (total)',  'icon' => 'tml-eye'],
            ['key' => 'clicks_unique', 'label' => 'Klicks (unique)',    'icon' => 'tml-link'],
            ['key' => 'clicks_total',  'label' => 'Klicks (total)',     'icon' => 'tml-link'],
            ['key' => 'bounces',       'label' => 'Bounces',            'icon' => 'tml-bounce'],
            ['key' => 'unsubs',        'label' => 'Abmeldungen',        'icon' => 'tml-user-minus'],
            ['key' => 'pdf',           'label' => 'PDF Downloads',      'icon' => 'tml-file'],
        ];
        foreach ($kpis as $kpi):
        ?>
            <div class="col-12 col-sm-6 col-lg-4 col-xxl-3">
                <div class="card h-100">
                    <div class="card-body">
                        <div class="d-flex align-items-start justify-content-between">
                            <div>
                                <div class="text-muted small"><?= htmlspecialchars($kpi['label']) ?></div>
                                <div class="h3 mb-0" data-kpi="<?= htmlspecialchars($kpi['key']) ?>">-</div>
                            </div>
                            <div class="text-muted">
                                <i class="tml <?= htmlspecialchars($kpi['icon']) ?>"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- ------------------------------------------------------------
         Chart: Verlauf pro Tag
         ------------------------------------------------------------ -->
    <div class="card mb-3">
        <div class="card-header d-flex align-items-center justify-content-between">
            <div class="fw-semibold"><i class="tml tml-linechart"></i> Verlauf (pro Tag)</div>
            <div class="text-muted small">Versand / Opens unique / Klicks unique / Bounces / Abmeldungen</div>
        </div>
        <div class="card-body">
            <div id="statsChartWrap">
                <canvas id="statsChart"></canvas>
            </div>
        </div>
    </div>

    <!-- ------------------------------------------------------------
         Chart: Tageszeiten (00-23 Uhr)
         ------------------------------------------------------------ -->
    <div class="card mb-3">
        <div class="card-header d-flex align-items-center justify-content-between">
            <div class="fw-semibold"><i class="tml tml-clock"></i> Tageszeiten (00-23 Uhr)</div>
            <div class="text-muted small">Aggregiert über den Zeitraum</div>
        </div>
        <div class="card-body">
            <div id="statsHourChartWrap">
                <canvas id="statsHourChart"></canvas>
            </div>
            <div class="text-muted small mt-2">
                Tipp: Peaks zeigen dir die besten Zeitfenster für Sendezeiten (z.B. 18-20 Uhr).
            </div>
        </div>
    </div>

    <!-- ------------------------------------------------------------
         HEATMAP: Wochentag x Stunde
         ------------------------------------------------------------ -->
    <div class="card mb-3">
        <div class="card-header d-flex align-items-center justify-content-between">
            <div class="fw-semibold"><i class="tml tml-grid"></i> Heatmap: Wochentag - Uhrzeit</div>
            <div class="text-muted small">Opens/Klicks (unique) pro Stunde & Wochentag</div>
        </div>
        <div class="card-body">

            <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-2">
                <div class="text-muted small">
                    Je dunkler die Zelle, desto mehr Events in diesem Zeitfenster.
                </div>
                <div class="heatmap-legend text-muted small">
                    <span>Skala:</span>
                    <span class="box" style="background: rgba(13,110,253,0.10)"></span><span>niedrig</span>
                    <span class="box" style="background: rgba(13,110,253,0.45)"></span>
                    <span class="box" style="background: rgba(13,110,253,0.80)"></span><span>hoch</span>
                </div>
            </div>

            <!-- Umschalter: Opens vs Klicks -->
            <div class="btn-group mb-3" role="group" aria-label="Heatmap Modus">
                <button type="button" class="btn btn-outline-primary active" id="btnHeatOpens">
                    <i class="tml tml-eye"></i> Opens (unique)
                </button>
                <button type="button" class="btn btn-outline-primary" id="btnHeatClicks">
                    <i class="tml tml-link"></i> Klicks (unique)
                </button>
            </div>

            <!-- Tabelle wird per JS erzeugt -->
            <div class="table-responsive">
                <table class="table table-sm table-bordered heatmap-table mb-0" id="heatmapTable">
                    <thead id="heatmapThead"></thead>
                    <tbody id="heatmapTbody"></tbody>
                </table>
            </div>

        </div>
    </div>

</div>

<!-- ------------------------------------------------------------
     JS: Laden + Rendern
     ------------------------------------------------------------ -->

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
(function() {
    // ------------------------------------------------------------
    // Auto-dismiss für Alerts
    // ------------------------------------------------------------
    document.querySelectorAll('.js-auto-dismiss').forEach(function(el) {
        setTimeout(function(){
            try {
                var alert = bootstrap.Alert.getOrCreateInstance(el);
                alert.close();
            } catch (e) {}
        }, 5000);
    });

    // ------------------------------------------------------------
    // Elemente
    // ------------------------------------------------------------
    const statusText = document.getElementById('statsStatusText');
    const form = document.getElementById('statsFilterForm');
    const btnReset = document.getElementById('btnReset');

    const btnHeatOpens = document.getElementById('btnHeatOpens');
    const btnHeatClicks = document.getElementById('btnHeatClicks');

    const heatmapThead = document.getElementById('heatmapThead');
    const heatmapTbody = document.getElementById('heatmapTbody');

    // ------------------------------------------------------------
    // Chart-Instanzen
    // ------------------------------------------------------------
    let dayChartInstance = null;
    let hourChartInstance = null;

    // Heatmap-Mode: 'opens' oder 'clicks'
    let heatMode = 'opens';

    // Letzte Heatmap-Daten merken, damit Umschalten ohne Reload geht
    let lastHeatmapData = null;

    function setStatus(msg) {
        statusText.textContent = msg;
    }

    // ------------------------------------------------------------
    // Filter zurücksetzen (Default: letzte 30 Tage)
    // ------------------------------------------------------------
    btnReset.addEventListener('click', function() {
        const today = new Date();
        const to = today.toISOString().slice(0, 10);

        const fromDate = new Date();
        fromDate.setDate(fromDate.getDate() - 29);
        const from = fromDate.toISOString().slice(0, 10);

        form.from.value = from;
        form.to.value = to;
        form.campaign_id.value = '';
        form.list_id.value = '';

        loadStats();
    });

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        loadStats();
    });

    // ------------------------------------------------------------
    // Heatmap Mode Buttons
    // ------------------------------------------------------------
    btnHeatOpens.addEventListener('click', function() {
        heatMode = 'opens';
        btnHeatOpens.classList.add('active');
        btnHeatClicks.classList.remove('active');
        if (lastHeatmapData) renderHeatmap(lastHeatmapData);
    });

    btnHeatClicks.addEventListener('click', function() {
        heatMode = 'clicks';
        btnHeatClicks.classList.add('active');
        btnHeatOpens.classList.remove('active');
        if (lastHeatmapData) renderHeatmap(lastHeatmapData);
    });

    // ------------------------------------------------------------
    // AJAX: Daten holen
    // ------------------------------------------------------------
    async function loadStats() {
        setStatus('Lade Statistik...');
        const formData = new FormData(form);

        try {
            const res = await fetch('statistics_ajax.php', {
                method: 'POST',
                body: formData
            });

            const data = await res.json();

            if (!data || data.success !== true) {
                setStatus('Fehler beim Laden.');
                console.error(data);
                return;
            }

            fillKpis(data.kpis);
            renderDayChart(data.series);
            renderHourChart(data.hourly);

            // Heatmap-Daten merken + rendern
            lastHeatmapData = data.heatmap || null;
            renderHeatmap(lastHeatmapData);

            setStatus('Aktualisiert.');
        } catch (err) {
            setStatus('Fehler beim Laden.');
            console.error(err);
        }
    }

    // ------------------------------------------------------------
    // KPI-Kacheln befuellen
    // ------------------------------------------------------------
    function fillKpis(kpis) {
        document.querySelectorAll('[data-kpi]').forEach(function(el) {
            const key = el.getAttribute('data-kpi');
            if (kpis && Object.prototype.hasOwnProperty.call(kpis, key)) {
                el.textContent = kpis[key];
            } else {
                el.textContent = '0';
            }
        });
    }

    // ------------------------------------------------------------
    // Chart 1: Verlauf pro Tag
    // ------------------------------------------------------------
    function renderDayChart(series) {
        const canvas = document.getElementById('statsChart');
        const ctx = canvas.getContext('2d');

        const labels = series.labels || [];
        const sent = series.sent || [];
        const opensUnique = series.opens_unique || [];
        const clicksUnique = series.clicks_unique || [];
        const bounces = series.bounces || [];
        const unsubs = series.unsubs || [];

        if (dayChartInstance) {
            dayChartInstance.destroy();
            dayChartInstance = null;
        }

        dayChartInstance = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    { label: 'Versendet', data: sent, tension: 0.2 },
                    { label: 'Opens (unique)', data: opensUnique, tension: 0.2 },
                    { label: 'Klicks (unique)', data: clicksUnique, tension: 0.2 },
                    { label: 'Bounces', data: bounces, tension: 0.2 },
                    { label: 'Abmeldungen', data: unsubs, tension: 0.2 },
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                animation: false,
                interaction: { mode: 'index', intersect: false },
                scales: { y: { beginAtZero: true } }
            }
        });
    }

    // ------------------------------------------------------------
    // Chart 2: Stundenverteilung 00-23
    // ------------------------------------------------------------
    function renderHourChart(hourly) {
        const canvas = document.getElementById('statsHourChart');
        const ctx = canvas.getContext('2d');

        const labels = (hourly && hourly.labels) ? hourly.labels : [];
        const sent = (hourly && hourly.sent) ? hourly.sent : [];
        const opensUnique = (hourly && hourly.opens_unique) ? hourly.opens_unique : [];
        const clicksUnique = (hourly && hourly.clicks_unique) ? hourly.clicks_unique : [];
        const bounces = (hourly && hourly.bounces) ? hourly.bounces : [];
        const unsubs = (hourly && hourly.unsubs) ? hourly.unsubs : [];

        if (hourChartInstance) {
            hourChartInstance.destroy();
            hourChartInstance = null;
        }

        hourChartInstance = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    { label: 'Versendet', data: sent, tension: 0.2 },
                    { label: 'Opens (unique)', data: opensUnique, tension: 0.2 },
                    { label: 'Klicks (unique)', data: clicksUnique, tension: 0.2 },
                    { label: 'Bounces', data: bounces, tension: 0.2 },
                    { label: 'Abmeldungen', data: unsubs, tension: 0.2 },
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                animation: false,
                interaction: { mode: 'index', intersect: false },
                scales: { y: { beginAtZero: true } }
            }
        });
    }

    // ------------------------------------------------------------
    // HEATMAP: Wochentag x Stunde
    // - Wir rendern als Tabelle, ohne externe JS-Libs.
    // - Farbintensitaet per rgba(13,110,253, alpha)
    // ------------------------------------------------------------
    function renderHeatmap(heatmap) {
        // Fallback: leere Anzeige
        if (!heatmap || !heatmap.labels_hours || !heatmap.labels_days || !heatmap.matrix_opens || !heatmap.matrix_clicks) {
            heatmapThead.innerHTML = '';
            heatmapTbody.innerHTML = '<tr><td class="text-muted">Keine Daten im Zeitraum.</td></tr>';
            return;
        }

        const hours = heatmap.labels_hours; // ["00".."23"]
        const days = heatmap.labels_days;   // ["Mo","Di","Mi","Do","Fr","Sa","So"]

        const matrix = (heatMode === 'clicks') ? heatmap.matrix_clicks : heatmap.matrix_opens;

        // Max-Wert fuer Skalierung bestimmen
        let maxVal = 0;
        for (let d = 0; d < days.length; d++) {
            for (let h = 0; h < hours.length; h++) {
                const v = matrix[d][h] || 0;
                if (v > maxVal) maxVal = v;
            }
        }

        // Header erstellen
        let theadHtml = '<tr><th>Tag \\ Uhr</th>';
        for (let h = 0; h < hours.length; h++) {
            theadHtml += '<th>' + hours[h] + '</th>';
        }
        theadHtml += '</tr>';
        heatmapThead.innerHTML = theadHtml;

        // Body erstellen
        let tbodyHtml = '';
        for (let d = 0; d < days.length; d++) {
            tbodyHtml += '<tr>';
            tbodyHtml += '<th scope="row">' + days[d] + '</th>';

            for (let h = 0; h < hours.length; h++) {
                const v = matrix[d][h] || 0;

                // Alpha berechnen: 0.10 .. 0.90 je nach Anteil
                let alpha = 0.10;
                if (maxVal > 0) {
                    alpha = 0.10 + (0.80 * (v / maxVal));
                }

                // Sehr kleine Werte sollen optisch nicht "zu dunkel" werden
                if (v === 0) alpha = 0.04;

                const bg = 'rgba(13,110,253,' + alpha.toFixed(3) + ')';

                // Tooltip: zeigt exakten Wert
                const title = (heatMode === 'clicks' ? 'Klicks (unique): ' : 'Opens (unique): ') + v;

                tbodyHtml += '<td style="background:' + bg + ';" title="' + title.replace(/"/g,'&quot;') + '">';
                tbodyHtml += v;
                tbodyHtml += '</td>';
            }

            tbodyHtml += '</tr>';
        }

        heatmapTbody.innerHTML = tbodyHtml;
    }

    // Initial Load
    loadStats();

})();
</script>

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

