<?php
/**
 * Kullanıcı - Kendi Paketini Oluştur Sayfası
 * Konum: /magaza/deneme-paket-olustur.php
 */

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

// 1. Havuzdaki Aktif ve Stokta Olan Tekli Denemeleri Çek 
// GÜNCELLEME: Sayfa çökmesini engellemek için LIMIT 200 eklendi. En güncel ve uygun 200 ürünü getirir.
$stmt = $db->prepare("
    SELECT 
        p.id, p.name, p.price, p.exam_type, p.sku, p.exam_publication_date, p.allow_custom_package,
        b.name as brand_name, b.id as brand_id,
        COALESCE(
            (SELECT image_path FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1),
            b.default_cover,
            'assets/img/no-image.jpg'
        ) as main_image
    FROM products p
    LEFT JOIN brands b ON p.brand_id = b.id
    WHERE p.type = 'single_exam' 
      AND p.status = 1 
      AND p.stock_quantity > 0
    ORDER BY 
      CASE 
        WHEN STR_TO_DATE(p.exam_publication_date, '%d.%m.%Y') >= CURDATE() OR p.exam_publication_date IS NULL OR p.exam_publication_date = '' THEN 0 
        ELSE 1 
      END ASC,
      STR_TO_DATE(p.exam_publication_date, '%d.%m.%Y') ASC, 
      p.id DESC
    LIMIT 200
");
$stmt->execute();
$denemeler = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 2. Filtreler İçin Benzersiz Türleri ve Markaları Çıkar
$turler = [];
$markalar = [];

foreach ($denemeler as $d) {
    if (!empty($d['exam_type']) && !in_array($d['exam_type'], $turler)) {
        $turler[] = $d['exam_type'];
    }
    if (!empty($d['brand_name']) && !isset($markalar[$d['brand_id']])) {
        $markalar[$d['brand_id']] = $d['brand_name'];
    }
}
sort($turler);

// 3. Tarih Filtreleri İçin Dinamik Yıl ve Ay Dizileri
$current_year = date('Y');
$yillar = [];
for ($y = $current_year + 1; $y >= $current_year - 2; $y--) {
    $yillar[] = $y;
}

$aylar_tr = [
    '01' => 'Ocak', '02' => 'Şubat', '03' => 'Mart', '04' => 'Nisan',
    '05' => 'Mayıs', '06' => 'Haziran', '07' => 'Temmuz', '08' => 'Ağustos',
    '09' => 'Eylül', '10' => 'Ekim', '11' => 'Kasım', '12' => 'Aralık'
];

// 4. Kargo Ayarlarını Çek
$kargo_ayarlari = $db->query("SELECT * FROM shipping_settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);

$bugun = new DateTime('midnight');
$page_title = "Kendi Deneme Paketini Oluştur | SINAVKOCU Mağaza";
require_once 'header.php';
?>

<style>
    .exam-card { transition: all 0.2s ease-in-out; border: 2px solid transparent; }
    .exam-card:hover { transform: translateY(-3px); box-shadow: 0 10px 20px rgba(0,0,0,0.1); border-color: var(--bs-primary); }
    .sticky-package { position: sticky; top: 120px; z-index: 100; } 
    .package-item { animation: fadeIn 0.3s ease; }
    @keyframes fadeIn { from { opacity: 0; transform: translateX(10px); } to { opacity: 1; transform: translateX(0); } }
    .custom-scrollbar::-webkit-scrollbar { width: 6px; }
    .custom-scrollbar::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 10px; }
    .custom-scrollbar::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 10px; }
    .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #a8a8a8; }
</style>

<main class="container py-5 text-dark">
    
    <div class="text-center mb-5">
        <span class="badge bg-primary px-3 py-2 rounded-pill mb-3 fs-6 shadow-sm"><i class="bi bi-stars text-warning me-1"></i> Sana Özel, Senin Seçimin</span>
        <h1 class="display-5 fw-bold text-dark mb-3">Kendi Deneme Paketini Oluştur</h1>
        <p class="text-muted lead mx-auto" style="max-width: 700px;">
            Aşağıdaki havuzdan dilediğin denemeleri seç, kendi özel paketini oluştur. Sepetindeki adet arttıkça kargo avantajlarından faydalan!
        </p>
    </div>

    <div class="row g-4">
        
        <div class="col-lg-3">
            <div class="card shadow-sm border-0 rounded-4 sticky-package">
                <div class="card-header bg-dark text-white rounded-top-4 py-3">
                    <h5 class="card-title mb-0 fw-bold fs-6 text-uppercase"><i class="bi bi-funnel-fill me-2 text-warning"></i>Hızlı Filtrele</h5>
                </div>
                <div class="card-body p-4">
                    <div class="mb-4">
                        <label class="form-label fw-bold small text-muted text-uppercase">Deneme Adı Ara</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light border-end-0"><i class="bi bi-search text-muted"></i></span>
                            <input type="text" id="searchFilter" class="form-control border-start-0 bg-light" placeholder="Örn: TYT Limit...">
                        </div>
                    </div>
                    
                    <div class="mb-4">
                        <div class="row g-2">
                            <div class="col-6">
                                <label class="form-label fw-bold small text-muted text-uppercase">Yayın Yılı</label>
                                <select id="yearFilter" class="form-select border-2">
                                    <option value="all">Tüm Yıllar</option>
                                    <?php foreach($yillar as $y): ?>
                                        <option value="<?= $y ?>"><?= $y ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-6">
                                <label class="form-label fw-bold small text-muted text-uppercase">Yayın Ayı</label>
                                <select id="monthFilter" class="form-select border-2">
                                    <option value="all">Tüm Aylar</option>
                                    <?php foreach($aylar_tr as $num => $name): ?>
                                        <option value="<?= $num ?>"><?= $name ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold small text-muted text-uppercase">Sınav Türü</label>
                        <div class="d-flex flex-column gap-2" id="typeFilters">
                            <div class="form-check">
                                <input class="form-check-input type-filter" type="radio" name="typeFilter" value="all" id="typeAll" checked>
                                <label class="form-check-label fw-bold" for="typeAll">Tüm Türler</label>
                            </div>
                            <?php foreach($turler as $t): ?>
                            <div class="form-check">
                                <input class="form-check-input type-filter" type="radio" name="typeFilter" value="<?= htmlspecialchars($t) ?>" id="type_<?= htmlspecialchars($t) ?>">
                                <label class="form-check-label" for="type_<?= htmlspecialchars($t) ?>"><?= htmlspecialchars($t) ?></label>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div>
                        <label class="form-label fw-bold small text-muted text-uppercase">Yayın Evi</label>
                        <select id="brandFilter" class="form-select border-2">
                            <option value="all">Tüm Yayınlar</option>
                            <?php foreach($markalar as $id => $name): ?>
                                <option value="<?= $id ?>"><?= htmlspecialchars($name) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-6">
            <div class="d-flex justify-content-between align-items-center mb-3 px-2">
                <h5 class="fw-bold text-dark mb-0">Deneme Havuzu</h5>
                <span class="badge bg-secondary" id="visibleCount"><?= count($denemeler) ?> Ürün</span>
            </div>

            <div class="alert alert-info border-0 shadow-sm rounded-4 mb-4 d-flex align-items-start">
                <i class="bi bi-info-circle-fill text-info fs-4 me-3 mt-1"></i>
                <div>
                    <strong class="d-block mb-1 text-dark">Kargo Süreciniz Nasıl İşliyor?</strong>
                    <span class="small text-muted">
                        Eklediğiniz denemelerin yayın tarihi geçmişse <b>hemen</b> kargolanır. Yayın tarihi gelecekte olan denemeler ise, yayın tarihini takip eden <b>ilk Salı günü</b> adresinize kargolanmak üzere yola çıkar. Kargo tarihlerinizi sağ taraftaki paketinizden takip edebilirsiniz.
                    </span>
                </div>
            </div>

            <div class="row g-3 custom-scrollbar" id="examPool" style="max-height: 800px; overflow-y: auto; overflow-x: hidden; padding-bottom: 20px;">
                <?php if(count($denemeler) > 0): ?>
                    <?php foreach($denemeler as $d): 
                        
                        $item_month = 'all';
                        $item_year = 'all';
                        $gecmis_mi = false;
                        $satisa_acik_mi = true; // Ön tanımlı olarak her şey satılabilir
                        $raw_date_js = '';
                        
                        $baski_metni = ''; // Geçmiş yayınlar için kullanılacak (Örn: Mart 2026 Baskısı)

                        if (!empty($d['exam_publication_date'])) {
                            $p = explode('.', $d['exam_publication_date']);
                            if(count($p) == 3) {
                                $item_month = str_pad($p[1], 2, '0', STR_PAD_LEFT);
                                $item_year = $p[2];
                                
                                $ay_ismi = $aylar_tr[$item_month] ?? '';
                                $baski_metni = "{$ay_ismi} {$item_year} Baskısı (Hemen Kargo)";
                                
                                $tarihObj = DateTime::createFromFormat('d.m.Y', $d['exam_publication_date']);
                                if ($tarihObj) {
                                    $raw_date_js = $tarihObj->format('Y-m-d');
                                    // Eğer sınav tarihi geçmişse...
                                    if ($tarihObj < $bugun) {
                                        $gecmis_mi = true;
                                        // Ve admin pakette satışa izin vermemişse...
                                        if ($d['allow_custom_package'] == 0) {
                                            $satisa_acik_mi = false;
                                        }
                                    }
                                }
                            }
                        }
                        
                        // Sadece satışa kapalıysa silik görünsün
                        $card_opacity = (!$satisa_acik_mi) ? 'opacity-75 bg-light' : '';
                        $img_grayscale = (!$satisa_acik_mi) ? 'grayscale(100%)' : 'none';
                    ?>
                        <div class="col-md-6 exam-item" 
                             data-name="<?= mb_strtolower($d['name']) ?>" 
                             data-type="<?= htmlspecialchars($d['exam_type']) ?>" 
                             data-brand="<?= $d['brand_id'] ?>"
                             data-month="<?= $item_month ?>"
                             data-year="<?= $item_year ?>">
                             
                            <div class="card h-100 shadow-sm rounded-4 exam-card <?= $card_opacity ?>">
                                <div class="row g-0 h-100">
                                    <div class="col-4 p-2 d-flex align-items-center justify-content-center bg-white rounded-start-4">
                                        <img src="<?= htmlspecialchars($d['main_image']) ?>" class="img-fluid rounded shadow-sm" style="max-height: 100px; object-fit: contain; filter: <?= $img_grayscale ?>;">
                                    </div>
                                    <div class="col-8">
                                        <div class="card-body p-3 d-flex flex-column h-100 justify-content-between">
                                            <div>
                                                <div class="mb-1 d-flex justify-content-between align-items-start">
                                                    <span class="badge bg-info text-dark" style="font-size:0.65rem;"><?= htmlspecialchars($d['exam_type'] ?? 'Genel') ?></span>
                                                    <?php if(!empty($d['exam_publication_date'])): ?>
                                                        <span class="<?= $gecmis_mi ? 'text-danger' : 'text-primary' ?> fw-bold" style="font-size:0.65rem;" title="Yayın Tarihi">
                                                            <i class="bi bi-calendar-event"></i> Yayın: <?= date('d.m.Y', strtotime($d['exam_publication_date'])) ?>
                                                        </span>
                                                    <?php endif; ?>
                                                </div>
                                                <h6 class="card-title fw-bold text-dark mb-1 lh-sm <?= (!$satisa_acik_mi) ? 'text-decoration-line-through' : '' ?>" style="font-size: 0.9rem;"><?= htmlspecialchars($d['name']) ?></h6>
                                                <div class="text-muted fw-bold" style="font-size:0.7rem;"><?= htmlspecialchars($d['brand_name'] ?? '') ?></div>
                                                
                                                <?php if($gecmis_mi && $satisa_acik_mi): ?>
                                                    <div class="mt-1" style="font-size:0.65rem;">
                                                        <span class="text-success fw-bold"><i class="bi bi-box-seam me-1"></i><?= $baski_metni ?></span>
                                                    </div>
                                                <?php elseif($gecmis_mi && !$satisa_acik_mi): ?>
                                                    <div class="mt-1" style="font-size:0.65rem;">
                                                        <span class="text-danger"><i class="bi bi-exclamation-circle me-1"></i>Sınav tarihi geçmiştir.</span>
                                                    </div>
                                                <?php endif; ?>
                                                
                                            </div>
                                            <div class="d-flex justify-content-between align-items-end mt-2">
                                                <span class="text-primary fw-bold fs-6 <?= (!$satisa_acik_mi) ? 'text-muted' : '' ?>"><?= number_format($d['price'], 2, ',', '.') ?> ₺</span>
                                                
                                                <?php if(!$satisa_acik_mi): ?>
                                                    <button type="button" class="btn btn-sm btn-secondary fw-bold rounded-pill shadow-sm px-3" disabled>
                                                        <i class="bi bi-dash-circle"></i> Süresi Geçti
                                                    </button>
                                                <?php else: ?>
                                                    <button type="button" class="btn btn-sm btn-success fw-bold rounded-pill shadow-sm px-3 btn-add-package" 
                                                            data-id="<?= $d['id'] ?>" 
                                                            data-name="<?= htmlspecialchars($d['name']) ?>" 
                                                            data-price="<?= $d['price'] ?>"
                                                            data-date="<?= $gecmis_mi ? '' : $raw_date_js ?>">
                                                        <i class="bi bi-plus-lg"></i> Ekle
                                                    </button>
                                                <?php endif; ?>
                                                
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="col-12">
                        <div class="alert alert-warning text-center border-0 shadow-sm rounded-4 py-4">
                            <i class="bi bi-calendar-x fs-1 d-block mb-2 text-warning opacity-75"></i>
                            <span class="fw-bold d-block">Deneme Bulunamadı</span>
                            <small class="text-muted">Şu an havuzda seçilebilir deneme bulunmuyor.</small>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="col-lg-3">
            <div class="card shadow border-primary border-2 rounded-4 sticky-package overflow-hidden">
                <div class="card-header bg-primary text-white py-3 d-flex justify-content-between align-items-center border-0">
                    <h5 class="card-title mb-0 fw-bold fs-6 text-uppercase"><i class="bi bi-box2-heart-fill me-2"></i>Benim Paketim</h5>
                    <span class="badge bg-light text-primary rounded-pill" id="packageItemCount">0</span>
                </div>
                
                <div id="dynamicMotivationBanner" class="bg-primary bg-opacity-10 border-bottom border-primary border-opacity-25 p-2 text-center" style="display:none;">
                </div>
                
                <div class="card-body p-0">
                    <div id="packageList" class="list-group list-group-flush custom-scrollbar" style="max-height: 350px; overflow-y: auto;">
                        <div class="p-4 text-center text-muted" id="emptyPackageMsg">
                            <i class="bi bi-bag-plus fs-1 opacity-50 mb-2 d-block"></i>
                            <small>Paketiniz şu an boş. Sol taraftaki listeden denemeleri eklemeye başlayın.</small>
                        </div>
                    </div>
                </div>
                
                <div class="card-footer bg-light border-top p-3">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="text-muted small fw-bold">Ara Toplam:</span>
                        <span class="fw-bold text-dark" id="packageSubTotal">0,00 ₺</span>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-3 pb-2 border-bottom">
                        <span class="text-muted small fw-bold">Kargo:</span>
                        <span class="fw-bold" id="packageShipping">0,00 ₺</span>
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span class="fw-bold text-dark fs-6">Genel Toplam:</span>
                        <span class="fs-4 fw-bold text-danger" id="packageTotal">0,00 ₺</span>
                    </div>
                    <button type="button" id="btnBuyPackage" class="btn btn-warning btn-lg w-100 fw-bold shadow rounded-pill" disabled>
                        <i class="bi bi-cart-check-fill me-2"></i>SEPETE EKLE
                    </button>
                </div>
            </div>
        </div>

    </div>
</main>

<script>
const kargoSabit = <?= (float)$kargo_ayarlari['fixed_fee'] ?>;
const kargoAdetBaraji = <?= (int)$kargo_ayarlari['free_quantity_limit'] ?>;
const kargoAdetAktif = <?= $kargo_ayarlari['free_quantity_status'] == 1 ? 'true' : 'false' ?>;

function getNextTuesday(dateString) {
    if (!dateString) return null;
    let d = new Date(dateString);
    if (isNaN(d.getTime())) return null;
    
    let day = d.getDay(); 
    let addDays = (2 - day + 7) % 7;
    if (addDays === 0) addDays = 7; 
    
    d.setDate(d.getDate() + addDays);
    
    let dayStr = ("0" + d.getDate()).slice(-2);
    let monthStr = ("0" + (d.getMonth() + 1)).slice(-2);
    let yearStr = d.getFullYear();
    
    return `${dayStr}.${monthStr}.${yearStr}`;
}

document.addEventListener("DOMContentLoaded", function() {
    
    // --- 1. ARAMA VE FİLTRELEME MOTORU ---
    const searchInput = document.getElementById('searchFilter');
    const brandSelect = document.getElementById('brandFilter');
    const yearSelect = document.getElementById('yearFilter');
    const monthSelect = document.getElementById('monthFilter');
    const typeRadios = document.querySelectorAll('.type-filter');
    const examItems = document.querySelectorAll('.exam-item');
    const visibleCount = document.getElementById('visibleCount');

    function applyFilters() {
        const searchTerm = searchInput.value.toLowerCase().trim();
        const selectedBrand = brandSelect.value;
        const selectedYear = yearSelect.value;
        const selectedMonth = monthSelect.value;
        const selectedType = document.querySelector('.type-filter:checked').value;
        
        let count = 0;
        
        examItems.forEach(item => {
            const name = item.getAttribute('data-name');
            const type = item.getAttribute('data-type');
            const brand = item.getAttribute('data-brand');
            const itemYear = item.getAttribute('data-year');
            const itemMonth = item.getAttribute('data-month');
            
            const matchSearch = name.includes(searchTerm);
            const matchBrand = (selectedBrand === 'all') || (brand === selectedBrand);
            const matchType = (selectedType === 'all') || (type === selectedType);
            const matchYear = (selectedYear === 'all') || (itemYear === selectedYear);
            const matchMonth = (selectedMonth === 'all') || (itemMonth === selectedMonth);
            
            if (matchSearch && matchBrand && matchType && matchYear && matchMonth) {
                item.style.display = 'block'; 
                count++;
            } else {
                item.style.display = 'none';
            }
        });
        
        visibleCount.innerText = count + ' Ürün';
    }

    searchInput.addEventListener('input', applyFilters);
    brandSelect.addEventListener('change', applyFilters);
    yearSelect.addEventListener('change', applyFilters);
    monthSelect.addEventListener('change', applyFilters);
    typeRadios.forEach(radio => radio.addEventListener('change', applyFilters));

    // --- 2. PAKETE EKLEME / ÇIKARMA VE KARGO HESAPLAMA MOTORU ---
    let myPackage = []; 
    
    const packageList = document.getElementById('packageList');
    const emptyPackageMsg = document.getElementById('emptyPackageMsg');
    
    const packageSubTotalEl = document.getElementById('packageSubTotal');
    const packageShippingEl = document.getElementById('packageShipping');
    const packageTotalEl = document.getElementById('packageTotal');
    
    const packageItemCountEl = document.getElementById('packageItemCount');
    const btnBuyPackage = document.getElementById('btnBuyPackage');
    const dynamicBanner = document.getElementById('dynamicMotivationBanner');

    // Ekle Butonları
    document.querySelectorAll('.btn-add-package').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            const name = this.getAttribute('data-name');
            const price = parseFloat(this.getAttribute('data-price'));
            const date = this.getAttribute('data-date');
            
            const existing = myPackage.find(item => item.id === id);
            if (existing) { existing.qty += 1; } 
            else { myPackage.push({ id: id, name: name, price: price, qty: 1, date: date }); }
            
            renderPackage();
        });
    });

    // Paketi Ekrana Çizme ve Kargo Hesaplama
    function renderPackage() {
        packageList.innerHTML = '';
        let araToplam = 0;
        let totalItems = 0;

        if (myPackage.length === 0) {
            packageList.appendChild(emptyPackageMsg);
            emptyPackageMsg.style.display = 'block';
            btnBuyPackage.disabled = true;
            dynamicBanner.style.display = 'none';
            
            packageSubTotalEl.innerText = "0,00 ₺";
            packageShippingEl.innerText = "0,00 ₺";
            packageTotalEl.innerText = "0,00 ₺";
            packageItemCountEl.innerText = "0";
        } else {
            emptyPackageMsg.style.display = 'none';
            btnBuyPackage.disabled = false;

            myPackage.forEach((item, index) => {
                araToplam += (item.price * item.qty);
                totalItems += item.qty;
                
                let kargoBadge = '';
                if (item.date && item.date !== '') {
                    let nxtTue = getNextTuesday(item.date);
                    kargoBadge = `<div class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-25 mt-1 d-inline-block text-start" style="font-size:0.65rem; white-space:normal;"><i class="bi bi-truck me-1"></i>Kargo: ${nxtTue} (Salı)</div>`;
                } else {
                    kargoBadge = `<div class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 mt-1 d-inline-block text-start" style="font-size:0.65rem;"><i class="bi bi-box-seam me-1"></i>Hemen Kargoya Hazır</div>`;
                }

                const itemHTML = `
                <div class="list-group-item package-item py-3 border-bottom">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div>
                            <div class="fw-bold text-dark" style="font-size:0.85rem; line-height:1.2;">${item.name}</div>
                            ${kargoBadge}
                        </div>
                        <button class="btn btn-link text-danger p-0 ms-2 btn-remove flex-shrink-0" data-index="${index}"><i class="bi bi-x-circle-fill fs-5"></i></button>
                    </div>
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="input-group input-group-sm" style="width: 80px;">
                            <button class="btn btn-outline-secondary btn-decrease" data-index="${index}">-</button>
                            <input type="text" class="form-control text-center px-0 bg-white" value="${item.qty}" readonly>
                            <button class="btn btn-outline-secondary btn-increase" data-index="${index}">+</button>
                        </div>
                        <div class="fw-bold text-primary">${(item.price * item.qty).toLocaleString('tr-TR', {minimumFractionDigits: 2})} ₺</div>
                    </div>
                </div>`;
                packageList.insertAdjacentHTML('beforeend', itemHTML);
            });
            
            let anlikKargo = kargoSabit;
            dynamicBanner.style.display = 'block';

            if (kargoAdetAktif && totalItems >= kargoAdetBaraji) {
                anlikKargo = 0;
                packageShippingEl.innerHTML = `<span class="text-success fw-bold">Bedava</span>`;
                dynamicBanner.innerHTML = `<div class="text-success fw-bold py-1"><i class="bi bi-balloon-fill me-1"></i> Tebrikler! Kargo Bedava.</div>`;
                dynamicBanner.className = "bg-success bg-opacity-10 border-bottom border-success border-opacity-25 p-2 text-center";
            } else {
                packageShippingEl.innerHTML = `<span class="text-dark">${anlikKargo.toLocaleString('tr-TR', {minimumFractionDigits: 2})} ₺</span>`;
                
                if (kargoAdetAktif) {
                    let kalan = kargoAdetBaraji - totalItems;
                    dynamicBanner.innerHTML = `
                        <div style="font-size: 0.75rem;" class="text-dark fw-bold">
                            <i class="bi bi-truck text-primary me-1"></i> Ücretsiz Kargo Fırsatı
                        </div>
                        <div style="font-size: 0.75rem;" class="text-danger mt-1">
                            Sadece <b>${kalan} adet</b> daha deneme ekle, kargo bedava olsun!
                        </div>`;
                    dynamicBanner.className = "bg-primary bg-opacity-10 border-bottom border-primary border-opacity-25 p-2 text-center";
                } else {
                    dynamicBanner.style.display = 'none';
                }
            }

            let genelToplam = araToplam + anlikKargo;

            packageSubTotalEl.innerText = araToplam.toLocaleString('tr-TR', {minimumFractionDigits: 2}) + ' ₺';
            packageTotalEl.innerText = genelToplam.toLocaleString('tr-TR', {minimumFractionDigits: 2}) + ' ₺';
            packageItemCountEl.innerText = totalItems;
        }

        updatePoolButtons();
        attachPackageEvents();
    }

    function updatePoolButtons() {
        document.querySelectorAll('.btn-add-package').forEach(btn => {
            const id = btn.getAttribute('data-id');
            const itemInPackage = myPackage.find(item => item.id === id);

            if (itemInPackage) {
                btn.innerHTML = `<i class="bi bi-check2-all"></i> Ekli <span class="badge bg-white text-primary ms-1">${itemInPackage.qty}</span>`;
                btn.classList.remove('btn-success');
                btn.classList.add('btn-primary');
            } else {
                btn.innerHTML = `<i class="bi bi-plus-lg"></i> Ekle`;
                btn.classList.remove('btn-primary');
                btn.classList.add('btn-success');
            }
        });
    }

    function attachPackageEvents() {
        document.querySelectorAll('.btn-remove').forEach(btn => {
            btn.addEventListener('click', function() {
                myPackage.splice(this.getAttribute('data-index'), 1);
                renderPackage();
            });
        });
        document.querySelectorAll('.btn-increase').forEach(btn => {
            btn.addEventListener('click', function() {
                myPackage[this.getAttribute('data-index')].qty += 1;
                renderPackage();
            });
        });
        document.querySelectorAll('.btn-decrease').forEach(btn => {
            btn.addEventListener('click', function() {
                let idx = this.getAttribute('data-index');
                if (myPackage[idx].qty > 1) { myPackage[idx].qty -= 1; } 
                else { myPackage.splice(idx, 1); }
                renderPackage();
            });
        });
    }

    btnBuyPackage.addEventListener('click', async function() {
        if(myPackage.length === 0) return;
        
        const originalHTML = this.innerHTML;
        this.disabled = true;
        this.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sepete Atılıyor...';

        let successCount = 0;
        for (const item of myPackage) {
            let formData = new FormData();
            formData.append('action', 'add');
            formData.append('product_id', item.id);
            formData.append('quantity', item.qty);

            try {
                let response = await fetch('sepet-islem.php', { method: 'POST', body: formData });
                let result = await response.json();
                if (result.status === 'success') { successCount++; }
            } catch (error) { console.error('Ekleme hatası:', item.id); }
        }

        this.innerHTML = originalHTML;
        this.disabled = false;

        if (successCount > 0) {
            if(typeof Swal !== 'undefined') {
                Swal.fire({
                    title: 'Paketiniz Hazır!',
                    text: 'Seçtiğiniz tüm denemeler başarıyla sepetinize eklendi.',
                    icon: 'success',
                    showCancelButton: true,
                    confirmButtonText: '<i class="bi bi-cart-check me-1"></i> Sepete Git',
                    cancelButtonText: 'Alışverişe Devam Et',
                    customClass: {
                        confirmButton: 'btn btn-success px-4 py-2 fw-bold rounded-pill mx-2 shadow-sm',
                        cancelButton: 'btn btn-secondary px-4 py-2 fw-bold rounded-pill mx-2 shadow-sm'
                    },
                    buttonsStyling: false
                }).then((result) => {
                    if (result.isConfirmed) { window.location.href = "sepet.php"; } 
                    else { myPackage = []; renderPackage(); }
                });
            } else {
                alert('Paketiniz başarıyla sepetinize eklendi!');
                window.location.href = "sepet.php";
            }
        } else {
            alert('Ürünler sepete eklenirken bir hata oluştu. Lütfen tekrar deneyin.');
        }
    });

});
</script>

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