<?php
require_once __DIR__ . '/../src/bootstrap.php';
require_once __DIR__ . '/../src/functions.php';

$pdo = db();

$summary = getAnalyticsSummary($pdo);
$campaignData = getCampaignPerformanceData($pdo, 12);
$dailyStats = getDailySendStats($pdo, 14);
$topOpenCampaigns = getTopOpenCampaigns($pdo, 5);

$campaignLabels = [];
$campaignSuccess = [];
$campaignFailed = [];
$campaignOpened = [];
foreach ($campaignData as $row) {
    $campaignLabels[] = '#' . $row['id'];
    $campaignSuccess[] = (int)$row['success_count'];
    $campaignFailed[] = (int)$row['failed_count'];
    $campaignOpened[] = (int)$row['opened_count'];
}

$dailyLabels = [];
$dailyTotal = [];
$dailySuccess = [];
$dailyFailed = [];
foreach ($dailyStats as $row) {
    $dailyLabels[] = $row['day'];
    $dailyTotal[] = (int)$row['total'];
    $dailySuccess[] = (int)$row['success'];
    $dailyFailed[] = (int)$row['failed'];
}

$statusLabels = ['Kuyrukta', 'Gönderiliyor', 'Tamamlandı'];
$statusValues = [(int)$summary['queued'], (int)$summary['sending'], (int)$summary['completed']];
?>
<!doctype html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grafikler / Analiz</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
* { box-sizing: border-box; }
body { margin: 0; font-family: Arial, Helvetica, sans-serif; background: #f5f7fb; color: #111827; }
.container { max-width: 1350px; margin: 30px auto; padding: 0 16px; }
.topbar { display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; margin-bottom: 20px; }
.topbar h1 { margin: 0; font-size: 28px; }
.actions { display: flex; gap: 10px; flex-wrap: wrap; }
.btn { display: inline-flex; align-items: center; justify-content: center; text-decoration: none; border: 0; border-radius: 12px; padding: 12px 18px; cursor: pointer; font-weight: 600; font-size: 14px; min-height: 44px; background: #e5e7eb; color: #111827; }
.btn-primary { background: #2563eb; color: #fff; }
.grid-cards { display: grid; grid-template-columns: repeat(6, 1fr); gap: 16px; margin-bottom: 24px; }
.card { background: #fff; border-radius: 18px; box-shadow: 0 10px 30px rgba(0,0,0,0.06); padding: 20px; }
.stat-title { font-size: 13px; color: #6b7280; margin-bottom: 8px; }
.stat-value { font-size: 28px; font-weight: 700; }
.stat-sub { margin-top: 8px; font-size: 13px; color: #6b7280; }
.grid-charts { display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-bottom: 24px; }
.grid-charts-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 24px; }
.chart-title { margin: 0 0 16px; font-size: 20px; }
.chart-box { position: relative; min-height: 360px; }
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; min-width: 700px; }
th, td { text-align: left; padding: 14px 16px; border-bottom: 1px solid #e5e7eb; font-size: 14px; vertical-align: top; }
th { background: #f9fafb; color: #374151; font-weight: 700; }
.badge { display: inline-block; padding: 7px 12px; border-radius: 999px; font-size: 12px; font-weight: 700; background: #dbeafe; color: #1d4ed8; }
@media (max-width: 1200px) { .grid-cards { grid-template-columns: repeat(3, 1fr); } .grid-charts, .grid-charts-2 { grid-template-columns: 1fr; } }
@media (max-width: 640px) { .grid-cards { grid-template-columns: 1fr; } .topbar h1 { font-size: 22px; } .actions { width: 100%; } .btn { width: 100%; } }
</style>
</head>
<body>
<div class="container">
    <div class="topbar">
        <h1>Grafikler / Analiz</h1>
        <div class="actions">
            <a href="index.php" class="btn">Panele Dön</a>
            <a href="customer_groups.php" class="btn">Müşteri Grupları</a>
            <a href="compose.php" class="btn btn-primary">Yeni Mail Oluştur</a>
        </div>
    </div>

    <div class="grid-cards">
        <div class="card"><div class="stat-title">Toplam Kampanya</div><div class="stat-value"><?= (int)$summary['campaign_count'] ?></div></div>
        <div class="card"><div class="stat-title">Toplam Gönderim</div><div class="stat-value"><?= (int)$summary['total_sent'] ?></div></div>
        <div class="card"><div class="stat-title">Başarılı</div><div class="stat-value"><?= (int)$summary['success'] ?></div></div>
        <div class="card"><div class="stat-title">Başarısız</div><div class="stat-value"><?= (int)$summary['failed'] ?></div></div>
        <div class="card"><div class="stat-title">Açılan</div><div class="stat-value"><?= (int)$summary['opened'] ?></div></div>
        <div class="card"><div class="stat-title">Başarı / Açılma</div><div class="stat-value">%<?= $summary['success_rate'] ?></div><div class="stat-sub">Açılma Oranı: %<?= $summary['open_rate'] ?></div></div>
    </div>

    <div class="grid-charts">
        <div class="card">
            <h2 class="chart-title">Son Kampanyalar Performans Grafiği</h2>
            <div class="chart-box"><canvas id="campaignPerformanceChart"></canvas></div>
        </div>
        <div class="card">
            <h2 class="chart-title">Durum Dağılımı</h2>
            <div class="chart-box"><canvas id="statusChart"></canvas></div>
        </div>
    </div>

    <div class="grid-charts-2">
        <div class="card">
            <h2 class="chart-title">Günlük Gönderim Analizi</h2>
            <div class="chart-box"><canvas id="dailyChart"></canvas></div>
        </div>
        <div class="card">
            <h2 class="chart-title">En İyi Açılma Oranına Sahip Kampanyalar</h2>
            <div class="table-wrap">
                <table>
                    <thead><tr><th>ID</th><th>Konu</th><th>Başarılı</th><th>Açılan</th><th>Oran</th></tr></thead>
                    <tbody>
                    <?php if (!$topOpenCampaigns): ?>
                        <tr><td colspan="5">Henüz yeterli veri yok.</td></tr>
                    <?php else: ?>
                        <?php foreach ($topOpenCampaigns as $row): ?>
                            <tr>
                                <td>#<?= (int)$row['id'] ?></td>
                                <td><?= e($row['subject']) ?></td>
                                <td><?= (int)$row['success_count'] ?></td>
                                <td><?= (int)$row['opened_count'] ?></td>
                                <td><span class="badge">%<?= e($row['open_rate']) ?></span></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
const campaignLabels = <?= json_encode($campaignLabels, JSON_UNESCAPED_UNICODE) ?>;
const campaignSuccess = <?= json_encode($campaignSuccess) ?>;
const campaignFailed = <?= json_encode($campaignFailed) ?>;
const campaignOpened = <?= json_encode($campaignOpened) ?>;
const dailyLabels = <?= json_encode($dailyLabels, JSON_UNESCAPED_UNICODE) ?>;
const dailyTotal = <?= json_encode($dailyTotal) ?>;
const dailySuccess = <?= json_encode($dailySuccess) ?>;
const dailyFailed = <?= json_encode($dailyFailed) ?>;
const statusLabels = <?= json_encode($statusLabels, JSON_UNESCAPED_UNICODE) ?>;
const statusValues = <?= json_encode($statusValues) ?>;

new Chart(document.getElementById('campaignPerformanceChart'), {
    type: 'bar',
    data: {
        labels: campaignLabels,
        datasets: [
            { label: 'Başarılı', data: campaignSuccess, backgroundColor: 'rgba(34,197,94,0.7)', borderRadius: 8 },
            { label: 'Başarısız', data: campaignFailed, backgroundColor: 'rgba(239,68,68,0.7)', borderRadius: 8 },
            { label: 'Açılan', data: campaignOpened, backgroundColor: 'rgba(59,130,246,0.7)', borderRadius: 8 }
        ]
    },
    options: { responsive: true, maintainAspectRatio: false }
});

new Chart(document.getElementById('statusChart'), {
    type: 'doughnut',
    data: {
        labels: statusLabels,
        datasets: [{
            data: statusValues,
            backgroundColor: ['rgba(139,92,246,0.75)','rgba(245,158,11,0.75)','rgba(34,197,94,0.75)']
        }]
    },
    options: { responsive: true, maintainAspectRatio: false }
});

new Chart(document.getElementById('dailyChart'), {
    type: 'line',
    data: {
        labels: dailyLabels,
        datasets: [
            { label: 'Toplam', data: dailyTotal, borderColor: 'rgba(37,99,235,1)', backgroundColor: 'rgba(37,99,235,0.15)', fill: true, tension: 0.35 },
            { label: 'Başarılı', data: dailySuccess, borderColor: 'rgba(34,197,94,1)', backgroundColor: 'rgba(34,197,94,0.10)', fill: true, tension: 0.35 },
            { label: 'Başarısız', data: dailyFailed, borderColor: 'rgba(239,68,68,1)', backgroundColor: 'rgba(239,68,68,0.10)', fill: true, tension: 0.35 }
        ]
    },
    options: { responsive: true, maintainAspectRatio: false }
});
</script>
</body>
</html>
