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

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

    $name = trim($_POST['name'] ?? '');
    $extraEmails = trim($_POST['extra_emails'] ?? '');

    if ($name === '') {
        flash('Grup adı zorunludur.', 'error');
        redirect('customer_group_create.php');
    }

    $emails = [];
    $emails = array_merge($emails, parseRecipients($extraEmails));

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

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

    if (!$emails) {
        flash('Gruba eklenecek en az bir geçerli mail adresi gerekiyor.', 'error');
        redirect('customer_group_create.php');
    }

    validateRecipientCount($emails);

    $pdo = db();

    $stmt = $pdo->prepare("SELECT id FROM customer_groups WHERE name = :name LIMIT 1");
    $stmt->execute([':name' => $name]);
    $existing = $stmt->fetch();

    if ($existing) {
        flash('Bu isimde bir müşteri grubu zaten mevcut.', 'error');
        redirect('customer_group_create.php');
    }

    createCustomerGroupFromEmails($pdo, $name, $emails);

    flash('Müşteri grubu oluşturuldu. Toplam ' . count($emails) . ' benzersiz mail eklendi.');
    redirect('customer_groups.php');

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