<?php
/**
 * Admin Ürün Düzenleme Sayfası (Deneme Paketi Destekli)
 * Konum: /magaza/admin/urunler/duzenle.php
 */

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

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

$mesaj = '';

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: index.php");
    exit;
}
$urun_id = (int)$_GET['id'];

// Ana Ürün Bilgilerini Çek
$stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$urun_id]);
$urun = $stmt->fetch();

if (!$urun) die("<div class='alert alert-danger m-4 text-dark'>Ürün bulunamadı! <a href='index.php'>Geri Dön</a></div>");

// --- DENEME PAKETİ ÖZEL VERİLERİNİ ÇEK ---
$secili_kategoriler = [];
$paket_icerigi = [];
if ($urun['type'] == 'exam_package') {
    // Çoklu kategorileri çek
    $secili_kategoriler = $db->prepare("SELECT category_id FROM product_categories WHERE product_id = ?");
    $secili_kategoriler->execute([$urun_id]);
    $secili_kategoriler = $secili_kategoriler->fetchAll(PDO::FETCH_COLUMN);

    // Paket içeriğini (denemeleri ve tarihleri) çek
    $icerik_stmt = $db->prepare("
        SELECT pi.*, p.name as exam_name 
        FROM package_items pi 
        JOIN products p ON pi.exam_product_id = p.id 
        WHERE pi.package_product_id = ? 
        ORDER BY pi.delivery_sequence ASC
    ");
    $icerik_stmt->execute([$urun_id]);
    $raw_icerik = $icerik_stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Veriyi sequence (gönderim sırası) bazlı gruplayalım
    foreach ($raw_icerik as $item) {
        $paket_icerigi[$item['delivery_sequence']]['date'] = $item['delivery_date'];
        $paket_icerigi[$item['delivery_sequence']]['exams'][] = [
            'id' => $item['exam_product_id'],
            'name' => $item['exam_name']
        ];
    }
}

// --- GÖRSEL YÖNETİMİ ---
if (isset($_GET['gorsel_sil']) && is_numeric($_GET['gorsel_sil'])) {
    $gorsel_id = (int)$_GET['gorsel_sil'];
    $g_stmt = $db->prepare("SELECT image_path FROM product_images WHERE id = ? AND product_id = ?");
    $g_stmt->execute([$gorsel_id, $urun_id]);
    $g_yol = $g_stmt->fetchColumn();

    if ($g_yol) {
        $fiziksel_yol = '../../' . $g_yol;
        if(file_exists($fiziksel_yol)) unlink($fiziksel_yol); 
        $db->prepare("DELETE FROM product_images WHERE id = ?")->execute([$gorsel_id]);
        $mesaj = "<div class='alert alert-info shadow-sm text-dark'><i class='bi bi-trash me-2'></i>Görsel silindi.</div>";
    }
}

if (isset($_GET['ana_yap']) && is_numeric($_GET['ana_yap'])) {
    $gorsel_id = (int)$_GET['ana_yap'];
    $db->prepare("UPDATE product_images SET is_main = 0 WHERE product_id = ?")->execute([$urun_id]);
    $db->prepare("UPDATE product_images SET is_main = 1 WHERE id = ?")->execute([$gorsel_id]);
    $mesaj = "<div class='alert alert-info shadow-sm text-dark'><i class='bi bi-star-fill me-2'></i>Ana görsel güncellendi.</div>";
}

$gorseller_stmt = $db->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY is_main DESC, id ASC");
$gorseller_stmt->execute([$urun_id]);
$mevcut_gorseller = $gorseller_stmt->fetchAll();

$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();
$turler = $db->query("SELECT DISTINCT exam_type FROM products WHERE type = 'single_exam' AND exam_type IS NOT NULL")->fetchAll(PDO::FETCH_COLUMN);

// --- GÜNCELLEME İŞLEMİ ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['urun_guncelle'])) {
    
    $name = trim($_POST['name']);
    $type = $_POST['type'];
    $brand_id = !empty($_POST['brand_id']) ? $_POST['brand_id'] : NULL;
    $description = trim($_POST['description']);
    $sku = !empty($_POST['sku']) ? trim($_POST['sku']) : NULL;
    
    // 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 (veya mevcut slug korunduysa) onu kullan
        $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ü (Aynı link başka üründe var mı?)
    $check = $db->prepare("SELECT id FROM products WHERE slug = ? AND id != ?");
    $check->execute([$slug, $urun_id]);
    if ($check->rowCount() > 0) { 
        if (!empty($sku)) {
            $slug = seoLink($name . '-' . $sku); // Varsa SKU ile birleştir
        } else {
            $slug = $slug . '-' . substr(md5(uniqid()), 0, 5); 
        }
    }
    // --------------------------------------

    $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;
    
    $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;
    
    // YENİ: Ü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;

    // Paket Ö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'] : NULL;
    $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : NULL;
    $status = isset($_POST['status']) ? (int)$_POST['status'] : 1;

    if (empty($name) || empty($price)) {
        $mesaj = "<div class='alert alert-warning text-dark'>Ürün adı ve fiyat zorunludur.</div>";
    } else {
        
        try {
            $db->beginTransaction();

            // Dosya Yönetimi
            $file_path = $urun['file_path'];
            if ($type == 'digital' && isset($_FILES['digital_file']) && $_FILES['digital_file']['error'] === UPLOAD_ERR_OK) {
                if ($file_path && file_exists('../../' . $file_path)) unlink('../../' . $file_path);
                $dosya_adi = $slug . '-doc-' . time() . '.' . strtolower(pathinfo($_FILES['digital_file']['name'], PATHINFO_EXTENSION));
                if (move_uploaded_file($_FILES['digital_file']['tmp_name'], '../../uploads/downloads/' . $dosya_adi)) {
                    $file_path = 'uploads/downloads/' . $dosya_adi;
                }
            }

            // Kategori Yönetimi
            $selected_categories = (isset($_POST['categories']) && is_array($_POST['categories'])) ? $_POST['categories'] : [];
            $category_id = ($type == 'exam_package' && !empty($selected_categories)) ? $selected_categories[0] : (!empty($_POST['category_id']) ? $_POST['category_id'] : NULL);

            // YENİ: custom_payment_text, custom_delivery_text, exam_type, exam_publication_date, exam_date EKLENDİ
            $update_sql = "UPDATE products SET 
                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=? 
                WHERE id=?";
            $db->prepare($update_sql)->execute([
                $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, $urun_id
            ]);
            
            // FİYAT ALARMI BİLDİRİM TETİKLEYİCİ
            $guncel_satis_fiyati = (!empty($discount_price) && $discount_price > 0) ? $discount_price : $price;
            checkAndNotifyPriceAlerts($urun_id, $guncel_satis_fiyati);

            // Paket İçeriği ve Çoklu Kategori Güncelleme
            if ($type == 'exam_package') {
                // 1. Kategorileri Güncelle
                $db->prepare("DELETE FROM product_categories WHERE product_id = ?")->execute([$urun_id]);
                $cat_stmt = $db->prepare("INSERT INTO product_categories (product_id, category_id) VALUES (?, ?)");
                foreach ($selected_categories as $cat_id) { $cat_stmt->execute([$urun_id, $cat_id]); }

                // 2. Paket İçeriğini Güncelle
                $db->prepare("DELETE FROM package_items WHERE package_product_id = ?")->execute([$urun_id]);
                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([$urun_id, $exam_id, $sequence, $delivery_date]);
                        }
                    }
                }
            }

            // Görsel Yükleme
            if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
                for ($i = 0; $i < count($_FILES['images']['name']); $i++) {
                    if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
                        $optimize_yol = uploadAndOptimizeImage($_FILES['images']['tmp_name'][$i], $_FILES['images']['name'][$i]);
                        if ($optimize_yol) {
                            $is_main = (count($mevcut_gorseller) == 0 && $i == 0) ? 1 : 0; 
                            $db->prepare("INSERT INTO product_images (product_id, image_path, is_main) VALUES (?, ?, ?)")->execute([$urun_id, $optimize_yol, $is_main]);
                        }
                    }
                }
            }

            $db->commit();
            $mesaj = "<div class='alert alert-success shadow-sm text-dark'><i class='bi bi-check-circle-fill me-2'></i>Değişiklikler kaydedildi! <a href='index.php' class='fw-bold'>Listeye Dön</a></div>";
            
            // Verileri yenileyelim
            $stmt->execute([$urun_id]); $urun = $stmt->fetch();
            $gorseller_stmt->execute([$urun_id]); $mevcut_gorseller = $gorseller_stmt->fetchAll();

        } catch (Exception $e) {
            $db->rollBack();
            $mesaj = "<div class='alert alert-danger shadow-sm text-dark'>Hata: " . $e->getMessage() . "</div>";
        }
    }
}

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-pencil-square text-warning me-2"></i>Ürün Düzenle</h2>
        <span class="text-muted small"><?= htmlspecialchars($urun['name']) ?></span>
    </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</a>
    </div>
</div>

<?= $mesaj; ?>

<form action="duzenle.php?id=<?= $urun_id ?>" method="POST" enctype="multipart/form-data" class="mb-5">
    <div class="row text-dark">
        <div class="col-md-8">
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center 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>
                    <select name="status" class="form-select form-select-sm w-auto fw-bold <?= $urun['status'] == 1 ? 'bg-success text-white' : 'bg-danger text-white' ?>">
                        <option value="1" <?= $urun['status'] == 1 ? 'selected' : '' ?>>AKTİF</option>
                        <option value="0" <?= $urun['status'] == 0 ? 'selected' : '' ?>>PASİF</option>
                    </select>
                </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 Adı *</label>
                            <input type="text" name="name" class="form-control form-control-lg border-2" required value="<?= htmlspecialchars($urun['name']) ?>">
                        </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" value="<?= htmlspecialchars($urun['slug']) ?>">
                        </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" value="<?= htmlspecialchars($urun['sku'] ?? '') ?>">
                        </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" <?= $urun['type'] == 'physical' ? 'selected' : '' ?>>Fiziksel Ürün</option>
                                <option value="single_exam" <?= $urun['type'] == 'single_exam' ? 'selected' : '' ?>>Tekli Deneme Sınavı</option> 
                                <option value="subscription" <?= $urun['type'] == 'subscription' ? 'selected' : '' ?>>Abonelik Sistemi</option>
                                <option value="digital" <?= $urun['type'] == 'digital' ? 'selected' : '' ?>>Dijital Ürün</option>
                                <option value="exam_package" <?= $urun['type'] == 'exam_package' ? 'selected' : '' ?>>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'] ?>" <?= $urun['category_id'] == $kat['id'] ? 'selected' : '' ?>><?= 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'] ?>" <?= in_array($kat['id'], $secili_kategoriler) ? 'selected' : '' ?>><?= 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'] ?>" <?= $urun['brand_id'] == $marka['id'] ? 'selected' : '' ?>><?= htmlspecialchars($marka['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Açıklama</label>
                        <textarea name="description" id="editor" class="form-control border-2 editor" rows="10"><?= htmlspecialchars($urun['description'] ?? '') ?></textarea>
                    </div>

                    <hr>
                    <label class="form-label fw-bold text-muted small text-uppercase mb-3">Görsel Yönetimi</label>
                    <div class="row g-3 mb-4">
                        <?php foreach($mevcut_gorseller as $gorsel): ?>
                            <div class="col-md-3 col-6 text-center">
                                <div class="card h-100 border shadow-none bg-light">
                                    <img src="/magaza/<?= htmlspecialchars($gorsel['image_path']) ?>" class="card-img-top" style="height: 120px; object-fit: cover;">
                                    <div class="card-body p-2">
                                        <?php if($gorsel['is_main'] == 1): ?>
                                            <span class="badge bg-primary w-100">Ana Görsel</span>
                                        <?php else: ?>
                                            <div class="btn-group w-100 shadow-sm">
                                                <a href="?id=<?= $urun_id ?>&ana_yap=<?= $gorsel['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-star"></i></a>
                                                <a href="?id=<?= $urun_id ?>&gorsel_sil=<?= $gorsel['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Silinsin mi?');"><i class="bi bi-trash"></i></a>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>

                    <div class="p-3 bg-light rounded border border-dashed">
                        <label class="form-label fw-bold text-muted small text-uppercase">Yeni Görseller Ekle</label>
                        <input type="file" name="images[]" class="form-control bg-white" accept="image/*" multiple>
                    </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..." value="<?= htmlspecialchars($urun['exam_type'] ?? '') ?>">
                        </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" value="<?= htmlspecialchars($urun['exam_publication_date'] ?? '') ?>">
                        </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" value="<?= htmlspecialchars($urun['exam_date'] ?? '') ?>">
                        </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" <?= $urun['package_delivery_type'] == 'single' ? 'selected' : '' ?>>Tek Seferde Gönderim</option>
                                <option value="weekly" <?= $urun['package_delivery_type'] == 'weekly' ? 'selected' : '' ?>>Haftalık Gönderim (Abonelik)</option>
                                <option value="monthly" <?= $urun['package_delivery_type'] == 'monthly' ? 'selected' : '' ?>>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 Sayısı *</label>
                            <div class="input-group">
                                <input type="number" name="package_delivery_count" id="packageDeliveryCount" class="form-control border-2 fw-bold" value="<?= $urun['package_delivery_count'] ?? 1 ?>" min="1" max="52">
                                <button type="button" class="btn btn-primary fw-bold" id="btnGenerateBoxes">Yeniden Oluştur <i class="bi bi-arrow-clockwise"></i></button>
                            </div>
                        </div>
                    </div>

                    <div class="bg-dark p-3 rounded mb-3 text-white" id="filterArea">
                        <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">
                                <select id="filterTur" class="form-select form-select-sm">
                                    <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">
                                <select id="filterMarka" class="form-select form-select-sm">
                                    <option value="">Tüm Yayınlar</option>
                                    <?php foreach($markalar as $m): ?>
                                        <option value="<?= $m['id'] ?>"><?= htmlspecialchars($m['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-3">
                                <input type="date" id="filterBaslangic" class="form-control form-control-sm">
                            </div>
                            <div class="col-md-3">
                                <input type="date" id="filterBitis" class="form-control form-control-sm">
                            </div>
                        </div>
                        <div class="input-group input-group-sm">
                            <input type="text" id="filterArama" class="form-control" placeholder="Deneme Adı veya SKU...">
                            <button class="btn btn-success fw-bold px-4" type="button" id="btnSearchExams">DENEMELERİ BUL</button>
                        </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">
                        <?php if(!empty($paket_icerigi)): ?>
                            <?php foreach($paket_icerigi as $seq => $data): ?>
                                <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><?= $seq ?>. 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[<?= $seq ?>]" class="form-control form-control-sm" style="width: 130px;" value="<?= $data['date'] ?>" required>
                                        </div>
                                    </div>
                                    <div class="card-body bg-white p-3">
                                        <div class="row" id="delivery_box_<?= $seq ?>">
                                            <?php foreach($data['exams'] as $exam): ?>
                                                <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><?= htmlspecialchars($exam['name']) ?></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[<?= $seq ?>][]" value="<?= $exam['id'] ?>">
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div id="digitalFields" class="card shadow-sm border-0 mb-4 bg-light border-start border-4 border-info">
                <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</h6>
                    <?php if($urun['file_path']): ?>
                        <div class="mb-3 p-2 bg-white border rounded d-flex justify-content-between align-items-center">
                            <span class="small text-muted fw-bold">Yüklü: <?= basename($urun['file_path']) ?></span>
                            <a href="/magaza/<?= $urun['file_path'] ?>" target="_blank" class="btn btn-sm btn-outline-info">İndir</a>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="digital_file" class="form-control border-2 bg-white" accept=".pdf,.zip,.rar,.mp4">
                </div>
            </div>

            <div id="subscriptionFields" class="card shadow-sm border-0 mb-4 bg-light border-start border-4 border-warning">
                <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 Ayarları</h6>
                    <div class="row">
                        <div class="col-md-6">
                            <label class="form-label fw-bold small">Teslimat Sayısı</label>
                            <input type="number" name="total_deliveries" class="form-control border-2 bg-white" value="<?= $urun['total_deliveries'] ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold small">Süre (Gün)</label>
                            <input type="number" name="duration_days" class="form-control border-2 bg-white" value="<?= $urun['duration_days'] ?>">
                        </div>
                    </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">
                            <label class="form-label fw-bold text-muted small text-uppercase">Kargo Planı</label>
                            <input type="text" name="shipping_info" class="form-control border-2" value="<?= htmlspecialchars($urun['shipping_info'] ?? '') ?>">
                        </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" <?= $urun['is_free_shipping'] == 1 ? 'checked' : '' ?>>
                                <label class="form-check-label ms-2 fw-bold text-success small text-uppercase" for="freeShipping">Ücretsiz Kargo</label>
                            </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="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"><?= htmlspecialchars($urun['custom_payment_text'] ?? '') ?></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"><?= htmlspecialchars($urun['custom_delivery_text'] ?? '') ?></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">Fiyat (₺) *</label>
                        <input type="number" step="0.01" name="price" class="form-control form-control-lg fw-bold text-primary border-2" required value="<?= $urun['price'] ?>">
                    </div>
                    <div class="mb-4">
                        <label class="form-label fw-bold text-danger small text-uppercase">İndirimli Fiyat (₺)</label>
                        <input type="number" step="0.01" name="discount_price" class="form-control fw-bold text-danger border-2" value="<?= $urun['discount_price'] ?>">
                    </div>
                    <div class="row mb-4">
                        <div class="col-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">KDV %</label>
                            <select name="vat_rate" class="form-select fw-bold border-2">
                                <?php foreach([0,1,10,20] as $v): ?>
                                    <option value="<?= $v ?>" <?= $urun['vat_rate'] == $v ? 'selected' : '' ?>><?= $v ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">KDV</label>
                            <select name="vat_included" class="form-select fw-bold border-2">
                                <option value="1" <?= $urun['vat_included'] == 1 ? 'selected' : '' ?>>Dahil</option>
                                <option value="0" <?= $urun['vat_included'] == 0 ? 'selected' : '' ?>>Hariç</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-bold text-muted small text-uppercase">Stok</label>
                        <input type="number" name="stock_quantity" class="form-control fw-bold border-2" value="<?= $urun['stock_quantity'] ?>">
                    </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="<?= $urun['publish_date'] ? date('Y-m-d\TH:i', strtotime($urun['publish_date'])) : '' ?>">
                    </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" value="<?= $urun['end_date'] ? date('Y-m-d\TH:i', strtotime($urun['end_date'])) : '' ?>">
                    </div>
                </div>
            </div>

            <button type="submit" name="urun_guncelle" class="btn btn-warning btn-lg w-100 fw-bold shadow-sm py-3 mb-2"><i class="bi bi-save-fill me-2"></i> DEĞİŞİKLİKLERİ KAYDET</button>
            <a href="index.php" class="btn btn-light border w-100 fw-bold text-muted">Vazgeç</a>
        </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: 350, 
        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 singleExamDiv = document.getElementById('singleExamFields'); // YENİ
        const stdCatDiv = document.getElementById('standardCategoryDiv');
        const multiCatDiv = document.getElementById('multipleCategoryDiv');

        function updateFields() {
            const type = typeSelect.value;
            
            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İ
            
            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();

        const btnGenerateBoxes = document.getElementById('btnGenerateBoxes');
        const deliveryBoxesArea = document.getElementById('deliveryBoxesArea');

        btnGenerateBoxes.addEventListener('click', function() {
            if(!confirm('Kutuları yeniden oluşturmak mevcut paket içeriğini temizleyecektir. Emin misiniz?')) return;
            const count = parseInt(document.getElementById('packageDeliveryCount').value) || 1;
            deliveryBoxesArea.innerHTML = ''; 
            
            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" style="width: 130px;" required>
                        </div>
                    </div>
                    <div class="card-body bg-white p-3">
                        <div class="row" id="delivery_box_${i}"></div>
                    </div>
                </div>`;
                deliveryBoxesArea.insertAdjacentHTML('beforeend', boxHTML);
            }
        });

        const btnSearchExams = document.getElementById('btnSearchExams');
        const examResultsArea = document.getElementById('examResultsArea');

        btnSearchExams.addEventListener('click', function() {
            const params = new URLSearchParams({
                'tur': document.getElementById('filterTur').value,
                'marka_id': document.getElementById('filterMarka').value,
                'arama': document.getElementById('filterArama').value,
                'baslangic_tarihi': document.getElementById('filterBaslangic').value,
                'bitis_tarihi': document.getElementById('filterBitis').value
            });
            
            examResultsArea.innerHTML = '<div class="col-12 text-center py-3"><div class="spinner-border text-primary"></div></div>';
            examResultsArea.style.display = 'flex';
            
            fetch('ajax_deneme_getir.php', { 
                method: 'POST', 
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, 
                body: params 
            })
            .then(res => res.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="">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 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="/magaza/${exam.main_image}" width="40" height="40" class="rounded object-fit-cover me-2">
                                <div class="flex-grow-1 overflow-hidden">
                                    <div class="fw-bold text-truncate" style="font-size:0.8rem;">${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: 85px; 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">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>';
            });
        });

        function attachAssignmentEvents() {
            document.querySelectorAll('.exam-assigner').forEach(select => {
                select.addEventListener('change', function() {
                    const seq = this.value; 
                    if(!seq) return;
                    
                    const id = this.dataset.examId; 
                    const name = this.dataset.examName;
                    const box = document.getElementById(`delivery_box_${seq}`);
                    
                    if(!box.querySelector(`input[value="${id}"]`)) {
                        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>${name}</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[${seq}][]" value="${id}">
                            </div>
                        </div>`;
                        box.insertAdjacentHTML('beforeend', addedHTML);
                    } else { 
                        alert('Zaten ekli!'); 
                    }
                    
                    this.value = '';
                });
            });
        }
    });
</script>

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