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

$pdo = db();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    flash('Geçersiz kampanya ID.', 'error');
    redirect('index.php');
}

$campaign = getCampaignById($pdo, $id);
if (!$campaign) {
    flash('Kampanya bulunamadı.', 'error');
    redirect('index.php');
}

$statusMap = [
    'queued' => 'Kuyrukta',
    'sending' => 'Gönderiliyor',
    'completed' => 'Tamamlandı',
];
?>
<!doctype html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gönderim Takibi</title>
    <style>
        * { box-sizing: border-box; }
        body { margin: 0; font-family: Arial, Helvetica, sans-serif; background: #f5f7fb; color: #111827; }
        .container { max-width: 980px; 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; }
        .card { background: #fff; border-radius: 18px; box-shadow: 0 10px 30px rgba(0,0,0,0.06); padding: 20px; margin-bottom: 20px; }
        .grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 20px; }
        .stat-title { font-size: 13px; color: #6b7280; margin-bottom: 8px; }
        .stat-value { font-size: 28px; font-weight: 700; }
        .progress-wrap { width: 100%; height: 18px; background: #e5e7eb; border-radius: 999px; overflow: hidden; margin-top: 14px; }
        .progress-bar { height: 100%; width: 0%; background: #2563eb; transition: width 0.35s ease; }
        .status-badge { display: inline-block; padding: 8px 12px; border-radius: 999px; font-size: 12px; font-weight: 700; background: #ede9fe; color: #6d28d9; }
        .status-sending { background: #fef3c7; color: #92400e; }
        .status-completed { background: #dcfce7; color: #166534; }
        .log { font-size: 14px; color: #4b5563; line-height: 1.7; }
        @media (max-width: 900px) { .grid { grid-template-columns: repeat(2, 1fr); } }
        @media (max-width: 640px) {
            .grid { 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>Gönderim Takibi</h1>
        <div class="actions">
            <a href="index.php" class="btn">Panele Dön</a>
            <a href="campaign.php?id=<?= (int)$campaign['id'] ?>" class="btn btn-primary">Kampanya Detayı</a>
        </div>
    </div>

    <div class="card">
        <div class="stat-title">Kampanya</div>
        <div style="font-size:22px;font-weight:700; margin-bottom:12px;"><?= e($campaign['subject']) ?></div>
        <span id="campaign-status" class="status-badge"><?= e($statusMap[$campaign['status'] ?? 'queued'] ?? 'Kuyrukta') ?></span>
        <div class="progress-wrap"><div id="progress-bar" class="progress-bar"></div></div>
        <div id="progress-text" style="margin-top:10px;font-size:14px;color:#6b7280;">Hazırlanıyor...</div>
    </div>

    <div class="grid">
        <div class="card"><div class="stat-title">Toplam</div><div id="total-count" class="stat-value"><?= (int)$campaign['total_count'] ?></div></div>
        <div class="card"><div class="stat-title">Başarılı</div><div id="success-count" class="stat-value"><?= (int)$campaign['success_count'] ?></div></div>
        <div class="card"><div class="stat-title">Başarısız</div><div id="failed-count" class="stat-value"><?= (int)$campaign['failed_count'] ?></div></div>
        <div class="card"><div class="stat-title">Açılan</div><div id="opened-count" class="stat-value"><?= (int)$campaign['opened_count'] ?></div></div>
    </div>

    <div class="card">
        <div class="stat-title">Canlı Durum</div>
        <div id="live-log" class="log">Gönderim partiler halinde işleniyor...</div>
    </div>
</div>

<script>
const campaignId = <?= (int)$campaign['id'] ?>;
let polling = true;

function statusClassName(status) {
    if (status === 'sending') return 'status-badge status-sending';
    if (status === 'completed') return 'status-badge status-completed';
    return 'status-badge';
}
function statusText(status) {
    if (status === 'sending') return 'Gönderiliyor';
    if (status === 'completed') return 'Tamamlandı';
    return 'Kuyrukta';
}

async function processBatch() {
    try {
        const response = await fetch('process_batch.php?id=' + campaignId, {
            method: 'GET',
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        });
        const data = await response.json();

        document.getElementById('total-count').textContent = data.total_count;
        document.getElementById('success-count').textContent = data.success_count;
        document.getElementById('failed-count').textContent = data.failed_count;
        document.getElementById('opened-count').textContent = data.opened_count;

        const done = Number(data.success_count) + Number(data.failed_count);
        const total = Number(data.total_count);
        const percent = total > 0 ? Math.round((done / total) * 100) : 0;

        document.getElementById('progress-bar').style.width = percent + '%';
        document.getElementById('progress-text').textContent = `${done} / ${total} işlendi • %${percent}`;

        const statusEl = document.getElementById('campaign-status');
        statusEl.className = statusClassName(data.status);
        statusEl.textContent = statusText(data.status);

        document.getElementById('live-log').textContent = data.message || 'İşlem devam ediyor...';

        if (data.status === 'completed') {
            polling = false;
        }
    } catch (e) {
        document.getElementById('live-log').textContent = 'İşlem durumu alınırken hata oluştu: ' + e;
    }
    if (polling) setTimeout(processBatch, 2500);
}
processBatch();
</script>
</body>
</html>
