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

$flash = getFlash();
$pdo = db();
$customerGroups = getCustomerGroups($pdo);
?>
<!doctype html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mail Oluştur</title>
    <link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
    <style>
        * { box-sizing: border-box; }
        body { margin: 0; font-family: Arial, Helvetica, sans-serif; background: #f5f7fb; color: #1f2937; }
        .container { max-width: 1150px; margin: 30px auto; padding: 0 16px; }
        .topbar { display: flex; gap: 12px; align-items: center; justify-content: space-between; margin-bottom: 20px; flex-wrap: wrap; }
        .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: 10px; padding: 12px 18px; cursor: pointer; font-weight: 600; font-size: 14px; min-height: 44px; }
        .btn-primary { background: #2563eb; color: #fff; }
        .btn-secondary { background: #e5e7eb; color: #111827; }
        .card { background: #fff; border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.06); padding: 20px; }
        .flash { padding: 14px 16px; border-radius: 12px; margin-bottom: 18px; font-size: 14px; }
        .flash.success { background: #dcfce7; color: #166534; }
        .flash.error { background: #fee2e2; color: #991b1b; }
        .limit-box { background: #eff6ff; border: 1px solid #bfdbfe; color: #1d4ed8; padding: 14px 16px; border-radius: 12px; margin-bottom: 18px; font-size: 14px; line-height: 1.6; }
        .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .field { margin-bottom: 16px; }
        .field.full { grid-column: 1 / -1; }
        label { display: block; margin-bottom: 8px; font-size: 14px; font-weight: 600; }
        input[type="text"], input[type="email"], input[type="file"], select, textarea { width: 100%; border: 1px solid #d1d5db; border-radius: 12px; padding: 12px 14px; font-size: 14px; outline: none; background: #fff; }
        textarea { min-height: 140px; resize: vertical; }
        input:focus, textarea:focus, select:focus { border-color: #2563eb; }
        .muted { color: #6b7280; font-size: 13px; margin-top: 6px; }
        .upload-box { border: 1px dashed #cbd5e1; border-radius: 12px; padding: 16px; background: #f8fafc; }
        #editor { background: #fff; min-height: 320px; border-radius: 12px; }
        .ql-toolbar.ql-snow { border-radius: 12px 12px 0 0; border-color: #d1d5db; }
        .ql-container.ql-snow { border-radius: 0 0 12px 12px; border-color: #d1d5db; min-height: 260px; font-size: 14px; }
        @media (max-width: 768px) {
            .grid { grid-template-columns: 1fr; }
            .topbar h1 { font-size: 22px; }
            .btn { width: 100%; }
            .actions { width: 100%; }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="topbar">
        <h1>Mail Oluştur</h1>
        <div class="actions">
            <a class="btn btn-secondary" href="index.php">Panele Dön</a>
            <a class="btn btn-secondary" href="customer_groups.php">Müşteri Grupları</a>
        </div>
    </div>

    <?php if ($flash): ?>
        <div class="flash <?= e($flash['type']) ?>"><?= e($flash['message']) ?></div>
    <?php endif; ?>

    <div class="limit-box">
        Maksimum <strong>100 benzersiz alıcı</strong> kabul edilir. Ek dosyaların toplam boyutu en fazla <strong>10 MB</strong> olabilir.
    </div>

    <div class="card">
        <form method="post" action="send.php" enctype="multipart/form-data">
            <div class="grid">
                <div class="field full">
                    <label for="subject">Konu</label>
                    <input type="text" id="subject" name="subject" required>
                </div>

                <div class="field full">
                    <label for="customer_group_id">Müşteri Grubu Seç</label>
                    <select id="customer_group_id" name="customer_group_id">
                        <option value="">Grup seçmeden devam et</option>
                        <?php foreach ($customerGroups as $group): ?>
                            <option value="<?= (int)$group['id'] ?>"><?= e($group['name']) ?> (<?= (int)$group['email_count'] ?>)</option>
                        <?php endforeach; ?>
                    </select>
                    <div class="muted">Bir grup seçersen sistem o grubun mail adreslerini otomatik alır.</div>
                </div>

                <div class="field">
                    <label for="single_email">Tekil Gönderim</label>
                    <input type="email" id="single_email" name="single_email" placeholder="ornek@mail.com">
                    <div class="muted">Tek kişiye gönderim için kullan.</div>
                </div>

                <div class="field">
                    <label for="multiple_emails">Çoklu Alıcılar</label>
                    <textarea id="multiple_emails" name="multiple_emails" placeholder="mail1@example.com, mail2@example.com&#10;mail3@example.com"></textarea>
                    <div class="muted">Virgül, boşluk veya alt alta e-posta ekleyebilirsin.</div>
                </div>

                <div class="field full">
                    <label for="recipients_file">Alıcı Excel / CSV Dosyası</label>
                    <div class="upload-box">
                        <input type="file" id="recipients_file" name="recipients_file" accept=".xlsx,.csv">
                        <div class="muted">.xlsx veya .csv dosyası yükleyebilirsin. Sistem yalnızca <strong>email</strong> başlıklı sütunu okur.</div>
                    </div>
                </div>

                <div class="field full">
                    <label for="plain_body">Düz Metin İçerik</label>
                    <textarea id="plain_body" name="plain_body" placeholder="Mailin düz metin versiyonu"></textarea>
                </div>

                <div class="field full">
                    <label>HTML İçerik</label>
                    <div id="editor"></div>
                    <textarea id="html_body" name="html_body" style="display:none;"></textarea>
                    <div class="muted">Mail içeriğini burada görsel olarak düzenleyebilirsin.</div>
                </div>

                <div class="field full">
                    <label for="attachments">Ek Dosyalar</label>
                    <div class="upload-box">
                        <input type="file" id="attachments" name="attachments[]" multiple accept=".jpg,.jpeg,.png,.gif,.webp,.pdf,.doc,.docx,.xls,.xlsx,.csv">
                        <div class="muted">Resim, PDF, Word, Excel ve CSV dosyalarını çoklu olarak yükleyebilirsin. Toplam ek boyutu en fazla 10 MB olabilir.</div>
                    </div>
                </div>

                <div class="field full">
                    <button type="submit" class="btn btn-primary">Gönderim Kuyruğunu Başlat</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.quilljs.com/1.3.6/quill.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const quill = new Quill('#editor', {
        theme: 'snow',
        modules: {
            toolbar: [
                [{ header: [1, 2, 3, false] }],
                ['bold', 'italic', 'underline'],
                [{ list: 'ordered' }, { list: 'bullet' }],
                [{ align: [] }],
                ['link'],
                ['clean']
            ]
        }
    });

    const form = document.querySelector('form');
    const attachmentsInput = document.getElementById('attachments');

    form.addEventListener('submit', function (e) {
        document.getElementById('html_body').value = quill.root.innerHTML;

        if (attachmentsInput && attachmentsInput.files.length > 0) {
            let totalSize = 0;
            for (let i = 0; i < attachmentsInput.files.length; i++) {
                totalSize += attachmentsInput.files[i].size;
            }

            const maxSize = 10 * 1024 * 1024;
            if (totalSize > maxSize) {
                e.preventDefault();
                alert('Ek dosyaların toplam boyutu en fazla 10 MB olabilir.');
                return false;
            }
        }
    });
});
</script>
</body>
</html>
