<?php
session_start(); // Kupon kontrolü için session başlattık
require_once 'includes/db.php';
require_once 'includes/functions.php';

// Proje ana dizinini belirle
$kok_dizin = "/magaza/";

$cart_token = isset($_COOKIE['cart_token']) ? $_COOKIE['cart_token'] : '';

$sepet_urunleri = [];
$ara_toplam = 0; // KDV DAHİL İndirimli (Geçerli) Ara Toplam
$toplam_indirimsiz_tutar = 0; // Müşteriye kazancını göstermek için liste fiyatları toplamı
$toplam_kdv = 0; // İçindeki Toplam KDV Miktarı
$kdv_haric_toplam = 0; // KDV Hariç Ara Toplam
$kargo_ucreti = 0;
$kargo_sebebi = ""; // Ücretsiz veya ücretli kargonun nedenini tutar

$fiziksel_urun_var_mi = false;
$vip_kargo_var_mi = false; // Sepette is_free_shipping=1 olan ürün var mı?
$adet_kampanyasina_dahil_urun_sayisi = 0; // Adet kargo kampanyası için
$indirim_tutari = 0;
$uygulanan_kupon = null;

// Sepette kullanılan KDV oranlarını tutmak için dizi
$kullanilan_kdv_oranlari = [];

// YENİ: Kargo Ayarlarını Veritabanından Çek
$kargo_ayarlari = $db->query("SELECT * FROM shipping_settings WHERE id = 1")->fetch(PDO::FETCH_ASSOC);
$kargo_sabit_ucret = (float)$kargo_ayarlari['fixed_fee'];
$kargo_tutar_baraji = (float)$kargo_ayarlari['free_amount_limit'];
$kargo_tutar_aktif = (bool)$kargo_ayarlari['free_amount_status'];
$kargo_adet_baraji = (int)$kargo_ayarlari['free_quantity_limit'];
$kargo_adet_aktif = (bool)$kargo_ayarlari['free_quantity_status'];
$kargo_hedef_kategoriler = $kargo_ayarlari['target_categories'] ? explode(',', $kargo_ayarlari['target_categories']) : [];

if ($cart_token) {
    // 1. Sepetteki Ürünleri Çek (YENİ: exam_publication_date eklendi)
    $stmt = $db->prepare("
        SELECT ci.id as cart_item_id, ci.quantity, 
               p.id as product_id, p.name, p.slug, p.price, p.discount_price, p.type, p.stock_quantity, p.is_free_shipping, p.vat_rate, p.vat_included, p.category_id, p.shipping_info, p.exam_publication_date,
               b.name as brand_name, b.logo as brand_logo,
               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,
               c.coupon_code
        FROM cart_items ci
        JOIN carts c ON ci.cart_id = c.id
        JOIN products p ON ci.product_id = p.id
        LEFT JOIN brands b ON p.brand_id = b.id
        WHERE c.session_token = ?
        ORDER BY ci.id DESC
    ");
    $stmt->execute([$cart_token]);
    $sepet_urunleri = $stmt->fetchAll();

    foreach ($sepet_urunleri as $urun) {
        $gecerli_fiyat = $urun['discount_price'] > 0 ? $urun['discount_price'] : $urun['price'];
        
        // KDV Hesaplama Motoru
        if ($urun['vat_included'] == 1) {
            $kdvli_fiyat = $gecerli_fiyat;
            $indirimsiz_kdvli_fiyat = $urun['price'];
        } else {
            $kdvli_fiyat = $gecerli_fiyat * (1 + ($urun['vat_rate'] / 100));
            $indirimsiz_kdvli_fiyat = $urun['price'] * (1 + ($urun['vat_rate'] / 100));
        }
        
        $kdvsiz_fiyat = $kdvli_fiyat / (1 + ($urun['vat_rate'] / 100));
        $kdv_tutari = ($kdvli_fiyat - $kdvsiz_fiyat) * $urun['quantity'];
        
        $ara_toplam += ($kdvli_fiyat * $urun['quantity']);
        $toplam_indirimsiz_tutar += ($indirimsiz_kdvli_fiyat * $urun['quantity']); // Toplam liste fiyatı
        $kdv_haric_toplam += ($kdvsiz_fiyat * $urun['quantity']);
        $toplam_kdv += $kdv_tutari;

        if (!in_array($urun['vat_rate'], $kullanilan_kdv_oranlari)) {
            $kullanilan_kdv_oranlari[] = $urun['vat_rate'];
        }

        // Lojistik Kontrolleri
        if (in_array($urun['type'], ['physical', 'subscription', 'exam_package', 'single_exam'])) { 
            $fiziksel_urun_var_mi = true; 
        }

        if ($urun['is_free_shipping'] == 1) {
            $vip_kargo_var_mi = true;
        }

        // Adet kampanyasına dahil olan ürünleri say (Tekli denemeleri de sayar)
        if (in_array($urun['category_id'], $kargo_hedef_kategoriler) || $urun['type'] === 'single_exam') {
            $adet_kampanyasina_dahil_urun_sayisi += $urun['quantity'];
        }
    }

    // 2. Kupon Kontrolü ve İndirim Hesaplaması
    if (count($sepet_urunleri) > 0 && !empty($sepet_urunleri[0]['coupon_code'])) {
        $uygulanan_kupon = $sepet_urunleri[0]['coupon_code'];
        
        $cpn_stmt = $db->prepare("SELECT * FROM coupons WHERE code = ? AND status = 1");
        $cpn_stmt->execute([$uygulanan_kupon]);
        $kupon_detay = $cpn_stmt->fetch();

        if ($kupon_detay) {
            if ($kupon_detay['min_cart_amount'] > 0 && $ara_toplam < $kupon_detay['min_cart_amount']) {
                $db->prepare("UPDATE carts SET coupon_code = NULL WHERE session_token = ?")->execute([$cart_token]);
                $uygulanan_kupon = null; 
            } else {
                if ($kupon_detay['discount_type'] == 'percentage') {
                    $indirim_tutari = ($ara_toplam * $kupon_detay['discount_value']) / 100;
                } else {
                    $indirim_tutari = $kupon_detay['discount_value']; 
                }
                if ($indirim_tutari > $ara_toplam) { $indirim_tutari = $ara_toplam; }
            }
        } else {
            $db->prepare("UPDATE carts SET coupon_code = NULL WHERE session_token = ?")->execute([$cart_token]);
            $uygulanan_kupon = null;
        }
    }

    // 3. KARGO ZEKASI (ALGORİTMA) VE GÖRSEL GÜZELLEŞTİRMELERİ
    $odenecek_ara_toplam = $ara_toplam - $indirim_tutari;
    
    if (!$fiziksel_urun_var_mi) {
        $kargo_ucreti = 0;
        $kargo_sebebi = '<div class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-50 mt-1"><i class="bi bi-cloud-arrow-down-fill me-1"></i>Dijital Teslimat</div>';
    } elseif ($vip_kargo_var_mi) {
        $kargo_ucreti = 0;
        $kargo_sebebi = '<div class="badge bg-primary bg-opacity-10 text-primary border border-primary border-opacity-50 mt-1"><i class="bi bi-award-fill me-1"></i>Ücretsiz Kargo Etiketli Ürün</div>';
    } elseif ($kargo_tutar_aktif && $odenecek_ara_toplam >= $kargo_tutar_baraji) {
        $kargo_ucreti = 0;
        $kargo_sebebi = '<div class="badge bg-warning bg-opacity-25 text-dark border border-warning mt-1"><i class="bi bi-wallet2 me-1"></i>Sepet Tutarı Kampanyası</div>';
    } elseif ($kargo_adet_aktif && $adet_kampanyasina_dahil_urun_sayisi >= $kargo_adet_baraji) {
        $kargo_ucreti = 0;
        $kargo_sebebi = '<div class="badge bg-info bg-opacity-10 text-dark border border-info mt-1"><i class="bi bi-boxes me-1"></i>' . $kargo_adet_baraji . '+ Adet Alım Kampanyası</div>';
    } else {
        $kargo_ucreti = $kargo_sabit_ucret;
    }
}

$genel_toplam = ($ara_toplam - $indirim_tutari) + $kargo_ucreti;
if ($genel_toplam < 0) $genel_toplam = 0;

// --- KAZANÇ (KÂR) HESAPLAMA MOTORU ---
$urun_indirimi_kazanci = $toplam_indirimsiz_tutar - $ara_toplam; 
$kargo_kazanci = ($fiziksel_urun_var_mi && $kargo_ucreti == 0) ? $kargo_sabit_ucret : 0; 
$toplam_kazanc = $urun_indirimi_kazanci + $indirim_tutari + $kargo_kazanci; 

$kullanilabilir_kuponlar = [];
if (isset($_SESSION['user_id'])) {
    $uid = (int)$_SESSION['user_id'];
    $k_stmt = $db->prepare("SELECT * FROM coupons WHERE status = 1 AND (valid_until IS NULL OR valid_until > NOW()) AND (user_id = ? OR user_id IS NULL) ORDER BY id DESC");
    $k_stmt->execute([$uid]);
    $kullanilabilir_kuponlar = $k_stmt->fetchAll();
}

$kdv_oran_metni = "";
if (count($kullanilan_kdv_oranlari) > 0) {
    sort($kullanilan_kdv_oranlari); 
    $formatli_oranlar = array_map(function($oran) { return "%" . $oran; }, $kullanilan_kdv_oranlari);
    $kdv_oran_metni = " (" . implode(', ', $formatli_oranlar) . ")";
}

$page_title = "Sepetim | SINAVKOCU Mağaza";
require_once 'header.php';
?>

<main class="container py-5">
    <h1 class="h3 fw-bold mb-4">Alışveriş Sepetim</h1>

    <?php if (count($sepet_urunleri) > 0): ?>
        
        <?php if ($kargo_ucreti > 0 && $kargo_tutar_aktif): ?>
            <?php 
                $kalan_tutar = $kargo_tutar_baraji - $odenecek_ara_toplam;
                $yuzde = ($odenecek_ara_toplam / $kargo_tutar_baraji) * 100;
            ?>
            <div class="row mb-4">
                <div class="col-lg-8">
                    <div class="alert alert-info border-0 shadow-sm rounded-4 px-4 py-3">
                        <div class="d-flex justify-content-between mb-2">
                            <span class="fw-bold text-dark"><i class="bi bi-box-seam me-2 text-primary"></i>Ücretsiz Kargo Fırsatı!</span>
                            <span class="text-primary fw-bold"><?= number_format($kalan_tutar, 2, ',', '.') ?> ₺ Kaldı</span>
                        </div>
                        <div class="progress" style="height: 10px;">
                            <div class="progress-bar progress-bar-striped progress-bar-animated bg-primary" role="progressbar" style="width: <?= $yuzde ?>%" aria-valuenow="<?= $yuzde ?>" aria-valuemin="0" aria-valuemax="100"></div>
                        </div>
                        <small class="text-muted mt-2 d-block">Sepetinize biraz daha ürün ekleyerek kargonuz ücretsiz olsun..</small>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-lg-8 mb-4">
                <div class="card shadow-sm border-0">
                    <div class="card-body p-0">
                        <ul class="list-group list-group-flush">
                            <?php foreach ($sepet_urunleri as $urun): ?>
                                <?php 
                                    $guncel_fiyat = $urun['discount_price'] > 0 ? $urun['discount_price'] : $urun['price'];
                                    $kdvli_fiyat_goster = ($urun['vat_included'] == 1) ? $guncel_fiyat : $guncel_fiyat * (1 + ($urun['vat_rate'] / 100));
                                    $toplam_fiyat = $kdvli_fiyat_goster * $urun['quantity'];
                                    
                                    $tur_isimleri = [
                                        'subscription' => 'Abonelik Sistemi',
                                        'physical' => 'Fiziksel Kitap / Ürün',
                                        'digital' => 'Dijital İçerik (E-Kitap/PDF)',
                                        'single_exam' => 'Tekli Deneme',
                                        'exam_package' => 'Özel Deneme Paketi'
                                    ];
                                    $urun_turu_tr = isset($tur_isimleri[$urun['type']]) ? $tur_isimleri[$urun['type']] : 'Standart Ürün';

                                    // Joker Kapak Zekası
                                    $gorsel = $urun['main_image'];
                                    if ($gorsel == 'assets/img/no-image.jpg' && !empty($urun['brand_logo'])) {
                                        $gorsel = $urun['brand_logo'];
                                    }
                                ?>
                                <li class="list-group-item p-4">
                                    <div class="row align-items-center">
                                        <div class="col-3 col-md-2 text-center">
                                            <img src="<?= $kok_dizin ?><?= htmlspecialchars($gorsel) ?>" class="img-fluid rounded" style="max-height: 80px; object-fit: contain;">
                                        </div>
                                        <div class="col-9 col-md-5 mb-3 mb-md-0 text-dark">
                                            <h5 class="h6 fw-bold mb-1"><a href="<?= $kok_dizin ?>urun/<?= $urun['slug'] ?>" class="text-dark text-decoration-none"><?= htmlspecialchars($urun['name']) ?></a></h5>
                                            <div class="small text-muted mb-2 text-uppercase">Tür: <span class="badge bg-light text-dark border"><?= htmlspecialchars($urun_turu_tr) ?></span></div>
                                            
                                            <?php if ($urun['is_free_shipping'] == 1): ?>
                                                <div class="badge bg-success bg-opacity-10 text-success border border-success mb-2"><i class="bi bi-truck me-1"></i> Ücretsiz Kargo</div>
                                            <?php endif; ?>

                                            <?php if ($urun['stock_quantity'] < $urun['quantity'] && $urun['type'] != 'digital'): ?>
                                                <span class="badge bg-danger d-block text-start" style="width: fit-content;">Stok Yetersiz! Miktarı düşürün.</span>
                                            <?php endif; ?>

                                            <?php if ($urun['type'] == 'single_exam' && !empty($urun['exam_publication_date'])): ?>
                                                <div class="small mt-2 text-dark"><i class="bi bi-calendar-event text-primary me-1"></i> <span class="fw-bold">Yayın Tarihi:</span> <?= htmlspecialchars($urun['exam_publication_date']) ?></div>
                                            <?php endif; ?>

                                            <?php 
                                            // --- KARGOLAMA VE TESLİMAT ZEKASI ---
                                            if ($urun['type'] == 'single_exam' && !empty($urun['exam_publication_date'])) {
                                                $tarihObj = DateTime::createFromFormat('d.m.Y', $urun['exam_publication_date']);
                                                $bugunObj = new DateTime('midnight');
                                                if ($tarihObj) {
                                                    if ($tarihObj < $bugunObj) {
                                                        echo '<div class="small mt-1 text-success fw-bold"><i class="bi bi-box-seam me-1"></i> Gönderim: Stokta - Hemen Kargo</div>';
                                                    } else {
                                                        $gun_farki = (2 - $tarihObj->format('N') + 7) % 7;
                                                        if ($gun_farki === 0) $gun_farki = 7;
                                                        $kargoTarihi = clone $tarihObj;
                                                        $kargoTarihi->modify("+$gun_farki days");
                                                        echo '<div class="small mt-1 text-primary fw-bold"><i class="bi bi-calendar2-week me-1"></i> Kargoya Veriliş: ' . $kargoTarihi->format('d.m.Y') . ' (Salı)</div>';
                                                    }
                                                }
                                            } elseif (!empty($urun['shipping_info'])) {
                                                echo '<div class="small mt-2 text-info fw-bold"><i class="bi bi-info-circle me-1"></i> ' . htmlspecialchars($urun['shipping_info']) . '</div>';
                                            }
                                            ?>

                                        </div>
                                        <div class="col-6 col-md-3">
                                            <div class="input-group input-group-sm w-75 mx-auto mx-md-0 shadow-sm border rounded">
                                                <button class="btn btn-light border-end" type="button" onclick="updateCartItem(<?= $urun['cart_item_id'] ?>, <?= $urun['quantity'] - 1 ?>)">
                                                    <i class="bi bi-dash"></i>
                                                </button>
                                                <input type="text" class="form-control text-center border-0 fw-bold bg-white" value="<?= $urun['quantity'] ?>" readonly style="min-width: 40px;">
                                                <button class="btn btn-light border-start" type="button" onclick="updateCartItem(<?= $urun['cart_item_id'] ?>, <?= $urun['quantity'] + 1 ?>)">
                                                    <i class="bi bi-plus"></i>
                                                </button>
                                            </div>
                                            <div class="text-center text-md-start mt-1">
                                                <?php if($urun['discount_price'] > 0): ?>
                                                    <small class="text-muted text-decoration-line-through d-block" style="font-size: 10px;"><?= number_format(($urun['vat_included'] == 1 ? $urun['price'] : $urun['price'] * (1 + ($urun['vat_rate'] / 100))), 2, ',', '.') ?> ₺</small>
                                                <?php endif; ?>
                                                <small class="text-danger fw-bold" style="font-size: 11px;">Birim: <?= number_format($kdvli_fiyat_goster, 2, ',', '.') ?> ₺</small>
                                            </div>
                                        </div>
                                        <div class="col-6 col-md-2 text-end">
                                            <div class="fw-bold text-primary fs-5"><?= number_format($toplam_fiyat, 2, ',', '.') ?> ₺</div>
                                            <button class="btn btn-link text-danger text-decoration-none p-0 mt-1 small" onclick="removeCartItem(<?= $urun['cart_item_id'] ?>)"><i class="bi bi-trash"></i> Kaldır</button>
                                        </div>
                                    </div>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            </div>

            <div class="col-lg-4 text-dark">
                <div class="card shadow-sm border-0 position-sticky" style="top: 80px;">
                    <div class="card-header bg-white pt-4 pb-3 border-bottom">
                        <h5 class="fw-bold mb-0">Sipariş Özeti</h5>
                    </div>
                    <div class="card-body p-4">
                        
                        <div class="mb-4 bg-light p-3 rounded border">
                            <label class="form-label fw-bold small text-muted text-uppercase">İndirim Kodu / Kupon</label>
                            <?php if ($uygulanan_kupon): ?>
                                <div class="alert alert-success d-flex justify-content-between align-items-center mb-0 p-2 border-success">
                                    <div><i class="bi bi-tag-fill me-1"></i> <strong><?= htmlspecialchars($uygulanan_kupon) ?></strong></div>
                                    <button class="btn btn-sm btn-outline-danger border-0" onclick="removeCoupon()" title="Kuponu İptal Et"><i class="bi bi-x-circle-fill"></i></button>
                                </div>
                            <?php else: ?>
                                <div class="input-group">
                                    <input type="text" id="couponInput" class="form-control" placeholder="Kodunuzu girin">
                                    <button class="btn btn-dark" onclick="applyCoupon()">Uygula</button>
                                </div>
                                
                                <?php if(isset($_SESSION['user_id']) && count($kullanilabilir_kuponlar) > 0): ?>
                                    <div class="mt-2 text-end">
                                        <a href="#" class="small text-primary text-decoration-none fw-bold" data-bs-toggle="modal" data-bs-target="#sepetKuponModal">
                                            <i class="bi bi-ticket-detailed"></i> Sana Özel Kuponlar (<?= count($kullanilabilir_kuponlar) ?>)
                                        </a>
                                    </div>
                                <?php elseif(!isset($_SESSION['user_id'])): ?>
                                    <div class="mt-2 text-end">
                                        <a href="<?= $kok_dizin ?>giris.php" class="small text-muted text-decoration-none"><i class="bi bi-lock"></i> Kuponlarınızı görmek için giriş yapın</a>
                                    </div>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>

                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-muted">Ara Toplam (KDV Hariç)</span>
                            <span class="fw-bold"><?= number_format($kdv_haric_toplam, 2, ',', '.') ?> ₺</span>
                        </div>
                        
                        <div class="d-flex justify-content-between mb-2">
                            <span class="text-muted">KDV Toplamı<?= $kdv_oran_metni ?></span>
                            <span class="fw-bold"><?= number_format($toplam_kdv, 2, ',', '.') ?> ₺</span>
                        </div>

                        <?php if ($indirim_tutari > 0): ?>
                            <div class="d-flex justify-content-between mb-2 text-success">
                                <span><i class="bi bi-tags"></i> Kupon İndirimi</span>
                                <span class="fw-bold">- <?= number_format($indirim_tutari, 2, ',', '.') ?> ₺</span>
                            </div>
                        <?php endif; ?>
                        
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <span class="text-muted">Kargo Ücreti</span>
                            <?php if (!$fiziksel_urun_var_mi): ?>
                                <span class="text-success fw-bold">Kargo Yok</span>
                            <?php elseif ($kargo_ucreti == 0): ?>
                                <div class="text-end">
                                    <span class="text-muted text-decoration-line-through me-2"><?= number_format($kargo_sabit_ucret, 2, ',', '.') ?> ₺</span>
                                    <span class="text-success fw-bold">Ücretsiz</span>
                                    <div class="mt-1 d-block">
                                        <?= $kargo_sebebi ?>
                                    </div>
                                </div>
                            <?php else: ?>
                                <span class="fw-bold"><?= number_format($kargo_ucreti, 2, ',', '.') ?> ₺</span>
                            <?php endif; ?>
                        </div>

                        <hr>
                        
                        <?php if ($toplam_kazanc > 0): ?>
                            <div class="alert alert-success border-0 shadow-sm rounded-3 px-3 py-2 mb-3 d-flex justify-content-between align-items-center">
                                <span class="fw-bold" style="font-size: 0.9rem;"><i class="bi bi-piggy-bank-fill me-2"></i>Toplam Kazancınız</span>
                                <span class="fw-bold fs-5"><?= number_format($toplam_kazanc, 2, ',', '.') ?> ₺</span>
                            </div>
                        <?php endif; ?>

                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <span class="h5 fw-bold mb-0">Ödenecek Tutar</span>
                            <span class="h3 fw-bold text-danger mb-0"><?= number_format($genel_toplam, 2, ',', '.') ?> ₺</span>
                        </div>

                        <a href="<?= $kok_dizin ?>odeme-adimi.php" class="btn btn-success btn-lg w-100 fw-bold shadow-sm py-3 rounded-pill">
                            Alışverişi Tamamla <i class="bi bi-lock-fill ms-1"></i>
                        </a>
                        <a href="<?= $kok_dizin ?>index.php" class="btn btn-link text-muted text-decoration-none w-100 mt-2 small text-center d-block">
                            Alışverişe Devam Et
                        </a>
                    </div>
                </div>
            </div>
        </div>

    <?php else: ?>
        <div class="text-center py-5 bg-white rounded shadow-sm border">
            <i class="bi bi-cart-x text-muted" style="font-size: 4rem;"></i>
            <h3 class="mt-3 fw-bold text-dark">Sepetiniz şu an boş.</h3>
            <p class="text-muted">Sınavlara hazırlıkta en iyi kaynaklar sizi bekliyor.</p>
            <a href="<?= $kok_dizin ?>index.php" class="btn btn-primary btn-lg mt-3 px-5 rounded-pill">Alışverişe Başla</a>
        </div>
    <?php endif; ?>
</main>

<?php if(isset($_SESSION['user_id']) && count($kullanilabilir_kuponlar) > 0 && !$uygulanan_kupon): ?>
<div class="modal fade" id="sepetKuponModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title fw-bold"><i class="bi bi-ticket-perforated me-2"></i>Kullanılabilir Kuponlarınız</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body bg-light">
                <div class="list-group">
                    <?php foreach($kullanilabilir_kuponlar as $kupon): ?>
                        <?php 
                            $indirim_metni = ($kupon['discount_type'] == 'percentage') ? '%'.round($kupon['discount_value']).' İndirim' : number_format($kupon['discount_value'], 0).' TL İndirim';
                            $uygun_mu = ($ara_toplam >= $kupon['min_cart_amount']);
                        ?>
                        <div class="list-group-item list-group-item-action p-3 mb-2 rounded border <?= $uygun_mu ? 'border-success' : 'border-secondary opacity-75' ?>">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <h6 class="fw-bold mb-1 text-dark"><?= $indirim_metni ?></h6>
                                    <small class="text-muted d-block mb-1">Kod: <strong class="user-select-all"><?= htmlspecialchars($kupon['code']) ?></strong></small>
                                    <small class="text-secondary" style="font-size: 11px;">
                                        <?= ($kupon['min_cart_amount'] > 0) ? "Min. Sepet: ".number_format($kupon['min_cart_amount'], 0)." TL" : "Alt limit yok" ?>
                                    </small>
                                </div>
                                <div>
                                    <?php if($uygun_mu): ?>
                                        <button class="btn btn-sm btn-success fw-bold px-3 shadow-sm" onclick="document.getElementById('couponInput').value='<?= htmlspecialchars($kupon['code']) ?>'; applyCoupon();">
                                            Kullan
                                        </button>
                                    <?php else: ?>
                                        <button class="btn btn-sm btn-secondary opacity-50" disabled title="Sepet tutarınız yetersiz">Yetersiz Bakiye</button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
function updateCartItem(itemId, qty) {
    if (qty < 1) return;
    let formData = new FormData();
    formData.append('action', 'update');
    formData.append('item_id', itemId);
    formData.append('quantity', qty);

    fetch('<?= $kok_dizin ?>sepet-islem.php', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(data => { if(data.status==='success') window.location.reload(); else alert(data.message); });
}

function removeCartItem(itemId) {
    if (!confirm('Ürünü sepetten çıkarmak istediğinize emin misiniz?')) return;
    let formData = new FormData();
    formData.append('action', 'remove');
    formData.append('item_id', itemId);

    fetch('<?= $kok_dizin ?>sepet-islem.php', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(data => { if(data.status==='success') window.location.reload(); });
}

function applyCoupon() {
    let code = document.getElementById('couponInput').value.trim();
    if (!code) { alert('Lütfen bir kupon kodu girin.'); return; }

    let formData = new FormData();
    formData.append('action', 'apply_coupon');
    formData.append('coupon_code', code);

    fetch('<?= $kok_dizin ?>sepet-islem.php', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(data => { 
            if(data.status === 'success') {
                window.location.reload(); 
            } else {
                alert(data.message); 
            }
        });
}

function removeCoupon() {
    let formData = new FormData();
    formData.append('action', 'remove_coupon');

    fetch('<?= $kok_dizin ?>sepet-islem.php', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(data => { if(data.status === 'success') window.location.reload(); });
}
</script>

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