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

// YENİ: Ürün Detay Sayfası Kayan Yazısını Çek
$marquee_product = $db->query("SELECT content FROM marquees WHERE page_type = 'product' AND status = 1")->fetchColumn();

// --- GENEL AYARLARI ÇEK (Teslimat ve Ödeme Standart Şablonları İçin) ---
$site_ayarlari = [];
try {
    $ayar_stmt = $db->query("SELECT * FROM settings LIMIT 1");
    if($ayar_stmt) {
        $site_ayarlari = $ayar_stmt->fetch(PDO::FETCH_ASSOC);
    }
} catch (PDOException $e) {
    // settings tablosu henüz yoksa veya hata verirse kodun patlamasını önler
}
// -----------------------------------------------------------------------

// 1. URL'den gelen slug'ı kontrol et
if (!isset($_GET['slug']) || empty($_GET['slug'])) {
    header("Location: index.php");
    exit;
}
$slug = trim($_GET['slug']);

// 2. Ürün Bilgilerini Çek (GÜNCELLEME: status = 1 kontrolü kaldırıldı, her ürün çekilir)
$stmt = $db->prepare("
    SELECT p.*, c.name as cat_name, c.slug as cat_slug, b.name as brand_name, b.default_cover, b.logo as brand_logo
    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    LEFT JOIN brands b ON p.brand_id = b.id
    WHERE p.slug = ?
");
$stmt->execute([$slug]);
$urun = $stmt->fetch();

// Ürün hiç yoksa ana sayfaya at (Örn: slug yanlış yazılmışsa)
if (!$urun) {
    header("Location: index.php");
    exit;
}

// ---------------------------------------------------------
// EĞER ÜRÜN "DENEME PAKETİ" İSE GÖNDERİM TAKVİMİNİ ÇEK
// ---------------------------------------------------------
$paket_takvimi = [];
if ($urun['type'] == 'exam_package') {
    $paket_stmt = $db->prepare("
        SELECT pi.delivery_sequence, pi.delivery_date, p.name as exam_name, p.exam_type, p.slug as exam_slug,
        COALESCE(
            (SELECT image_path FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1),
            (SELECT default_cover FROM brands WHERE id = p.brand_id),
            'assets/img/no-image.jpg'
        ) as exam_image
        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
    ");
    $paket_stmt->execute([$urun['id']]);
    $raw_paket = $paket_stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($raw_paket as $item) {
        $seq = $item['delivery_sequence'];
        if (!isset($paket_takvimi[$seq])) {
            $paket_takvimi[$seq] = [
                'date' => $item['delivery_date'],
                'exams' => []
            ];
        }
        $paket_takvimi[$seq]['exams'][] = $item;
    }
}
// ---------------------------------------------------------

// 3. Ürün Görsellerini Çek
$gorsel_stmt = $db->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY is_main DESC, id ASC");
$gorsel_stmt->execute([$urun['id']]);
$gorseller = $gorsel_stmt->fetchAll();

if (count($gorseller) > 0) {
    $ana_gorsel = $gorseller[0]['image_path'];
} else if (!empty($urun['default_cover'])) {
    $ana_gorsel = $urun['default_cover'];
} else {
    $ana_gorsel = 'assets/img/no-image.jpg';
}

$satis_fiyati = $urun['discount_price'] > 0 ? $urun['discount_price'] : $urun['price'];

// 4. BENZER ÜRÜNLERİ ÇEK (Sadece Aktif olanları çekmeye devam ediyoruz)
$benzer_stmt = $db->prepare("
    SELECT p.id, p.name, p.slug, p.type, p.price, p.discount_price, p.exam_publication_date, p.is_free_shipping,
    b.logo as brand_logo, b.name as brand_name,
    COALESCE(
        (SELECT image_path FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1),
        (SELECT default_cover FROM brands WHERE id = p.brand_id),
        'assets/img/no-image.jpg'
    ) as main_image
    FROM products p 
    LEFT JOIN brands b ON p.brand_id = b.id
    WHERE p.category_id = ? AND p.id != ? AND p.status = 1 
    ORDER BY RAND() LIMIT 4
");
$benzer_stmt->execute([$urun['category_id'], $urun['id']]);
$benzer_urunler = $benzer_stmt->fetchAll();

// 5. BU ÜRÜNE AİT ONAYLANMIŞ YORUMLARI ÇEK
$yorumlar_stmt = $db->prepare("
    SELECT name, rating, comment, created_at 
    FROM reviews 
    WHERE product_id = ? AND status = 1 
    ORDER BY created_at DESC
");
$yorumlar_stmt->execute([$urun['id']]);
$urun_yorumlari = $yorumlar_stmt->fetchAll();
$yorum_sayisi = count($urun_yorumlari);

$ortalama_puan = 0;
if ($yorum_sayisi > 0) {
    $toplam_puan = 0;
    foreach ($urun_yorumlari as $y) { $toplam_puan += $y['rating']; }
    $ortalama_puan = round($toplam_puan / $yorum_sayisi, 1);
}

// Ürün Detay SSS Çekimi
$sss_sorulari = $db->query("SELECT * FROM faqs WHERE page_type = 'product' AND status = 1 ORDER BY sort_order ASC, id DESC")->fetchAll();

// --- MÜŞTERİ YORUM YAPMA MOTORU ---
$mesaj_yorum = '';
$satinaldi_mi = false;
$is_favorited = false; // YENİ EKLENDİ
$is_price_alert = false; // YENİ EKLENDİ

if (isset($_SESSION['user_id'])) {
    $k_id = $_SESSION['user_id'];
    
    // YENİ: Favori kontrolü
    $fav_chk = $db->prepare("SELECT id FROM favorites WHERE user_id = ? AND product_id = ?");
    $fav_chk->execute([$k_id, $urun['id']]);
    if($fav_chk->fetch()) $is_favorited = true;

    // YENİ: Fiyat alarmı kontrolü
    $alert_chk = $db->prepare("SELECT id FROM price_alerts WHERE user_id = ? AND product_id = ?");
    $alert_chk->execute([$k_id, $urun['id']]);
    if($alert_chk->fetch()) $is_price_alert = true;
    
    $chk = $db->prepare("
        SELECT oi.id 
        FROM order_items oi 
        JOIN orders o ON oi.order_id = o.id 
        WHERE o.user_id = ? AND oi.product_id = ? AND o.status = 'completed' 
        LIMIT 1
    ");
    $chk->execute([$k_id, $urun['id']]);
    if ($chk->fetch()) {
        $satinaldi_mi = true;
    }
    
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['yorum_gonder'])) {
        if ($satinaldi_mi) {
            $rating = (int)$_POST['rating'];
            $comment = clean($_POST['comment']);
            
            $u_stmt = $db->prepare("SELECT name, surname FROM users WHERE id = ?");
            $u_stmt->execute([$k_id]);
            $u_info = $u_stmt->fetch();
            $ad_soyad = $u_info['name'] . ' ' . $u_info['surname'];
            
            $rev_chk = $db->prepare("SELECT id FROM reviews WHERE product_id = ? AND name = ?");
            $rev_chk->execute([$urun['id'], $ad_soyad]);
            
            if ($rev_chk->fetch()) {
                $mesaj_yorum = "<div class='alert alert-warning shadow-sm'><i class='bi bi-exclamation-triangle me-2'></i> Bu ürün için zaten bir değerlendirme yaptınız.</div>";
            } else {
                $ins = $db->prepare("INSERT INTO reviews (product_id, name, rating, comment, status) VALUES (?, ?, ?, ?, 0)");
                $ins->execute([$urun['id'], $ad_soyad, $rating, $comment]);
                $mesaj_yorum = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i> Değerlendirmeniz alındı! Yönetici onayından sonra yayınlanacaktır. Teşekkür ederiz.</div>";
            }
        }
    }
}
// ----------------------------------------

// Google Schema Kodu...
$schema_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$schema = [
    "@context" => "https://schema.org/",
    "@type" => "Product",
    "name" => $urun['name'],
    "image" => "https://" . $_SERVER['HTTP_HOST'] . "/" . $ana_gorsel,
    "description" => strip_tags($urun['description'] ?? $urun['name']),
    "sku" => $urun['sku'] ? $urun['sku'] : $urun['id'],
    "brand" => [
        "@type" => "Brand",
        "name" => $urun['brand_name'] ? $urun['brand_name'] : "Sınav Koçu"
    ],
    "offers" => [
        "@type" => "Offer",
        "url" => $schema_url,
        "priceCurrency" => "TRY",
        "price" => number_format($satis_fiyati, 2, '.', ''),
        "availability" => ($urun['stock_quantity'] > 0 || $urun['type'] != 'physical') ? "https://schema.org/InStock" : "https://schema.org/OutOfStock",
        "itemCondition" => "https://schema.org/NewCondition"
    ]
];

if ($yorum_sayisi > 0) {
    $schema["aggregateRating"] = [
        "@type" => "AggregateRating",
        "ratingValue" => $ortalama_puan,
        "reviewCount" => $yorum_sayisi
    ];
}

$page_title = $urun['name'] . " | SINAVKOCU Mağaza";

require_once 'header.php';
?>

<?php if($marquee_product): ?>
<section class="marquee-section bg-dark text-white shadow-sm border-bottom border-primary border-3">
    <div class="marquee-container">
        <div class="marquee-content fw-bold fs-6 tracking-wide">
            <?= $marquee_product ?> &nbsp;&nbsp;&nbsp; 
            <?= $marquee_product ?> &nbsp;&nbsp;&nbsp; 
            <?= $marquee_product ?> &nbsp;&nbsp;&nbsp; 
            <?= $marquee_product ?>
        </div>
    </div>
</section>
<?php endif; ?>

<script type="application/ld+json"><?= json_encode($schema, JSON_UNESCAPED_UNICODE); ?></script>

<main class="container py-4 text-dark">
    <?php if($urun['status'] == 0): ?>
    <div class="alert alert-danger shadow-sm border-0 border-start border-danger border-5 mb-4 rounded-3 d-flex align-items-center p-4">
        <i class="bi bi-x-circle-fill text-danger fs-1 me-3"></i>
        <div>
            <h4 class="fw-bold mb-1">Bu Ürün Şu An Satışa Kapalıdır</h4>
            <p class="mb-0">İncelemekte olduğunuz ürün stoklarımızda kalmamış veya yayından kaldırılmış olabilir. Sayfanın alt kısmındaki benzer ürünlere göz atabilirsiniz.</p>
        </div>
    </div>
    <?php endif; ?>

    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb mb-0">
            <li class="breadcrumb-item"><a href="index.php" class="text-decoration-none"><i class="bi bi-house-door"></i> Ana Sayfa</a></li>
            <?php if($urun['cat_name']): ?>
                <li class="breadcrumb-item"><a href="urun-kategori.php?kategori=<?= $urun['cat_slug'] ?>" class="text-decoration-none"><?= htmlspecialchars($urun['cat_name']) ?></a></li>
            <?php endif; ?>
            <li class="breadcrumb-item active text-truncate" aria-current="page" style="max-width: 500px;"><?= htmlspecialchars($urun['name']) ?></li>
        </ol>
    </nav>

    <div class="row bg-white rounded shadow-sm p-3 p-md-4 border mb-5 <?= ($urun['status'] == 0) ? 'opacity-75' : '' ?>">
        <div class="col-md-5 mb-4 mb-md-0">
            <div class="border rounded text-center p-2 mb-3 position-relative bg-light" style="height: 400px;">
                
                <?php if(!empty($urun['brand_logo'])): ?>
                    <div class="position-absolute top-0 end-0 m-2 bg-white rounded shadow-sm d-flex align-items-center justify-content-center p-1" style="width: 60px; height: 40px; z-index: 5;">
                        <img src="<?= htmlspecialchars($urun['brand_logo']) ?>" class="img-fluid" style="max-height: 100%; max-width: 100%; object-fit: contain;">
                    </div>
                <?php endif; ?>

                <?php if($urun['discount_price'] > 0): ?>
                    <span class="badge bg-danger position-absolute top-0 start-0 m-2 fs-6">-%<?= round((($urun['price'] - $urun['discount_price']) / $urun['price']) * 100) ?></span>
                <?php endif; ?>
                
                <img id="mainProductImage" src="<?= htmlspecialchars($ana_gorsel) ?>" class="img-fluid h-100 w-100" style="object-fit: contain;">
            </div>
            
            <?php if(count($gorseller) > 1): ?>
            <div class="d-flex gap-2 overflow-auto py-1">
                <?php foreach($gorseller as $gorsel): ?>
                    <div class="border rounded p-1 cursor-pointer thumbnail-wrapper" style="width: 80px; height: 80px; flex-shrink: 0;" onclick="changeMainImage('<?= htmlspecialchars($gorsel['image_path']) ?>', this)">
                        <img src="<?= htmlspecialchars($gorsel['image_path']) ?>" class="img-fluid h-100 w-100" style="object-fit: cover;">
                    </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>

        <div class="col-md-7 ps-md-5 d-flex flex-column text-dark">
            <?php if($urun['brand_name']): ?><span class="text-muted text-uppercase small fw-bold"><?= htmlspecialchars($urun['brand_name']) ?></span><?php endif; ?>
            <h1 class="h2 fw-bold mb-2"><?= htmlspecialchars($urun['name']) ?></h1>
            
            <?php if($yorum_sayisi > 0): ?>
                <div class="mb-3 d-flex align-items-center">
                    <div class="text-warning me-2" style="font-size: 1.1rem;">
                        <?= str_repeat('<i class="bi bi-star-fill"></i>', round($ortalama_puan)) ?>
                        <?= str_repeat('<i class="bi bi-star"></i>', 5 - round($ortalama_puan)) ?>
                    </div>
                    <a href="#yorumlar" class="text-muted small text-decoration-none" onclick="document.getElementById('yorumlar-tab').click();">(<?= $yorum_sayisi ?> Değerlendirme)</a>
                </div>
            <?php endif; ?>
            
            <div class="mb-4 bg-light p-3 rounded border border-light">
                <?php if($urun['discount_price'] > 0): ?>
                    <span class="text-muted text-decoration-line-through fs-5 me-2"><?= number_format($urun['price'], 2, ',', '.') ?> ₺</span>
                    <span class="text-danger fw-bold fs-2"><?= number_format($urun['discount_price'], 2, ',', '.') ?> ₺</span>
                <?php else: ?>
                    <span class="text-primary fw-bold fs-2"><?= number_format($urun['price'], 2, ',', '.') ?> ₺</span>
                <?php endif; ?>
            </div>

            <div class="mb-4">
                <ul class="list-unstyled mb-0">
                    <li class="mb-2"><i class="bi bi-box-seam text-secondary me-2"></i> <strong>Durum:</strong> 
                        <?php if($urun['status'] == 0): ?>
                            <span class="badge bg-danger">Satışa Kapalı</span>
                        <?php else: ?>
                            <?= ($urun['type'] == 'digital') ? '<span class="badge bg-success">Anında Tanımlama</span>' : (($urun['stock_quantity'] > 0) ? '<span class="text-success fw-bold">Stokta Var</span>' : '<span class="text-danger fw-bold">Tükendi</span>') ?>
                        <?php endif; ?>
                    </li>
                    <li class="mb-2"><i class="bi bi-upc-scan text-secondary me-2"></i> <strong>SKU:</strong> <?= htmlspecialchars($urun['sku'] ? $urun['sku'] : '-') ?></li>
                    
                    <?php if($urun['type'] != 'digital'): ?>
                        <li class="mb-2"><i class="bi bi-truck text-secondary me-2"></i> <strong>Kargo:</strong> 
                            <?= $urun['is_free_shipping'] == 1 ? '<span class="text-success fw-bold">Bedava Kargo</span>' : '<span class="text-muted fw-bold">Alıcı Öder</span>' ?>
                        </li>
                    <?php endif; ?>

                    <?php if($urun['shipping_info']): ?><li class="mb-2"><i class="bi bi-info-circle text-primary me-2"></i> <strong>Lojistik:</strong> <?= htmlspecialchars($urun['shipping_info']) ?></li><?php endif; ?>
                    
                    <?php if($urun['type'] == 'subscription'): ?>
                        <li class="mb-2"><i class="bi bi-calendar-event text-warning me-2"></i> <strong>Abonelik Planı:</strong> <?= $urun['total_deliveries'] ?> Aylık Gönderim</li>
                    <?php endif; ?>

                    <?php if($urun['type'] == 'single_exam'): ?>
                        <li class="mb-2"><i class="bi bi-calendar-check text-primary me-2"></i> <strong>Yayın Tarihi:</strong> <?= htmlspecialchars($urun['exam_publication_date']) ?: 'Belirtilmemiş' ?></li>
                        <?php
                        // --- YENİ EKLENEN KARGOLAMA MANTIĞI ---
                        if (!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 '<li class="mb-2"><i class="bi bi-box-seam text-success me-2"></i> <strong>Gönderim Durumu:</strong> <span class="text-success fw-bold">Stokta - Hemen Kargo</span></li>';
                                } 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 '<li class="mb-2"><i class="bi bi-calendar2-week text-primary me-2"></i> <strong>Kargoya Veriliş:</strong> <span class="text-primary fw-bold">' . $kargoTarihi->format('d.m.Y') . ' (Salı)</span></li>';
                                }
                            }
                        }
                        // --- BİTİŞ ---
                        ?>
                    <?php endif; ?>
                    
                    <?php if($urun['type'] == 'exam_package'): ?>
                        <li class="mb-2"><i class="bi bi-gift text-primary me-2"></i> <strong>Paket Tipi:</strong> Özel Deneme Paketi</li>
                        <li class="mb-2"><i class="bi bi-calendar3 text-primary me-2"></i> <strong>Gönderim:</strong> Toplam <?= count($paket_takvimi) ?> Farklı Kargo (Detaylar aşağıda)</li>
                    <?php endif; ?>
                </ul>
            </div>

            <div class="mt-auto pt-3 border-top">
                <?php if($urun['status'] == 0): ?>
                    <button class="btn btn-secondary btn-lg w-100 fw-bold" disabled><i class="bi bi-slash-circle me-2"></i>SATIŞA KAPALI</button>
                <?php elseif($urun['type'] != 'digital' && $urun['stock_quantity'] <= 0): ?>
                    <button class="btn btn-secondary btn-lg w-100 fw-bold" disabled>Ürün Tükendi</button>
                <?php else: ?>
                    <div class="d-flex gap-2 align-items-center mb-3">
    <input type="hidden" id="detailProductId" value="<?= $urun['id'] ?>">
    
    <?php if($urun['type'] != 'digital'): ?>
        <div class="input-group" style="width: 130px;">
            <button class="btn btn-outline-secondary px-3" type="button" onclick="updateQty(-1)">-</button>
            <input type="number" id="detailQtyInput" class="form-control text-center bg-white fw-bold" value="1" min="1" max="<?= $urun['stock_quantity'] ?>" readonly>
            <button class="btn btn-outline-secondary px-3" type="button" onclick="updateQty(1)">+</button>
        </div>
    <?php else: ?>
        <input type="hidden" value="1" id="detailQtyInput">
    <?php endif; ?>
    
    <button type="button" id="btnDetailAddToCart" class="btn btn-primary btn-lg flex-grow-1 fw-bold shadow-sm">
        <i class="bi bi-cart-plus me-2"></i> SEPETE EKLE
    </button>
    
    <button type="button" class="btn <?= $is_favorited ? 'btn-danger' : 'btn-outline-danger' ?> btn-lg shadow-sm fav-btn" data-pid="<?= $urun['id'] ?>" title="Favorilere Ekle">
        <i class="bi <?= $is_favorited ? 'bi-heart-fill' : 'bi-heart' ?>" id="favIcon"></i>
    </button>
</div>

<button type="button" class="btn <?= $is_price_alert ? 'btn-warning' : 'btn-outline-warning' ?> text-dark w-100 fw-bold shadow-sm alert-btn mb-4" data-pid="<?= $urun['id'] ?>">
    <i class="bi <?= $is_price_alert ? 'bi-bell-fill' : 'bi-bell' ?> me-2" id="alertIcon"></i> 
    <span id="alertText"><?= $is_price_alert ? 'Fiyat Alarmı Kuruldu' : 'Fiyatı Düşünce Haber Ver' ?></span>
</button>
                <?php endif; ?>
                
                <div class="mt-4 pt-3 border-top">
    <span class="text-muted small fw-bold mb-2 d-block text-uppercase" style="letter-spacing: 1px;">Bu Ürünü Paylaş:</span>
    <div class="d-flex gap-2">
        <?php $paylas_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>
        
        <button type="button" class="btn btn-light border rounded-circle shadow-sm share-btn d-flex align-items-center justify-content-center" data-platform="whatsapp" data-url="<?= $paylas_url ?>" style="width:42px; height:42px; color:#25D366; transition: 0.3s;" onmouseover="this.style.backgroundColor='#25D366'; this.style.color='#fff'" onmouseout="this.style.backgroundColor=''; this.style.color='#25D366'">
            <i class="bi bi-whatsapp fs-5"></i>
        </button>
        
        <button type="button" class="btn btn-light border rounded-circle shadow-sm share-btn d-flex align-items-center justify-content-center" data-platform="facebook" data-url="<?= $paylas_url ?>" style="width:42px; height:42px; color:#1877F2; transition: 0.3s;" onmouseover="this.style.backgroundColor='#1877F2'; this.style.color='#fff'" onmouseout="this.style.backgroundColor=''; this.style.color='#1877F2'">
            <i class="bi bi-facebook fs-5"></i>
        </button>
        
        <button type="button" class="btn btn-light border rounded-circle shadow-sm share-btn d-flex align-items-center justify-content-center" data-platform="twitter" data-url="<?= $paylas_url ?>" style="width:42px; height:42px; color:#000000; transition: 0.3s;" onmouseover="this.style.backgroundColor='#000'; this.style.color='#fff'" onmouseout="this.style.backgroundColor=''; this.style.color='#000'">
            <i class="bi bi-twitter fs-5"></i>
        </button>
        
        <button type="button" class="btn btn-light border rounded-circle shadow-sm share-btn d-flex align-items-center justify-content-center" data-platform="copy" data-url="<?= $paylas_url ?>" style="width:42px; height:42px; color:#6c757d; transition: 0.3s;" onmouseover="this.style.backgroundColor='#6c757d'; this.style.color='#fff'" onmouseout="this.style.backgroundColor=''; this.style.color='#6c757d'" title="Bağlantıyı Kopyala">
            <i class="bi bi-link-45deg fs-4"></i>
        </button>
    </div>
</div>
            </div>
        </div>
    </div>
    
    

    <div class="row mb-5">
        <div class="col-12 text-dark">
            <div class="card shadow-sm border-0">
                <div class="card-header bg-white border-bottom-0 pt-3 overflow-hidden">
                    <ul class="nav nav-tabs card-header-tabs flex-nowrap overflow-auto pb-1" id="myTab" role="tablist">
                        
                        <?php if($urun['type'] == 'exam_package' && count($paket_takvimi) > 0): ?>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active fw-bold text-primary text-nowrap" id="takvim-tab" data-bs-toggle="tab" data-bs-target="#takvim" type="button" role="tab">📦 Gönderim Takvimi ve Paket İçeriği</button>
                        </li>
                        <?php endif; ?>

                        <li class="nav-item" role="presentation">
                            <button class="nav-link <?= ($urun['type'] != 'exam_package') ? 'active' : '' ?> fw-bold text-dark text-nowrap" id="aciklama-tab" data-bs-toggle="tab" data-bs-target="#aciklama" type="button" role="tab">Ürün Açıklaması</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link fw-bold text-dark text-nowrap" id="yorumlar-tab" data-bs-toggle="tab" data-bs-target="#yorumlar" type="button" role="tab">
                                Müşteri Yorumları <span class="badge bg-secondary ms-1"><?= $yorum_sayisi ?></span>
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link fw-bold text-dark text-nowrap" id="odeme-tab" data-bs-toggle="tab" data-bs-target="#odeme" type="button" role="tab">Ödeme Seçenekleri</button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link fw-bold text-dark text-nowrap" id="kargo-tab" data-bs-toggle="tab" data-bs-target="#kargo" type="button" role="tab">Teslimat & İade</button>
                        </li>
                    </ul>
                </div>
                <div class="card-body p-4">
                    <div class="tab-content" id="myTabContent">
                        
                        <?php if($urun['type'] == 'exam_package' && count($paket_takvimi) > 0): ?>
                        <div class="tab-pane fade show active" id="takvim" role="tabpanel">
                            <div class="alert alert-info border-0 shadow-sm mb-4">
                                <i class="bi bi-info-circle-fill me-2"></i>Bu paket <strong><?= count($paket_takvimi) ?> aşamalı</strong> bir gönderim planına sahiptir. Aşağıdaki takvimde hangi tarihte adresinize hangi denemelerin kargolanacağını görebilirsiniz.
                            </div>
                            
                            <div class="timeline-container ps-2 ps-md-4">
                                <?php foreach($paket_takvimi as $seq => $data): ?>
                                    <div class="position-relative border-start border-primary border-3 ms-3 mb-5 ps-4">
                                        <span class="position-absolute bg-primary text-white rounded-circle d-flex align-items-center justify-content-center shadow" style="width:30px; height:30px; left:-16px; top:0;"><i class="bi bi-truck"></i></span>
                                        
                                        <div class="mb-3">
                                            <h5 class="fw-bold text-dark mb-0 d-inline-block"><?= $seq ?>. Gönderim</h5>
                                            <?php if($data['date']): ?>
                                                <span class="badge bg-warning text-dark ms-2" style="font-size:0.85rem;"><i class="bi bi-calendar-event me-1"></i> Kargolanma: <?= date('d.m.Y', strtotime($data['date'])) ?></span>
                                            <?php else: ?>
                                                <span class="badge bg-secondary ms-2" style="font-size:0.85rem;">Tarih Belirsiz</span>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <div class="row row-cols-1 row-cols-md-2 g-3">
                                            <?php foreach($data['exams'] as $exam): ?>
                                                <div class="col">
                                                    <div class="d-flex align-items-center border rounded bg-white p-2 shadow-sm h-100">
                                                        <img src="/magaza/<?= htmlspecialchars($exam['exam_image']) ?>" class="rounded object-fit-contain me-3 border bg-light" style="width:60px; height:80px;">
                                                        <div class="flex-grow-1 overflow-hidden">
                                                            <h6 class="fw-bold text-dark mb-1 text-truncate" title="<?= htmlspecialchars($exam['exam_name']) ?>"><?= htmlspecialchars($exam['exam_name']) ?></h6>
                                                            <div class="text-muted small">
                                                                <span class="badge bg-light text-dark border"><?= htmlspecialchars($exam['exam_type'] ?? 'Genel') ?></span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <div class="tab-pane fade <?= ($urun['type'] != 'exam_package') ? 'show active' : '' ?> lh-lg" id="aciklama" role="tabpanel">
                            <?= $urun['description'] ?> 
                        </div>
                        
                        <div class="tab-pane fade" id="yorumlar" role="tabpanel">
                            <?php if(isset($_SESSION['user_id'])): ?>
                                <?php if($satinaldi_mi): ?>
                                    <div class="mb-5 p-4 bg-light border border-primary border-opacity-25 rounded-4 shadow-sm">
                                        <h5 class="fw-bold mb-3 text-primary"><i class="bi bi-chat-right-text me-2"></i>Bu Ürünü Değerlendirin</h5>
                                        <?= $mesaj_yorum ?>
                                        <form method="POST" action="#yorumlar">
                                            <div class="row">
                                                <div class="col-md-3 mb-3">
                                                    <label class="form-label fw-bold small text-muted">Ürün Puanınız</label>
                                                    <select name="rating" class="form-select border-2 text-warning fw-bold" required>
                                                        <option value="5">⭐⭐⭐⭐⭐ (5)</option>
                                                        <option value="4">⭐⭐⭐⭐ (4)</option>
                                                        <option value="3">⭐⭐⭐ (3)</option>
                                                        <option value="2">⭐⭐ (2)</option>
                                                        <option value="1">⭐ (1)</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-9 mb-3">
                                                    <label class="form-label fw-bold small text-muted">Deneyiminiz</label>
                                                    <textarea name="comment" class="form-control border-2" rows="2" required placeholder="Ürün beklentilerinizi karşıladı mı?"></textarea>
                                                </div>
                                            </div>
                                            <div class="text-end">
                                                <button type="submit" name="yorum_gonder" class="btn btn-primary fw-bold px-4 rounded-pill">Yorumu Gönder</button>
                                            </div>
                                        </form>
                                    </div>
                                <?php else: ?>
                                    <div class="alert alert-secondary shadow-sm mb-5 border-0">
                                        <i class="bi bi-info-circle-fill text-secondary me-2"></i> Bu ürünü değerlendirebilmek için satın almış ve siparişinizin "Tamamlandı" durumuna geçmiş olması gerekmektedir.
                                    </div>
                                <?php endif; ?>
                            <?php else: ?>
                                <div class="alert alert-secondary shadow-sm mb-5 border-0 text-center">
                                    Ürün değerlendirmesi yapabilmek için <a href="giris.php" class="fw-bold text-dark text-decoration-none border-bottom border-dark">giriş yapmalısınız</a>.
                                </div>
                            <?php endif; ?>
                            
                            <?php if($yorum_sayisi > 0): ?>
                                <div class="row mb-4 align-items-center">
                                    <div class="col-md-4 text-center border-end">
                                        <h2 class="display-3 fw-bold text-dark mb-0"><?= $ortalama_puan ?></h2>
                                        <div class="text-warning fs-4">
                                            <?= str_repeat('<i class="bi bi-star-fill"></i>', round($ortalama_puan)) ?>
                                            <?= str_repeat('<i class="bi bi-star"></i>', 5 - round($ortalama_puan)) ?>
                                        </div>
                                        <span class="text-muted small"><?= $yorum_sayisi ?> Değerlendirme</span>
                                    </div>
                                    <div class="col-md-8 ps-md-4 mt-3 mt-md-0">
                                        <p class="text-muted mb-0"><i class="bi bi-patch-check-fill text-success me-1"></i> Tüm değerlendirmeler ürünü mağazamızdan satın alan ve kullanan onaylı müşterilerimize aittir.</p>
                                    </div>
                                </div>
                                
                                <div class="list-group list-group-flush border-top pt-3">
                                    <?php foreach($urun_yorumlari as $yorum): ?>
                                        <div class="list-group-item px-0 py-3 border-bottom-0 border-light mb-2 bg-light rounded px-3">
                                            <div class="d-flex justify-content-between align-items-center mb-2">
                                                <div>
                                                    <span class="fw-bold text-dark me-2"><i class="bi bi-person-circle text-secondary me-1"></i> <?= maskNameKVKK($yorum['name']) ?></span>
                                                    <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 rounded-pill" style="font-size: 0.7rem;"><i class="bi bi-check2-circle"></i> Onaylı Kullanıcı</span>
                                                </div>
                                                <small class="text-muted"><?= date('d.m.Y', strtotime($yorum['created_at'])) ?></small>
                                            </div>
                                            <div class="text-warning mb-2" style="font-size: 0.9rem;">
                                                <?= str_repeat('<i class="bi bi-star-fill"></i>', $yorum['rating']) ?>
                                                <?= str_repeat('<i class="bi bi-star"></i>', 5 - $yorum['rating']) ?>
                                            </div>
                                            <p class="mb-0 text-dark"><?= nl2br(htmlspecialchars($yorum['comment'])) ?></p>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php else: ?>
                                <div class="text-center py-5">
                                    <i class="bi bi-chat-square-text text-muted mb-3" style="font-size: 3rem;"></i>
                                    <h5 class="fw-bold text-dark">Bu ürüne henüz yorum yapılmamış.</h5>
                                    <p class="text-muted">Ürünü satın alarak ilk yorumu siz yapabilirsiniz.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="tab-pane fade" id="odeme" role="tabpanel">
                            <?php if(!empty($urun['custom_payment_text'])): ?>
                                <?= $urun['custom_payment_text'] ?>
                            <?php else: ?>
                                <?= $site_ayarlari['default_payment_text'] ?? '
                                <h5 class="fw-bold text-dark mb-3"><i class="bi bi-credit-card-2-front"></i> Güvenli Ödeme Altyapısı</h5>
                                <p>Sitemiz üzerinden yapacağınız tüm alışverişler 256-Bit SSL sertifikası ile korunmaktadır.</p>
                                <ul>
                                    <li>Kredi ve Banka Kartı</li>
                                    <li>Havale / EFT ile ödeme</li>
                                </ul>' ?>
                            <?php endif; ?>
                        </div>
                        
                        <div class="tab-pane fade" id="kargo" role="tabpanel">
                            <?php if(!empty($urun['custom_delivery_text'])): ?>
                                <?= $urun['custom_delivery_text'] ?>
                            <?php else: ?>
                                <?= $site_ayarlari['default_delivery_text'] ?? '
                                <h5 class="fw-bold text-dark mb-3"><i class="bi bi-box-seam"></i> Teslimat Şartları</h5>
                                <p><strong>Abonelikler ve Paketler:</strong> Düzenli gönderim içeren abonelik veya özel paket satın aldıysanız, kargolarınız belirtilen "Kargo Takvimi" tarihlerinde gönderilir.</p>
                                <p><strong>Kitaplar:</strong> Saat 15:00\'a kadar olan siparişler aynı gün kargoya teslim edilir.</p>' ?>
                            <?php endif; ?>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php if(count($benzer_urunler) > 0): ?>
    <section class="mb-5 text-dark">
        <h3 class="h4 fw-bold border-start border-primary border-4 ps-2 mb-4">Bu Kategorideki Diğer Ürünler</h3>
        <div class="row row-cols-2 row-cols-md-4 g-3">
            <?php foreach($benzer_urunler as $b_urun): ?>
                <div class="col">
                    <div class="card h-100 border-0 shadow-sm product-card transition rounded-4 overflow-hidden position-relative">
                        
                        <?php if(!empty($b_urun['brand_logo'])): ?>
                            <div class="position-absolute top-0 end-0 m-2 bg-white rounded shadow-sm d-flex align-items-center justify-content-center p-1" style="width: 40px; height: 25px; z-index: 5;">
                                <img src="<?= htmlspecialchars($b_urun['brand_logo']) ?>" class="img-fluid" style="max-height: 100%; max-width: 100%; object-fit: contain;">
                            </div>
                        <?php endif; ?>

                        <div class="position-relative overflow-hidden bg-light p-2 text-center">
                            <a href="urun-detay.php?slug=<?= $b_urun['slug'] ?>">
                                <img src="<?= htmlspecialchars($b_urun['main_image']) ?>" 
                                     class="card-img-top p-2" alt="<?= htmlspecialchars($b_urun['name']) ?>" 
                                     style="height: 180px; object-fit: contain;">
                            </a>
                            <?php if ($b_urun['discount_price'] > 0): ?>
                                <span class="badge bg-danger position-absolute top-0 start-0 m-2 shadow-sm px-2 py-1" style="z-index: 2; font-size:0.7rem;">-%<?= round((($b_urun['price'] - $b_urun['discount_price']) / $b_urun['price']) * 100) ?></span>
                            <?php endif; ?>
                            <?php if ($b_urun['is_free_shipping'] == 1): ?>
                                <span class="badge bg-success position-absolute bottom-0 end-0 m-2 shadow-sm px-2 py-1" style="z-index: 2; font-size:0.7rem;"><i class="bi bi-truck me-1"></i>Kargo Bedava</span>
                            <?php endif; ?>
                            <?php if ($b_urun['type'] == 'subscription' || $b_urun['type'] == 'exam_package'): ?>
                                <span class="badge bg-dark position-absolute bottom-0 start-0 m-2 shadow-sm px-2 py-1" style="z-index: 2; font-size:0.7rem;"><i class="bi bi-truck me-1"></i>Paket</span>
                            <?php endif; ?>
                        </div>

                        <div class="card-body text-center d-flex flex-column bg-white border-top p-2">
                            <h5 class="card-title fw-bold mb-1" style="height: 32px; overflow: hidden; font-size: 0.85rem;">
                                <a href="urun-detay.php?slug=<?= $b_urun['slug'] ?>" class="text-dark text-decoration-none" title="<?= htmlspecialchars($b_urun['name']) ?>">
                                    <?= htmlspecialchars($b_urun['name']) ?>
                                </a>
                            </h5>
                            
                            <?php if($b_urun['type'] == 'single_exam'): ?>
                                <div class="d-flex justify-content-between align-items-center mb-1 px-1 border-bottom pb-1">
                                    <div class="small text-muted fw-bold" style="font-size: 0.65rem;">
                                        <i class="bi bi-calendar-event text-primary"></i> <?= htmlspecialchars($b_urun['exam_publication_date']) ?: 'Tarih Yok' ?>
                                    </div>
                                    <div class="small fw-bold" style="font-size: 0.65rem;">
                                        <?php if($b_urun['is_free_shipping'] == 1): ?>
                                            <span class="text-success"><i class="bi bi-truck"></i> Bedava</span>
                                        <?php else: ?>
                                            <span class="text-muted"><i class="bi bi-truck"></i> Alıcı Öder</span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <div class="mt-auto pt-1">
                                <?php if ($b_urun['discount_price'] > 0): ?>
                                    <div class="d-flex justify-content-center align-items-baseline gap-1">
                                        <span class="text-muted small text-decoration-line-through" style="font-size:0.7rem;"><?= number_format($b_urun['price'], 2, ',', '.') ?> ₺</span>
                                        <span class="text-danger fw-bold fs-6"><?= number_format($b_urun['discount_price'], 2, ',', '.') ?> ₺</span>
                                    </div>
                                <?php else: ?>
                                    <div class="text-primary fw-bold fs-6"><?= number_format($b_urun['price'], 2, ',', '.') ?> ₺</div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>

    <?php if(count($sss_sorulari) > 0): ?>
    <div class="mt-5 pt-4 border-top">
        <section class="bg-white p-4 p-md-5 rounded-4 shadow-sm border border-light">
            <div class="text-center mb-4">
                <h2 class="h3 fw-bold text-dark mb-1">Sıkça Sorulan Sorular</h2>
                <p class="text-muted small">Alışverişiniz hakkında merak edilenler</p>
            </div>
            
            <div class="accordion accordion-flush" id="accordionSssProduct">
                <?php foreach($sss_sorulari as $index => $soru): ?>
                    <div class="accordion-item border-bottom">
                        <h2 class="accordion-header" id="flush-heading-<?= $soru['id'] ?>">
                            <button class="accordion-button <?= $index !== 0 ? 'collapsed' : '' ?> fw-bold text-dark fs-6 bg-white" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapse-<?= $soru['id'] ?>">
                                <?= htmlspecialchars($soru['question']) ?>
                            </button>
                        </h2>
                        <div id="flush-collapse-<?= $soru['id'] ?>" class="accordion-collapse collapse <?= $index === 0 ? 'show' : '' ?>" data-bs-parent="#accordionSssProduct">
                            <div class="accordion-body text-muted lh-lg">
                                <?= nl2br(htmlspecialchars($soru['answer'])) ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </section>
    </div>
    <?php endif; ?>

</main>

<style>
.marquee-section { padding: 10px 0; }
.marquee-container { width: 100%; overflow: hidden; white-space: nowrap; position: relative; }
.marquee-content { display: inline-block; padding-left: 100%; animation: marqueeScroll 25s linear infinite; }
.marquee-content:hover { animation-play-state: paused; cursor: pointer; }
.tracking-wide { letter-spacing: 1px; }
@keyframes marqueeScroll { 0% { transform: translate(0, 0); } 100% { transform: translate(-100%, 0); } }
.product-card { transition: all 0.3s ease; }
.product-card:hover { transform: translateY(-7px); box-shadow: 0 14px 28px rgba(0,0,0,0.1) !important; }
.timeline-container { border-left: 3px solid #dee2e6; margin-left: 10px; padding-left: 0; }
</style>

<script>
function changeMainImage(path, el) {
    document.getElementById('mainProductImage').src = path;
    document.querySelectorAll('.thumbnail-wrapper').forEach(th => th.classList.remove('border-primary', 'border-2'));
    el.classList.add('border-primary', 'border-2');
}

function updateQty(ch) {
    let inp = document.getElementById('detailQtyInput');
    let val = parseInt(inp.value) + ch;
    let max = parseInt(inp.getAttribute('max')) || 999;
    if(val >= 1 && val <= max) inp.value = val;
}

// PAYLAŞIM VE İSTATİSTİK MOTORU
document.querySelectorAll('.share-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        let platform = this.getAttribute('data-platform');
        let url = this.getAttribute('data-url');
        let text = encodeURIComponent("Bu ürünü Beğendim Alacağım Sende İncele: ");
        let shareUrl = '';

        // İlgili platformun linkini oluştur
        if (platform === 'whatsapp') shareUrl = 'https://api.whatsapp.com/send?text=' + text + encodeURIComponent(url);
        if (platform === 'facebook') shareUrl = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(url);
        if (platform === 'twitter') shareUrl = 'https://twitter.com/intent/tweet?text=' + text + '&url=' + encodeURIComponent(url);

        // Arka planda veritabanına logla
        let fd = new FormData();
        fd.append('product_id', document.getElementById('detailProductId').value);
        fd.append('platform', platform);
        fetch('ajax-share.php', { method: 'POST', body: fd });

        // İşlemi gerçekleştir
        if(platform === 'copy') {
            navigator.clipboard.writeText(url).then(() => {
                if(typeof Swal !== 'undefined') {
                    Swal.fire({ icon: 'success', title: 'Kopyalandı!', text: 'Ürün bağlantısı panoya kopyalandı.', timer: 1500, showConfirmButton: false });
                } else {
                    alert("Bağlantı kopyalandı!");
                }
            });
        } else {
            // Popup olarak aç
            window.open(shareUrl, '_blank', 'width=600,height=500,toolbar=0,status=0');
        }
    });
});

// KULLANICI GİRİŞ KONTROLÜ (PHP'den JS'ye)
const isUserLoggedIn = <?= isset($_SESSION['user_id']) ? 'true' : 'false' ?>;

// FAVORİ VE ALARM BUTON İŞLEMLERİ
document.querySelectorAll('.fav-btn, .alert-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        if (!isUserLoggedIn) {
            Swal.fire({
                icon: 'info',
                title: 'Giriş Yapmalısınız',
                text: 'Bu özelliği kullanabilmek için lütfen üye girişi yapın.',
                confirmButtonText: 'Giriş Yap',
                confirmButtonColor: '#0d6efd',
                showCancelButton: true,
                cancelButtonText: 'İptal'
            }).then((result) => {
                if (result.isConfirmed) window.location.href = "giris.php";
            });
            return;
        }

        let isFav = this.classList.contains('fav-btn');
        let action = isFav ? 'toggle_fav' : 'toggle_alert';
        let pid = this.getAttribute('data-pid');
        let currentPrice = <?= $satis_fiyati ?>; // O anki fiyatı da gönderiyoruz

        let fd = new FormData();
        fd.append('action', action);
        fd.append('product_id', pid);
        fd.append('price', currentPrice);

        fetch('ajax-user-actions.php', { method: 'POST', body: fd })
        .then(res => res.json())
        .then(data => {
            if(data.status === 'success') {
                // Favori butonu UI güncellemesi
                if(isFav) {
                    let icon = document.getElementById('favIcon');
                    if(data.state === 'added') {
                        this.classList.replace('btn-outline-danger', 'btn-danger');
                        icon.classList.replace('bi-heart', 'bi-heart-fill');
                        Swal.fire({icon: 'success', title: 'Eklendi', text: 'Ürün favorilerinize eklendi.', timer: 1500, showConfirmButton: false});
                    } else {
                        this.classList.replace('btn-danger', 'btn-outline-danger');
                        icon.classList.replace('bi-heart-fill', 'bi-heart');
                        Swal.fire({icon: 'info', title: 'Çıkarıldı', text: 'Ürün favorilerinizden çıkarıldı.', timer: 1500, showConfirmButton: false});
                    }
                } 
                // Alarm butonu UI güncellemesi
                else {
                    let icon = document.getElementById('alertIcon');
                    let text = document.getElementById('alertText');
                    if(data.state === 'added') {
                        this.classList.replace('btn-outline-warning', 'btn-warning');
                        icon.classList.replace('bi-bell', 'bi-bell-fill');
                        text.innerText = 'Fiyat Alarmı Kuruldu';
                        Swal.fire({icon: 'success', title: 'Alarm Kuruldu', text: 'Fiyat düştüğünde size bildirim göndereceğiz.', timer: 2000, showConfirmButton: false});
                    } else {
                        this.classList.replace('btn-warning', 'btn-outline-warning');
                        icon.classList.replace('bi-bell-fill', 'bi-bell');
                        text.innerText = 'Fiyatı Düşünce Haber Ver';
                        Swal.fire({icon: 'info', title: 'Alarm İptal', text: 'Fiyat alarmı iptal edildi.', timer: 1500, showConfirmButton: false});
                    }
                }
            }
        });
    });
});

// SEPETE EKLEME MOTORU
document.getElementById('btnDetailAddToCart')?.addEventListener('click', function() {
    const btn = this;
    const productId = document.getElementById('detailProductId').value;
    const quantity = document.getElementById('detailQtyInput').value;

    const originalHTML = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Ekleniyor...';

    let formData = new FormData();
    formData.append('action', 'add');
    formData.append('product_id', productId);
    formData.append('quantity', quantity);

    fetch('sepet-islem.php', {
        method: 'POST',
        body: formData,
        credentials: 'same-origin'
    })
    .then(res => res.json())
    .then(data => {
        btn.innerHTML = originalHTML;
        btn.disabled = false;

        if(data.status === 'success') {
            const cartBadge = document.getElementById('cartBadge');
            if(cartBadge && data.total_items !== undefined) {
                cartBadge.innerText = data.total_items;
            }

            if(typeof Swal !== 'undefined') {
                Swal.fire({
                    title: 'Harika!',
                    text: data.message,
                    icon: 'success',
                    showCancelButton: true,
                    confirmButtonText: '<i class="bi bi-cart-check me-1"></i> Sepete Git',
                    cancelButtonText: 'Alışverişe Devam',
                    reverseButtons: true,
                    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 {
                alert(data.message);
            }
        } else {
            if(typeof Swal !== 'undefined') {
                Swal.fire('Hata!', data.message, 'warning');
            } else {
                alert(data.message);
            }
        }
    })
    .catch(err => {
        btn.innerHTML = originalHTML;
        btn.disabled = false;
        alert("Bir bağlantı hatası oluştu.");
    });
});
</script>

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