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

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

// YENİ: Kategori Sayfası Kayan Yazısını Çek
$marquee_category = $db->query("SELECT content FROM marquees WHERE page_type = 'category' AND status = 1")->fetchColumn();

// YENİ: Kategori Sayfası Sıkça Sorulan Sorularını (S.S.S) Çek
$sss_sorulari = $db->query("SELECT * FROM faqs WHERE page_type = 'category' AND status = 1 ORDER BY sort_order ASC, id DESC")->fetchAll();

// --- 1. ARAMA, İNDİRİM VEYA KATEGORİ KONTROLÜ ---
$kategori = null;
$sorgu_kosulu = "p.status = 1"; 
$parametreler = [];
$sayfa_basligi = "Tüm Ürünler";
$sorgu_tipi = ''; 

// --- SIRALAMA İÇİN BASE URL OLUŞTURUCU (SEO UYUMLU YAPI İÇİN) ---
$sort_base_url = "";

if (isset($_GET['kategori']) && !empty($_GET['kategori'])) {
    $slug = trim($_GET['kategori']); 
    $sorgu_tipi = "kategori=$slug";
    $sort_base_url = $kok_dizin . "kategori/" . htmlspecialchars($slug) . "?"; // YENİ SEO URL
    
    $stmt = $db->prepare("SELECT * FROM categories WHERE slug = ? AND status = 1");
    $stmt->execute([$slug]);
    $kategori = $stmt->fetch();

    if ($kategori) {
        // GÜNCELLEME: Hem ana kategori ID'sine hem de Çoklu Kategori (Pivot) tablosuna bakar!
        $sorgu_kosulu .= " AND (p.category_id = ? OR p.id IN (SELECT product_id FROM product_categories WHERE category_id = ?))";
        $parametreler[] = $kategori['id'];
        $parametreler[] = $kategori['id']; // İki soru işareti (?) olduğu için iki kez ekliyoruz
        $sayfa_basligi = $kategori['name'];
    } else {
        header("Location: " . $kok_dizin . "index.php");
        exit;
    }
}
elseif (isset($_GET['indirim']) && $_GET['indirim'] == 1) {
    $sorgu_tipi = "indirim=1";
    $sort_base_url = $kok_dizin . "indirimli-urunler.php?";
    $sorgu_kosulu .= " AND p.discount_price IS NOT NULL AND p.discount_price > 0";
    $sayfa_basligi = "% İndirimli Ürünler";
} 
elseif (isset($_GET['q']) && !empty(trim($_GET['q']))) {
    $arama = trim($_GET['q']);
    $sorgu_tipi = "q=" . urlencode($arama);
    $sort_base_url = $kok_dizin . "urun-kategori.php?q=" . urlencode($arama) . "&";
    $sorgu_kosulu .= " AND (p.name LIKE ? OR p.description LIKE ? OR p.sku LIKE ?)";
    $parametreler[] = "%$arama%";
    $parametreler[] = "%$arama%";
    $parametreler[] = "%$arama%"; 
    $sayfa_basligi = "'$arama' için arama sonuçları";
} 
else {
    header("Location: " . $kok_dizin . "index.php");
    exit;
}

// --- SAYFALAMA AYARLARI (YENİ EKLE) ---
$urun_basina_limit = 24; 
$sayfa = isset($_GET['sayfa']) && is_numeric($_GET['sayfa']) ? (int)$_GET['sayfa'] : 1;
if ($sayfa < 1) $sayfa = 1;
$offset = ($sayfa - 1) * $urun_basina_limit;

// Toplam ürün sayısını bulmak için (Sorgu koşulundan sonra, SQL sorgusundan önce)
$count_stmt = $db->prepare("SELECT COUNT(p.id) FROM products p WHERE $sorgu_kosulu");
$count_stmt->execute($parametreler);
$toplam_urun = $count_stmt->fetchColumn();
$toplam_sayfa = ceil($toplam_urun / $urun_basina_limit);

// --- 2. SIRALAMA AYARLARI ---
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'random'; // Varsayılanı 'random' yaptık
$order_query = "RAND()"; // Varsayılan sıralama sorgusu rastgele oldu

switch ($sort) {
    case 'price_low': 
        $order_query = "COALESCE(NULLIF(p.discount_price, 0), p.price) ASC"; 
        break;
    case 'price_high': 
        $order_query = "COALESCE(NULLIF(p.discount_price, 0), p.price) DESC"; 
        break;
    case 'newest': 
        $order_query = "p.created_at DESC"; 
        break;
    case 'random': 
        $order_query = "RAND()"; 
        break;
}

// --- 3. ÜRÜNLERİ ÇEK (Joker Kapak, Logo ve Kargo Zekası) ---
$p_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 $sorgu_kosulu
   ORDER BY $order_query
    LIMIT $urun_basina_limit OFFSET $offset
");
$p_stmt->execute($parametreler);
$urunler = $p_stmt->fetchAll();

$page_title = $sayfa_basligi . " | Kitap, Deneme, Kırtasiye, Teknoloji | SINAVKOCU Mağaza";
require_once 'header.php';
?>

<?php if($marquee_category): ?>
<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_category ?> &nbsp;&nbsp;&nbsp; 
            <?= $marquee_category ?> &nbsp;&nbsp;&nbsp; 
            <?= $marquee_category ?> &nbsp;&nbsp;&nbsp; 
            <?= $marquee_category ?>
        </div>
    </div>
</section>
<?php endif; ?>

<nav class="bg-light py-2 border-bottom mb-4">
    <div class="container">
        <ol class="breadcrumb mb-0" style="font-size: 0.85rem;">
            <li class="breadcrumb-item"><a href="<?= $kok_dizin ?>index.php" class="text-decoration-none">Ana Sayfa</a></li>
            <li class="breadcrumb-item active fw-bold" aria-current="page"><?= htmlspecialchars($sayfa_basligi) ?></li>
        </ol>
    </div>
</nav>

<div class="container mb-5 text-dark">
    <div class="row align-items-center mb-4">
        <div class="col-md-6">
            <h1 class="fw-bold h2 mb-1"><?= htmlspecialchars($sayfa_basligi) ?></h1>
            <p class="text-muted mb-0 fw-bold"><?= $toplam_urun ?> ürün listeleniyor</p>
        </div>
        <div class="col-md-6 d-flex justify-content-md-end mt-3 mt-md-0">
            <div class="d-flex align-items-center">
                <span class="text-nowrap me-2 small fw-bold text-muted">Sırala:</span>
                <select class="form-select form-select-sm border-2 fw-bold" style="width: 200px;" onchange="location.href = '<?= $sort_base_url ?>sort=' + this.value;">
    <option value="random" <?= $sort == 'random' ? 'selected' : '' ?>>Karışık Liste</option>
    <option value="newest" <?= $sort == 'newest' ? 'selected' : '' ?>>En Yeniler</option>
    <option value="price_low" <?= $sort == 'price_low' ? 'selected' : '' ?>>Fiyat (Artan)</option>
    <option value="price_high" <?= $sort == 'price_high' ? 'selected' : '' ?>>Fiyat (Azalan)</option>
</select>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <?php if (count($urunler) > 0): ?>
            <?php foreach ($urunler as $urun): ?>
                <div class="col-6 col-md-4 col-lg-3">
                    <div class="card h-100 border-0 shadow-sm product-card transition rounded-4 overflow-hidden position-relative">
                        
                        <?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: 40px; height: 25px; z-index: 5;">
                                <img src="<?= $kok_dizin ?><?= htmlspecialchars($urun['brand_logo']) ?>" class="img-fluid" style="max-height: 100%; max-width: 100%; object-fit: contain;">
                            </div>
                        <?php elseif(!empty($urun['brand_name'])): ?>
                            <div class="position-absolute top-0 end-0 m-2 bg-white text-dark rounded shadow-sm px-2 py-1 fw-bold text-uppercase" style="font-size: 0.6rem; z-index: 5;">
                                <?= htmlspecialchars($urun['brand_name']) ?>
                            </div>
                        <?php endif; ?>

                        <div class="position-relative overflow-hidden bg-light p-2 text-center">
    <a href="urun/<?= $urun['slug'] ?>">
        <img src="<?= htmlspecialchars($urun['main_image']) ?>" 
             class="card-img-top p-2" alt="<?= htmlspecialchars($urun['name']) ?>" 
             style="height: 200px; object-fit: contain;">
    </a>
    
    <div class="position-absolute top-0 start-0 m-2 d-flex flex-column gap-1 align-items-start" style="z-index: 2;">
        <?php if ($urun['discount_price'] > 0): ?>
            <span class="badge bg-danger shadow-sm px-2 py-1" style="font-size:0.7rem;">
                -%<?= round((($urun['price'] - $urun['discount_price']) / $urun['price']) * 100) ?> İndirim
            </span>
        <?php endif; ?>
        
        <?php if ($urun['is_free_shipping'] == 1): ?>
            <span class="badge bg-success shadow-sm px-2 py-1" style="font-size:0.7rem;">
                <i class="bi bi-truck me-1"></i>Kargo Bedava
            </span>
        <?php endif; ?>
    </div>

    <?php if ($urun['type'] == 'subscription' || $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-box-seam me-1"></i>Deneme Paketi
        </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: 35px; overflow: hidden; font-size: 0.85rem; line-height: 1.2;">
                                <a href="<?= $kok_dizin ?>urun/<?= $urun['slug'] ?>" class="text-dark text-decoration-none" title="<?= htmlspecialchars($urun['name']) ?>">
                                    <?= htmlspecialchars($urun['name']) ?>
                                </a>
                            </h5>
                            
                            <?php if($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($urun['exam_publication_date']) ?: 'Tarih Yok' ?>
                                    </div>
                                    <div class="small fw-bold" style="font-size: 0.65rem;">
                                        <?php if($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 ($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($urun['price'], 2, ',', '.') ?> ₺</span>
                                        <span class="text-danger fw-bold fs-6"><?= number_format($urun['discount_price'], 2, ',', '.') ?> ₺</span>
                                    </div>
                                <?php else: ?>
                                    <div class="text-primary fw-bold fs-6"><?= number_format($urun['price'], 2, ',', '.') ?> ₺</div>
                                <?php endif; ?>

                                <div class="d-grid mt-3">
                                    <button class="btn btn-outline-primary btn-sm fw-bold rounded-pill shadow-sm sepete-ekle-btn" data-id="<?= $urun['id'] ?>">
                                        <i class="bi bi-cart-plus me-1"></i> Sepete Ekle
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
           <?php endforeach; ?>
            
            <?php if ($toplam_sayfa > 1): ?>
            <div class="col-12 mt-5">
                <nav>
                    <ul class="pagination justify-content-center shadow-sm">
                        <li class="page-item <?= ($sayfa <= 1) ? 'disabled' : '' ?>">
                            <a class="page-link border-2 fw-bold" href="<?= $sort_base_url ?>sort=<?= $sort ?>&sayfa=<?= $sayfa - 1 ?>">Geri</a>
                        </li>
                        <?php for ($i = 1; $i <= $toplam_sayfa; $i++): ?>
                            <li class="page-item <?= ($sayfa == $i) ? 'active' : '' ?>">
                                <a class="page-link border-2 fw-bold" href="<?= $sort_base_url ?>sort=<?= $sort ?>&sayfa=<?= $i ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>
                        <li class="page-item <?= ($sayfa >= $toplam_sayfa) ? 'disabled' : '' ?>">
                            <a class="page-link border-2 fw-bold" href="<?= $sort_base_url ?>sort=<?= $sort ?>&sayfa=<?= $sayfa + 1 ?>">İleri</a>
                        </li>
                    </ul>
                </nav>
            </div>
            <?php endif; ?>
            <?php else: ?>
            <div class="col-12 text-center py-5 bg-white rounded-4 shadow-sm border">
                <i class="bi bi-search text-muted mb-3" style="font-size: 4rem;"></i>
                <h4 class="fw-bold">Bu kriterlere uygun ürün bulunamadı.</h4>
                <p class="text-muted">Aramanızı değiştirebilir veya diğer kategorilerimize göz atabilirsiniz.</p>
                <a href="<?= $kok_dizin ?>index.php" class="btn btn-primary px-5 rounded-pill fw-bold mt-2">Alışverişe Başla</a>
            </div>
        <?php endif; ?>
    </div>

    <?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">Bu kategori hakkında merak edilenler</p>
            </div>
            
            <div class="accordion accordion-flush" id="accordionSssCategory">
                <?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="#accordionSssCategory">
                            <div class="accordion-body text-muted lh-lg">
                                <?= nl2br(htmlspecialchars($soru['answer'])) ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </section>
    </div>
    <?php endif; ?>

</div>

<style>
.product-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.1) !important; }
.transition { transition: all 0.3s ease; }
.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); } }
</style>

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