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

header('Content-Type: application/json; charset=utf-8');

try {
    $pdo = db();
    $campaignId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

    if ($campaignId <= 0) {
        throw new RuntimeException('Geçersiz kampanya ID.');
    }

    $campaign = getCampaignById($pdo, $campaignId);
    if (!$campaign) {
        throw new RuntimeException('Kampanya bulunamadı.');
    }

    $cfg = app_config();
    $batchPerRun = 5;

    if (($campaign['status'] ?? 'queued') !== 'completed') {
        setCampaignStatus($pdo, $campaignId, 'sending');

        $attachments = getCampaignAttachments($pdo, $campaignId);
        $pendingSends = getPendingSendsByCampaign($pdo, $campaignId, $batchPerRun);

        foreach ($pendingSends as $send) {
            $recipient = getRecipientById($pdo, (int)$send['recipient_id']);

            if (!$recipient || (int)($recipient['unsubscribed'] ?? 0) === 1) {
                updateSendStatus($pdo, (int)$send['id'], false, 'Alıcı abonelikten çıkmış veya bulunamadı.');
                continue;
            }

            $trackedHtml = buildTrackedHtml($campaign['html_body'], $send['tracking_token'], $send['email']);

            $result = sendEmailNow(
                $send['email'],
                $campaign['subject'],
                $trackedHtml,
                (string)($campaign['plain_body'] ?? ''),
                $attachments
            );

            updateSendStatus($pdo, (int)$send['id'], (bool)$result['success'], $result['error'] ?? null);

            usleep((int)($cfg['sending']['sleep_microseconds_between_sends'] ?? 300000));
        }

        finalizeCampaignStats($pdo, $campaignId);

        $remaining = countPendingSendsByCampaign($pdo, $campaignId);

        if ($remaining <= 0) {
            setCampaignStatus($pdo, $campaignId, 'completed');
        } else {
            setCampaignStatus($pdo, $campaignId, 'sending');
        }
    }

    $campaign = getCampaignById($pdo, $campaignId);

    echo json_encode([
        'success' => true,
        'status' => $campaign['status'] ?? 'queued',
        'total_count' => (int)$campaign['total_count'],
        'success_count' => (int)$campaign['success_count'],
        'failed_count' => (int)$campaign['failed_count'],
        'opened_count' => (int)$campaign['opened_count'],
        'message' => (($campaign['status'] ?? 'queued') === 'completed') ? 'Gönderim tamamlandı.' : 'Gönderim partiler halinde devam ediyor.'
    ], JSON_UNESCAPED_UNICODE);

} catch (\Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
