<?php
/**
 * Admin Ürün Ekleme Sayfası (Deneme Paketi Modülü ve Lojistik Tarihli)
 * Konum: /magaza/admin/urunler/ekle.php
 */

require_once '../../includes/db.php';
require_once '../../includes/functions.php';

/**
 * GÜVENLİK KONTROLÜ
 */
adminCheck();

$mesaj = '';

// Kategori ve Markaları Çek (Formdaki seçim alanlarını beslemek için)
$kategoriler = $db->query("SELECT id, name FROM categories ORDER BY name ASC")->fetchAll();
$markalar = $db->query("SELECT id, name FROM brands ORDER BY name ASC")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['urun_ekle'])) {
    
    // 1. TEMEL BİLGİLERİ AL VE TEMİZLE
    $name = trim($_POST['name']);
    $type = $_POST['type'];
    $brand_id = !empty($_POST['brand_id']) ? $_POST['brand_id'] : NULL;
    $description = trim($_POST['description']); // Editörden gelen HTML verisi
    $sku = !empty($_POST['sku']) ? trim($_POST['sku']) : NULL;
    
    // Çoklu veya Tekli Kategori Yönetimi
    $category_id = (!empty($_POST['category_id']) && !is_array($_POST['category_id'])) ? $_POST['category_id'] : NULL;
    $selected_categories = (isset($_POST['categories']) && is_array($_POST['categories'])) ? $_POST['categories'] : [];
    
    // YENİ: Tekli Deneme Sınavı (single_exam) Özel Alanları
    $exam_type = !empty($_POST['exam_type']) ? trim($_POST['exam_type']) : NULL;
    $exam_publication_date = !empty($_POST['exam_publication_date']) ? trim($_POST['exam_publication_date']) : NULL;
    $exam_date = !empty($_POST['exam_date']) ? $_POST['exam_date'] : NULL;

    // --- YENİ SEO URL (SLUG) STRATEJİSİ ---
    $custom_slug = !empty($_POST['custom_slug']) ? trim($_POST['custom_slug']) : '';
    
    if (!empty($custom_slug)) {
        // Kullanıcı manuel SEO link girdiyse onu kullan (TÜM ÜRÜN TİPLERİ İÇİN GEÇERLİDİR)
        $slug = seoLink($custom_slug);
    } else {
        // Boş bırakıldıysa otomatik oluştur
        if ($type == 'single_exam') {
            $tarih_metni = !empty($exam_publication_date) ? str_replace('.', '-', $exam_publication_date) : '';
            $ham_slug_metni = $name . ($tarih_metni ? '-' . $tarih_metni : '');
            $slug = seoLink($ham_slug_metni);
        } else {
            $slug = seoLink($name);
        }
    }

    // Benzersiz Slug Kontrolü ve Düzeltmesi (Çirkin Sayılar Yerine SKU veya ID Mantığı)
    $check = $db->prepare("SELECT id FROM products WHERE slug = ?");
    $check->execute([$slug]);
    if ($check->rowCount() > 0) { 
        if (!empty($sku)) {
            $slug = seoLink($name . '-' . $sku); // Varsa SKU ile birleştir
        } else {
            // Yine de çakışırsa kısa, anlamlı, ufak bir rastgele karakter
            $slug = $slug . '-' . substr(md5(uniqid()), 0, 5); 
        }
    }
    // --------------------------------------

    // 2. FİYAT, KDV VE STOK VERİLERİ
    $price = $_POST['price'];
    $discount_price = !empty($_POST['discount_price']) ? $_POST['discount_price'] : NULL;
    $vat_rate = isset($_POST['vat_rate']) ? (int)$_POST['vat_rate'] : 0;
    $vat_included = isset($_POST['vat_included']) ? (int)$_POST['vat_included'] : 1;
    $stock_quantity = !empty($_POST['stock_quantity']) ? (int)$_POST['stock_quantity'] : 0;
    
    // 3. KARGO, ABONELİK VE PAKET DETAYLARI
    $shipping_info = !empty($_POST['shipping_info']) ? trim($_POST['shipping_info']) : NULL;
    $is_free_shipping = isset($_POST['is_free_shipping']) ? 1 : 0;
    $duration_days = !empty($_POST['duration_days']) ? (int)$_POST['duration_days'] : NULL;
    $total_deliveries = !empty($_POST['total_deliveries']) ? (int)$_POST['total_deliveries'] : 1;
    
    // ÜRÜNE ÖZEL TESLİMAT VE ÖDEME METİNLERİ
    $custom_payment_text = !empty($_POST['custom_payment_text']) ? trim($_POST['custom_payment_text']) : NULL;
    $custom_delivery_text = !empty($_POST['custom_delivery_text']) ? trim($_POST['custom_delivery_text']) : NULL;

    // Deneme Paketi Özel Alanları
    $package_delivery_type = !empty($_POST['package_delivery_type']) ? $_POST['package_delivery_type'] : NULL;
    $package_delivery_count = !empty($_POST['package_delivery_count']) ? (int)$_POST['package_delivery_count'] : 1;

    $publish_date = !empty($_POST['publish_date']) ? $_POST['publish_date'] : date('Y-m-d H:i:s');
    $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : NULL;

    // Zorunlu Alan Kontrolü
    if (empty($name) || empty($price)) {
        $mesaj = "<div class='alert alert-warning shadow-sm'><i class='bi bi-exclamation-triangle me-2'></i>Ürün adı ve fiyat alanları zorunludur.</div>";
    } else {

        try {
            $db->beginTransaction();

            $file_path = NULL;
            if ($type == 'digital' && isset($_FILES['digital_file']) && $_FILES['digital_file']['error'] === UPLOAD_ERR_OK) {
                $ext = strtolower(pathinfo($_FILES['digital_file']['name'], PATHINFO_EXTENSION));
                $dosya_adi = $slug . '-' . time() . '.' . $ext;
                $hedef = '../../uploads/downloads/' . $dosya_adi; 
                if (move_uploaded_file($_FILES['digital_file']['tmp_name'], $hedef)) {
                    $file_path = 'uploads/downloads/' . $dosya_adi;
                }
            }

            // 1. Ürünü Kaydet
            // Eğer exam_package ise kategori null olabilir (ara tabloda tutacağız)
            $main_category_insert = ($type == 'exam_package' && !empty($selected_categories)) ? $selected_categories[0] : $category_id;

            $stmt = $db->prepare("INSERT INTO products (category_id, brand_id, type, name, slug, description, file_path, duration_days, total_deliveries, package_delivery_type, package_delivery_count, price, discount_price, vat_rate, vat_included, stock_quantity, sku, shipping_info, is_free_shipping, custom_payment_text, custom_delivery_text, publish_date, end_date, status, exam_type, exam_publication_date, exam_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)");
            
            $stmt->execute([$main_category_insert, $brand_id, $type, $name, $slug, $description, $file_path, $duration_days, $total_deliveries, $package_delivery_type, $package_delivery_count, $price, $discount_price, $vat_rate, $vat_included, $stock_quantity, $sku, $shipping_info, $is_free_shipping, $custom_payment_text, $custom_delivery_text, $publish_date, $end_date, $exam_type, $exam_publication_date, $exam_date]);
            
            $product_id = $db->lastInsertId();

            // 2. Deneme Paketi İse Çoklu Kategorileri ve Seçilen Denemeleri Kaydet
            if ($type == 'exam_package') {
                // Kategorileri Ekle (product_categories pivot tablosuna)
                if (!empty($selected_categories)) {
                    $cat_stmt = $db->prepare("INSERT INTO product_categories (product_id, category_id) VALUES (?, ?)");
                    foreach ($selected_categories as $cat_id) {
                        $cat_stmt->execute([$product_id, $cat_id]);
                    }
                }

                // Denemeleri Ekle ve Gönderim Tarihlerini Kaydet (package_items pivot tablosuna)
                if (isset($_POST['package_items']) && is_array($_POST['package_items'])) {
                    $pack_stmt = $db->prepare("INSERT INTO package_items (package_product_id, exam_product_id, delivery_sequence, delivery_date) VALUES (?, ?, ?, ?)");
                    
                    foreach ($_POST['package_items'] as $sequence => $exam_ids) {
                        $delivery_date = !empty($_POST['package_delivery_dates'][$sequence]) ? $_POST['package_delivery_dates'][$sequence] : NULL;
                        foreach ($exam_ids as $exam_id) {
                            $pack_stmt->execute([$product_id, $exam_id, $sequence, $delivery_date]);
                        }
                    }
                }
            }

            // 3. Çoklu Görsel Yükleme İşlemi (AKILLI MOTOR İLE)
            if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
                $dosya_sayisi = count($_FILES['images']['name']);
                for ($i = 0; $i < $dosya_sayisi; $i++) {
                    if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
                        $tmp_name = $_FILES['images']['tmp_name'][$i];
                        $orijinal_isim = $_FILES['images']['name'][$i];
                        $optimize_yol = uploadAndOptimizeImage($tmp_name, $orijinal_isim);
                        if ($optimize_yol) {
                            $is_main = ($i === 0) ? 1 : 0; 
                            $db->prepare("INSERT INTO product_images (product_id, image_path, is_main) VALUES (?, ?, ?)")->execute([$product_id, $optimize_yol, $is_main]);
                        }
                    }
                }
            }

            $db->commit();
            $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i>Ürün/Paket tüm detaylarıyla başarıyla eklendi! <a href='index.php' class='fw-bold'>Listeye Dön</a></div>";

        } catch (Exception $e) {
            $db->rollBack();
            $mesaj = "<div class='alert alert-danger shadow-sm'><i class='bi bi-x-circle-fill me-2'></i>Hata Oluştu: " . $e->getMessage() . "</div>";
        }
    }
}

// Tüm benzersiz sınav türlerini çek (Filtreleme için)
$turler = $db->query("SELECT DISTINCT exam_type FROM products WHERE type = 'single_exam' AND exam_type IS NOT NULL")->fetchAll(PDO::FETCH_COLUMN);

// --- TASARIM BAŞLANGICI ---
require_once '../header.php';
?>

<div class="row mb-4 align-items-center">
    <div class="col-6">
        <h2 class="fw-bold mb-0 text-dark"><i class="bi bi-plus-circle-fill text-success me-2"></i>Kapsamlı Ürün Ekle</h2>
    </div>
    <div class="col-6 text-end">
        <a href="index.php" class="btn btn-outline-secondary shadow-sm fw-bold"><i class="bi bi-arrow-left me-1"></i> İptal / Geri Dön</a>
    </div>
</div>

<?= $mesaj; ?>

<form action="ekle.php" method="POST" enctype="multipart/form-data" class="mb-5">
    <div class="row">
        <div class="col-md-8">
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-dark text-white py-3">
                    <h5 class="card-title mb-0 fw-bold small text-uppercase"><i class="bi bi-info-circle me-2"></i>Temel Bilgiler</h5>
                </div>
                <div class="card-body p-4">
                    <div class="row mb-4">
                        <div class="col-md-5">
                            <label class="form-label fw-bold text-muted small text-uppercase">Ürün / Paket Adı *</label>
                            <input type="text" name="name" class="form-control form-control-lg border-2" required placeholder="Örn: 3 Aylık TYT Deneme">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold text-muted small text-uppercase">SEO Link (İsteğe Bağlı)</label>
                            <input type="text" name="custom_slug" class="form-control form-control-lg border-2" placeholder="Boşsa otomatik oluşur">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-bold text-muted small text-uppercase">Ürün Kodu (SKU)</label>
                            <input type="text" name="sku" class="form-control form-control-lg border-2" placeholder="Örn: LGS-MAT-01">
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <label class="form-label fw-bold text-muted small text-uppercase">Ürün Tipi *</label>
                            <select name="type" id="productType" class="form-select border-2" required>
                                <option value="physical">Fiziksel Ürün (Tek Seferlik)</option>
                                <option value="single_exam">Tekli Deneme Sınavı</option> 
                                <option value="subscription">Abonelik (Fiziksel Gönderim)</option>
                                <option value="digital">Dijital Ürün (İndirilebilir)</option>
                                <option value="exam_package">Deneme Paketi (Kombinasyon)</option>
                            </select>
                        </div>
                        
                        <div class="col-md-4" id="standardCategoryDiv">
                            <label class="form-label fw-bold text-muted small text-uppercase">Kategori</label>
                            <select name="category_id" class="form-select border-2">
                                <option value="">Seçiniz...</option>
                                <?php foreach($kategoriler as $kat): ?>
                                    <option value="<?= $kat['id']; ?>"><?= htmlspecialchars($kat['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="col-md-4" id="multipleCategoryDiv" style="display: none;">
                            <label class="form-label fw-bold text-muted small text-uppercase text-primary">Kategori (Çoklu Seçim)</label>
                            <select name="categories[]" class="form-select border-2" multiple style="height: 100px;">
                                <?php foreach($kategoriler as $kat): ?>
                                    <option value="<?= $kat['id']; ?>"><?= htmlspecialchars($kat['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted" style="font-size:0.7rem;">CTRL veya SHIFT ile çoklu seçin.</small>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label fw-bold text-muted small text-uppercase">Marka / Yayınevi</label>
                            <select name="brand_id" class="form-select border-2">
                                <option value="">Karma / Belirtilmemiş</option>
                                <?php foreach($markalar as $marka): ?>
                                    <option value="<?= $marka['id']; ?>"><?= htmlspecialchars($marka['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Detaylı Açıklama</label>
                        <textarea name="description" class="form-control editor border-2" rows="10" placeholder="İçerik detaylarını yazın..."></textarea>
                    </div>

                    <div class="mb-0 p-3 bg-light rounded border-2 border-dashed">
                        <label class="form-label fw-bold text-muted small text-uppercase"><i class="bi bi-images me-1 text-primary"></i>Ürün Görselleri (Çoklu Seçim)</label>
                        <input type="file" name="images[]" class="form-control border-0 bg-transparent" accept="image/*" multiple>
                        <div class="form-text text-primary small mt-2 fw-bold"><i class="bi bi-info-circle-fill"></i> (Önerilen Boyut: 600x800 px) - Sıkıştırma motoru aktiftir, yüksek çözünürlüklü yükleyebilirsiniz.</div>
                    </div>
                </div>
            </div>

            <div id="singleExamFields" class="card shadow-sm border-0 mb-4 bg-light border-start border-4 border-danger" style="display: none;">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="card-title mb-0 fw-bold text-danger small text-uppercase"><i class="bi bi-journal-bookmark me-2"></i>Deneme Sınavı Detayları</h5>
                </div>
                <div class="card-body p-4">
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold small text-uppercase text-muted">Sınav Türü (Örn: TYT)</label>
                            <input type="text" name="exam_type" class="form-control border-2 bg-white" placeholder="TYT, AYT, LGS...">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold small text-uppercase text-muted">Yayın Tarihi</label>
                            <input type="text" name="exam_publication_date" class="form-control border-2 bg-white" placeholder="Örn: 14.09.2025">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label fw-bold small text-uppercase text-muted">Uygulanma Tarihi</label>
                            <input type="date" name="exam_date" class="form-control border-2 bg-white">
                        </div>
                    </div>
                </div>
            </div>

            <div id="digitalFields" class="card shadow-sm border-0 mb-4 bg-light border-start border-4 border-info" style="display: none;">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-info text-uppercase mb-3"><i class="bi bi-cloud-arrow-up me-2"></i>Dijital Dosya Yükle</h6>
                    <input type="file" name="digital_file" class="form-control border-2 bg-white" accept=".pdf,.zip,.rar,.mp4">
                    <small class="text-muted mt-2 d-block">Müşteri satın aldıktan sonra bu dosyayı panosundan indirebilecektir.</small>
                </div>
            </div>

            <div id="subscriptionFields" class="card shadow-sm border-0 mb-4 bg-light border-start border-4 border-warning" style="display: none;">
                <div class="card-body p-4">
                    <h6 class="fw-bold text-warning text-uppercase mb-3"><i class="bi bi-calendar-check text-dark me-2"></i>Abonelik Lojistik Takvimi</h6>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold small">Toplam Kargo Sayısı (Ay)</label>
                            <div class="input-group">
                                <input type="number" name="total_deliveries" class="form-control border-2 bg-white" placeholder="Örn: 3" value="1" min="1">
                                <span class="input-group-text bg-warning text-dark border-2 fw-bold">TESLİMAT</span>
                            </div>
                            <small class="text-muted">Bu paket süresince toplam kaç ay kargo gönderilecek?</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold small">Erişim Süresi (Gün)</label>
                            <div class="input-group">
                                <input type="number" name="duration_days" class="form-control border-2 bg-white" placeholder="Örn: 90" value="30">
                                <span class="input-group-text bg-light border-2 fw-bold">GÜN</span>
                            </div>
                            <small class="text-muted">Sisteme dijital erişim süresi.</small>
                        </div>
                    </div>
                </div>
            </div>

            <div id="packageFields" class="card shadow-sm border-0 mb-4 bg-light border-start border-4 border-primary" style="display: none;">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0 fw-bold text-primary small text-uppercase"><i class="bi bi-box-seam me-2"></i>Deneme Paketi Yapılandırması</h5>
                </div>
                <div class="card-body p-4">
                    <div class="row mb-4 bg-white p-3 rounded border">
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-dark small">Paket Gönderim Türü *</label>
                            <select name="package_delivery_type" id="packageDeliveryType" class="form-select border-2">
                                <option value="single">Tek Seferde Gönderim</option>
                                <option value="weekly">Haftalık Gönderim (Abonelik)</option>
                                <option value="monthly">Aylık Gönderim (Abonelik)</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-dark small">Toplam Gönderim (Kargo) Sayısı *</label>
                            <div class="input-group">
                                <input type="number" name="package_delivery_count" id="packageDeliveryCount" class="form-control border-2 fw-bold" value="1" min="1" max="52">
                                <button type="button" class="btn btn-primary fw-bold" id="btnGenerateBoxes">Oluştur <i class="bi bi-arrow-down"></i></button>
                            </div>
                            <small class="text-muted d-block mt-1">Sayıyı girip "Oluştur"a basın.</small>
                        </div>
                    </div>

                    <div class="bg-dark p-3 rounded mb-3 text-white" id="filterArea" style="display:none;">
                        <h6 class="fw-bold small text-uppercase mb-3"><i class="bi bi-search me-2"></i>Havuzdan Deneme Bul</h6>
                        <div class="row g-2 mb-2">
                            <div class="col-md-3">
                                <label class="small text-muted mb-1">Sınav Türü</label>
                                <select id="filterTur" class="form-select form-select-sm" title="Sınav Türü">
                                    <option value="">Tüm Türler</option>
                                    <?php foreach($turler as $t): ?>
                                        <option value="<?= htmlspecialchars($t) ?>"><?= htmlspecialchars($t) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="small text-muted mb-1">Yayın Evi</label>
                                <select id="filterMarka" class="form-select form-select-sm" title="Yayın Evi">
                                    <option value="">Tüm Yayınlar</option>
                                    <?php foreach($markalar as $marka): ?>
                                        <option value="<?= $marka['id']; ?>"><?= htmlspecialchars($marka['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <label class="small text-muted mb-1">Sınav Tarihi (Başlangıç)</label>
                                <input type="date" id="filterBaslangic" class="form-control form-control-sm" title="Sınav Uygulanma Tarihi (Başlangıç)">
                            </div>
                            <div class="col-md-3">
                                <label class="small text-muted mb-1">Sınav Tarihi (Bitiş)</label>
                                <input type="date" id="filterBitis" class="form-control form-control-sm" title="Sınav Uygulanma Tarihi (Bitiş)">
                            </div>
                        </div>
                        <div class="row g-2">
                            <div class="col-12">
                                <div class="input-group input-group-sm">
                                    <input type="text" id="filterArama" class="form-control" placeholder="Deneme Adı veya SKU Kodu yazın...">
                                    <button class="btn btn-success fw-bold px-4" type="button" id="btnSearchExams">DENEMELERİ BUL</button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div id="examResultsArea" class="row mb-4" style="max-height: 250px; overflow-y: auto; display:none;">
                    </div>

                    <div id="deliveryBoxesArea" class="mt-4">
                    </div>

                </div>
            </div>

            <div id="shippingFields" class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="card-title mb-0 fw-bold text-secondary small text-uppercase"><i class="bi bi-truck me-2 text-primary"></i>Kargo Bilgisi</h5>
                </div>
                <div class="card-body p-4">
                    <div class="row align-items-center">
                        <div class="col-md-7 mb-3 mb-md-0">
                            <label class="form-label fw-bold text-muted small text-uppercase">Gönderim Takvimi Notu</label>
                            <input type="text" name="shipping_info" class="form-control border-2" placeholder="Örn: Her ayın 10. günü kargolanır.">
                        </div>
                        <div class="col-md-5 d-flex justify-content-md-end align-items-center">
                            <div class="form-check form-switch fs-5">
                                <input class="form-check-input" type="checkbox" id="freeShipping" name="is_free_shipping" value="1" checked>
                                <label class="form-check-label ms-2 fw-bold text-success small text-uppercase" for="freeShipping">Ücretsiz Kargo</label>
                            </div>
                        </div>
                        <div class="col-12 mt-3">
                            <div class="alert alert-secondary py-2 mb-0" style="font-size: 0.8rem;">
                                <i class="bi bi-info-circle-fill text-primary me-1"></i> <b>Kargo Sistemi Nasıl Çalışır?</b> <br>
                                Eğer üstteki "Ücretsiz Kargo" butonu <b>açıksa</b>, bu ürün her halükarda ücretsiz kargolanır (Büyük abonelik paketlerinde önerilir).<br>
                                Eğer buton <b>kapalıysa</b> (Tekli denemelerde önerilir), sepet sisteminizdeki <i>"1000 TL Üzeri Ücretsiz"</i> veya <i>"4 Adet Deneme Alana Ücretsiz"</i> gibi genel sepet kuralları devreye girer.
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm border-0 mb-4 bg-light border-start border-4 border-secondary">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="card-title mb-0 fw-bold text-secondary small text-uppercase"><i class="bi bi-file-earmark-text me-2"></i>Özel Sekme İçerikleri (Opsiyonel)</h5>
                </div>
                <div class="card-body p-4">
                    <div class="alert alert-info py-2" style="font-size: 0.85rem;">
                        <i class="bi bi-info-circle-fill me-1"></i> <b>Not:</b> Bu alanları boş bırakırsanız, ürün detay sayfasında sitenin standart <b>"Ödeme Seçenekleri"</b> ve <b>"Teslimat & İade"</b> metinleri gösterilir. Sadece bu ürüne özel bir istisna varsa doldurunuz.
                    </div>
                    
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Ürüne Özel Ödeme Seçenekleri</label>
                        <textarea name="custom_payment_text" class="form-control editor border-2" rows="4" placeholder="Sadece bu ürüne özel ödeme şartı varsa yazın..."></textarea>
                    </div>
                    
                    <div class="mb-0">
                        <label class="form-label fw-bold text-muted small text-uppercase">Ürüne Özel Teslimat & İade Şartları</label>
                        <textarea name="custom_delivery_text" class="form-control editor border-2" rows="4" placeholder="Örn: Bu ürün kırılabilecek eşya statüsünde olduğu için kargo görevlisi yanında açılmalıdır..."></textarea>
                    </div>
                </div>
            </div>

        </div>

        <div class="col-md-4">
            <div class="card shadow-sm mb-4 border-primary border-top border-4">
                <div class="card-header bg-primary text-white py-3 text-center">
                    <h5 class="card-title mb-0 fw-bold small text-uppercase"><i class="bi bi-cash-stack me-2"></i>Fiyat & Stok</h5>
                </div>
                <div class="card-body p-4">
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Paket Fiyatı (₺) *</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light fw-bold border-2 border-end-0">₺</span>
                            <input type="number" step="0.01" name="price" class="form-control form-control-lg fw-bold text-primary border-2 border-start-0" required placeholder="0.00">
                        </div>
                    </div>
                    <div class="mb-4">
                        <label class="form-label fw-bold text-danger small text-uppercase">İndirimli Fiyat (₺)</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light text-danger fw-bold border-2 border-end-0">₺</span>
                            <input type="number" step="0.01" name="discount_price" class="form-control fw-bold text-danger border-2 border-start-0" placeholder="0.00">
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">KDV Oranı</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light fw-bold border-2">%</span>
                                <select name="vat_rate" class="form-select fw-bold border-2">
                                    <option value="0">0</option>
                                    <option value="1">1</option>
                                    <option value="10">10</option>
                                    <option value="20" selected>20</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">KDV Durumu</label>
                            <select name="vat_included" class="form-select fw-bold border-2">
                                <option value="1" selected>KDV Dahil</option>
                                <option value="0">KDV Hariç</option>
                            </select>
                        </div>
                    </div>

                    <div class="mb-0">
                        <label class="form-label fw-bold text-muted small text-uppercase">Mevcut Stok (Paket)</label>
                        <input type="number" name="stock_quantity" class="form-control fw-bold border-2" value="100">
                    </div>
                </div>
            </div>

            <div class="card shadow-sm mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="card-title mb-0 fw-bold text-secondary small text-uppercase"><i class="bi bi-clock-history me-2 text-warning"></i>Zamanlama</h5>
                </div>
                <div class="card-body p-4">
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Yayınlanma Tarihi</label>
                        <input type="datetime-local" name="publish_date" class="form-control border-2" value="<?= date('Y-m-d\TH:i'); ?>">
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-bold text-muted small text-uppercase">Bitiş Tarihi</label>
                        <input type="datetime-local" name="end_date" class="form-control border-2">
                    </div>
                </div>
            </div>

            <div class="d-grid gap-2">
                <button type="submit" name="urun_ekle" class="btn btn-success btn-lg fw-bold shadow-sm py-3">
                    <i class="bi bi-cloud-arrow-up-fill me-2"></i>ÜRÜNÜ YAYINA AL
                </button>
            </div>
        </div>
    </div>
</form>

<script src="https://cdn.tiny.cloud/1/vrj5aef2zvyqm82vfs8ay0ltvq1l9v6bmkio7ovzkqj8trrq/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
    tinymce.init({
        selector: '.editor',
        height: 300,
        menubar: false,
        plugins: 'lists link table code wordcount',
        toolbar: 'undo redo | formatselect | bold italic textcolor | alignleft aligncenter alignright alignjustify | bullist numlist | removeformat',
        language: 'tr'
    });

    document.addEventListener("DOMContentLoaded", function() {
        const typeSelect = document.getElementById('productType');
        const shippingDiv = document.getElementById('shippingFields');
        const digitalDiv = document.getElementById('digitalFields');
        const subDiv = document.getElementById('subscriptionFields');
        const packageDiv = document.getElementById('packageFields');
        const stdCatDiv = document.getElementById('standardCategoryDiv');
        const multiCatDiv = document.getElementById('multipleCategoryDiv');
        const singleExamDiv = document.getElementById('singleExamFields'); // YENİ: Tekli deneme alanı

        function updateFields() {
            const type = typeSelect.value;
            
            // Mevcut Alanların Gizlenip/Gösterilmesi
            shippingDiv.style.display = (type === 'digital') ? 'none' : 'block';
            digitalDiv.style.display = (type === 'digital') ? 'block' : 'none';
            subDiv.style.display = (type === 'subscription') ? 'block' : 'none';
            packageDiv.style.display = (type === 'exam_package') ? 'block' : 'none';
            singleExamDiv.style.display = (type === 'single_exam') ? 'block' : 'none'; // YENİ
            
            // Kategori alanı (Paket ise çoklu seçim aktif olur)
            if (type === 'exam_package') {
                stdCatDiv.style.display = 'none';
                multiCatDiv.style.display = 'block';
            } else {
                stdCatDiv.style.display = 'block';
                multiCatDiv.style.display = 'none';
            }
        }

        typeSelect.addEventListener('change', updateFields);
        updateFields(); 
        
        // ==========================================
        // DENEME PAKETİ DİNAMİK ALANLARI VE AJAX
        // ==========================================
        
        const btnGenerateBoxes = document.getElementById('btnGenerateBoxes');
        const deliveryBoxesArea = document.getElementById('deliveryBoxesArea');
        const filterArea = document.getElementById('filterArea');
        const examResultsArea = document.getElementById('examResultsArea');
        const btnSearchExams = document.getElementById('btnSearchExams');

        // 1. Kutu Oluşturucu
        btnGenerateBoxes.addEventListener('click', function() {
            const count = parseInt(document.getElementById('packageDeliveryCount').value) || 1;
            deliveryBoxesArea.innerHTML = ''; // Önceki kutuları temizle
            
            for (let i = 1; i <= count; i++) {
                let boxHTML = `
                <div class="card mb-3 border-2 border-primary shadow-sm">
                    <div class="card-header bg-primary text-white py-2 d-flex justify-content-between align-items-center">
                        <h6 class="mb-0 fw-bold"><i class="bi bi-box-seam me-2"></i>${i}. Gönderim Paketi</h6>
                        <div class="d-flex align-items-center">
                            <label class="small me-2 mb-0 fw-bold">Kargolanma Tarihi: *</label>
                            <input type="date" name="package_delivery_dates[${i}]" class="form-control form-control-sm text-dark fw-bold" style="width: 130px;" required>
                        </div>
                    </div>
                    <div class="card-body bg-white p-3">
                        <p class="text-muted small mb-2"><i class="bi bi-info-circle"></i> Yukarıdaki havuzdan arama yapıp çıkan sonuçlardan bu haftaya/gönderime eklemek istediklerinizi seçin.</p>
                        <div class="row" id="delivery_box_${i}">
                        </div>
                    </div>
                </div>`;
                deliveryBoxesArea.insertAdjacentHTML('beforeend', boxHTML);
            }
            
            // Filtre ve Sonuç alanını görünür yap
            filterArea.style.display = 'block';
            examResultsArea.style.display = 'flex';
        });

        // 2. AJAX İle Deneme Getirme
        btnSearchExams.addEventListener('click', function() {
            const tur = document.getElementById('filterTur').value;
            const marka = document.getElementById('filterMarka').value;
            const arama = document.getElementById('filterArama').value;
            const baslangic = document.getElementById('filterBaslangic').value;
            const bitis = document.getElementById('filterBitis').value;
            
            examResultsArea.innerHTML = '<div class="col-12 text-center py-3"><div class="spinner-border text-primary" role="status"></div></div>';
            
            fetch('ajax_deneme_getir.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({
                    'tur': tur,
                    'marka_id': marka,
                    'arama': arama,
                    'baslangic_tarihi': baslangic,
                    'bitis_tarihi': bitis
                })
            })
            .then(response => response.json())
            .then(data => {
                examResultsArea.innerHTML = '';
                
                if(data.status === 'success' && data.count > 0) {
                    const count = parseInt(document.getElementById('packageDeliveryCount').value) || 1;
                    
                    data.data.forEach(exam => {
                        let options = `<option value="">Gönderime Ekle...</option>`;
                        for(let j=1; j<=count; j++) {
                            options += `<option value="${j}">${j}. Gönderim</option>`;
                        }
                        
                        let formattedDate = exam.formatted_date ? exam.formatted_date : 'Tarih Yok';
                        let imageSrc = '/magaza/assets/img/no-image.jpg';
                        if (exam.main_image && exam.main_image !== '') {
                            imageSrc = '/magaza/' + exam.main_image;
                        } else if (exam.brand_logo && exam.brand_logo !== '') {
                            imageSrc = '/magaza/' + exam.brand_logo;
                        }
                        
                        let cardHTML = `
                        <div class="col-md-6 col-lg-4 mb-2">
                            <div class="border rounded p-2 d-flex align-items-center bg-white shadow-sm h-100">
                                <img src="${imageSrc}" width="40" height="40" class="rounded object-fit-cover me-2 border bg-light">
                                <div class="flex-grow-1 overflow-hidden">
                                    <div class="fw-bold text-truncate" style="font-size:0.8rem;" title="${exam.name}">${exam.name}</div>
                                    <div class="text-muted" style="font-size:0.7rem;">${exam.exam_type} | <span class="text-danger fw-bold">${formattedDate}</span></div>
                                </div>
                                <div class="ms-2">
                                    <select class="form-select form-select-sm border-2 fw-bold text-primary exam-assigner" data-exam-id="${exam.id}" data-exam-name="${exam.name}" style="width: 100px; font-size:0.75rem;">
                                        ${options}
                                    </select>
                                </div>
                            </div>
                        </div>`;
                        examResultsArea.insertAdjacentHTML('beforeend', cardHTML);
                    });
                    attachAssignmentEvents();
                } else {
                    examResultsArea.innerHTML = '<div class="col-12 text-center py-3 text-muted">Arama ve tarih kriterlerine uygun sonuç bulunamadı.</div>';
                }
            })
            .catch(error => {
                examResultsArea.innerHTML = '<div class="col-12 text-center py-3 text-danger">Bağlantı hatası! Lütfen tekrar deneyin.</div>';
            });
        });

        // 3. Seçilen Denemeyi Gönderim Kutusuna Aktarma Mantığı
        function attachAssignmentEvents() {
            const assigners = document.querySelectorAll('.exam-assigner');
            assigners.forEach(select => {
                select.addEventListener('change', function() {
                    const targetBoxNum = this.value;
                    const examId = this.getAttribute('data-exam-id');
                    const examName = this.getAttribute('data-exam-name');
                    
                    if (targetBoxNum) {
                        const targetBox = document.getElementById(`delivery_box_${targetBoxNum}`);
                        
                        if(!targetBox.querySelector(`input[value="${examId}"]`)) {
                            let addedHTML = `
                            <div class="col-12 mb-2">
                                <div class="alert alert-secondary m-0 p-2 d-flex justify-content-between align-items-center border-0 shadow-sm">
                                    <div style="font-size:0.85rem;"><i class="bi bi-check2-square text-success me-2"></i>${examName}</div>
                                    <button type="button" class="btn btn-sm btn-danger py-0 px-2" onclick="this.parentElement.parentElement.remove()">X</button>
                                    <input type="hidden" name="package_items[${targetBoxNum}][]" value="${examId}">
                                </div>
                            </div>`;
                            targetBox.insertAdjacentHTML('beforeend', addedHTML);
                        } else {
                            alert('Bu deneme bu gönderim paketinde zaten var!');
                        }
                        this.value = '';
                    }
                });
            });
        }
    });
</script>

<?php require_once '../footer.php'; ?>