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

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        redirect('compose.php');
    }

    $subject = trim($_POST['subject'] ?? '');
    $single = trim($_POST['single_email'] ?? '');
    $multiple = trim($_POST['multiple_emails'] ?? '');
    $plain = trim($_POST['plain_body'] ?? '');
    $html = trim($_POST['html_body'] ?? '');
    $customerGroupId = isset($_POST['customer_group_id']) ? (int)$_POST['customer_group_id'] : 0;

    if ($subject === '' || $html === '') {
        flash('Konu ve HTML içerik zorunludur.', 'error');
        redirect('compose.php');
    }

    $pdo = db();
    $recipients = [];

    if ($customerGroupId > 0) {
        $group = getCustomerGroupById($pdo, $customerGroupId);
        if (!$group) {
            flash('Seçilen müşteri grubu bulunamadı.', 'error');
            redirect('compose.php');
        }
        $groupEmails = getCustomerGroupEmails($pdo, $customerGroupId);
        $recipients = array_merge($recipients, $groupEmails);
    }

    if ($single !== '' && filter_var($single, FILTER_VALIDATE_EMAIL)) {
        $recipients[] = strtolower($single);
    }

    $recipients = array_merge($recipients, parseRecipients($multiple));

    if (isset($_FILES['recipients_file'])) {
        $fileRecipients = extractEmailsFromUploadedRecipientFile($_FILES['recipients_file']);
        $recipients = array_merge($recipients, $fileRecipients);
    }

    $recipients = array_values(array_unique(array_map(function ($email) {
        return mb_strtolower(trim((string)$email));
    }, $recipients)));

    if (count($recipients) === 0) {
        flash('Müşteri grubu, tekil alan, çoklu alan veya Excel/CSV dosyası üzerinden en az bir geçerli alıcı girmen gerekiyor.', 'error');
        redirect('compose.php');
    }

    validateRecipientCount($recipients);

    if (isset($_FILES['attachments'])) {
        validateAttachmentsTotalSize($_FILES['attachments']);
    }

    $campaignId = createCampaign($pdo, $subject, $html, $plain, count($recipients));
    setCampaignStatus($pdo, $campaignId, 'queued');

    if (isset($_FILES['attachments'])) {
        saveUploadedAttachments($pdo, $campaignId, $_FILES['attachments']);
    }

    foreach ($recipients as $email) {
        $recipient = findOrCreateRecipient($pdo, $email);
        if ((int)($recipient['unsubscribed'] ?? 0) === 1) {
            continue;
        }
        createSendRecord($pdo, $campaignId, (int)$recipient['id'], $email);
    }

    finalizeCampaignStats($pdo, $campaignId);

    flash('Kampanya kuyruğa alındı. Toplam ' . count($recipients) . ' benzersiz alıcı içe aktarıldı.');
    redirect('runner.php?id=' . $campaignId);

} catch (\Throwable $e) {
    flash('Hata: ' . $e->getMessage(), 'error');
    redirect('compose.php');
}
