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

$kok_dizin = "/magaza/";

if (!isset($_GET['slug']) || empty($_GET['slug'])) {
    header("Location: " . $kok_dizin . "markalar.php");
    exit;
}
$marka_slug = trim($_GET['slug']);

// Markayı Bul
$marka_stmt = $db->prepare("SELECT * FROM brands WHERE slug = ? AND status = 1");
$marka_stmt->execute([$marka_slug]);
$aktif_marka = $marka_stmt->fetch(PDO::FETCH_ASSOC);

if (!$aktif_marka) {
    header("Location: " . $kok_dizin . "markalar.php");
    exit;
}

$page_title = $aktif_marka['name'] . " Ürünleri ve Denemeleri | SINAVKOCU Mağaza";
require_once 'header.php';

// Sayfalama (Pagination) Ayarları
$sayfada = 12; // Bir sayfada gösterilecek ürün sayısı
$sorgu = $db->prepare("SELECT COUNT(id) FROM products WHERE status = 1 AND brand_id = ?");
$sorgu->execute([$aktif_marka['id']]);
$toplam_icerik = $sorgu->fetchColumn();
$toplam_sayfa = ceil($toplam_icerik / $sayfada);
$sayfa = isset($_GET['sayfa']) ? (int) $_GET['sayfa'] : 1;
if($sayfa < 1) $sayfa = 1;
if($sayfa > $toplam_sayfa && $toplam_sayfa > 0) $sayfa = $toplam_sayfa;
$limit = ($sayfa - 1) * $sayfada;

// Markaya ait ürünleri çek
$urunler_stmt = $db->prepare("
    SELECT p.id, p.name, p.slug, p.price, p.discount_price, p.type, p.exam_publication_date, p.is_free_shipping,
    b.logo as brand_logo, b.name as brand_name,
    (SELECT name FROM categories WHERE id = p.category_id) as cat_name,
    (SELECT GROUP_CONCAT(c3.name SEPARATOR ', ') FROM product_categories pc3 JOIN categories c3 ON pc3.category_id = c3.id WHERE pc3.product_id = p.id) as sub_categories,
    COALESCE(
        (SELECT image_path FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1),
        b.default_cover,
        'assets/img/no-image.jpg'
    ) as main_image
    FROM products p 
    LEFT JOIN brands b ON p.brand_id = b.id
    WHERE p.status = 1 AND p.brand_id = :brand_id
    ORDER BY p.id DESC LIMIT :limit, :sayfada
");
$urunler_stmt->bindValue(':brand_id', $aktif_marka['id'], PDO::PARAM_INT);
$urunler_stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
$urunler_stmt->bindValue(':sayfada', (int) $sayfada, PDO::PARAM_INT);
$urunler_stmt->execute();
$urun_listesi = $urunler_stmt->fetchAll(PDO::FETCH_ASSOC);

$marka_logo = !empty($aktif_marka['logo']) ? $aktif_marka['logo'] : 'assets/img/no-image.jpg';
?>

<main class="container py-4 text-dark">
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb mb-0">
            <li class="breadcrumb-item"><a href="<?= $kok_dizin ?>index.php" class="text-decoration-none"><i class="bi bi-house-door"></i> Ana Sayfa</a></li>
            <li class="breadcrumb-item"><a href="<?= $kok_dizin ?>markalar.php" class="text-decoration-none">Markalar</a></li>
            <li class="breadcrumb-item active" aria-current="page"><?= htmlspecialchars($aktif_marka['name']) ?></li>
        </ol>
    </nav>

    <div class="card border-0 shadow-sm rounded-4 mb-5 bg-white overflow-hidden">
        <div class="card-body p-4 d-flex align-items-center">
            <div class="bg-light rounded p-2 me-4 border d-flex align-items-center justify-content-center" style="width: 120px; height: 90px;">
                <img src="<?= $kok_dizin ?><?= htmlspecialchars($marka_logo) ?>" alt="<?= htmlspecialchars($aktif_marka['name']) ?>" class="img-fluid" style="max-height: 100%; object-fit: contain;">
            </div>
            <div>
                <h1 class="h2 fw-bold text-dark mb-1"><?= htmlspecialchars($aktif_marka['name']) ?></h1>
                <p class="text-muted mb-0"><i class="bi bi-box-seam me-1"></i> Bu markaya ait toplam <strong><?= $toplam_icerik ?></strong> ürün listeleniyor.</p>
            </div>
        </div>
    </div>

    <?php if(count($urun_listesi) > 0): ?>
        <div class="row row-cols-2 row-cols-md-3 row-cols-lg-4 g-3 mb-5">
            <?php foreach($urun_listesi as $urun): ?>
                <div class="col">
                    <article class="card h-100 product-card shadow-sm border-0 position-relative transition rounded-4 overflow-hidden">
                        
                        <?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 endif; ?>

                        <div class="position-relative overflow-hidden bg-light p-2 text-center">
                            <a href="<?= $kok_dizin ?>urun/<?= $urun['slug'] ?>">
                                <img src="<?= $kok_dizin ?><?= 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) ?> İndirimli
                                    </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">
                            <?php 
                                $kategori_isimleri = !empty($urun['sub_categories']) ? $urun['sub_categories'] : ($urun['cat_name'] ?? '');
                                if($kategori_isimleri): 
                            ?>
                                <small class="text-muted fw-bold text-uppercase text-truncate d-block mb-1" style="font-size: 0.60rem; letter-spacing: 0.5px;" title="<?= htmlspecialchars($kategori_isimleri) ?>">
                                    <?= htmlspecialchars($kategori_isimleri) ?>
                                </small>
                            <?php endif; ?>

                            <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-center 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>
                            <?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'], 1, ',', '.') ?> ₺</div>
                                <?php endif; ?>
                                
                                <button class="btn btn-outline-primary w-100 btn-sm sepete-ekle-btn fw-bold mt-2" data-id="<?= $urun['id'] ?>">
                                    <i class="bi bi-cart-plus"></i> Sepete Ekle
                                </button>
                            </div>
                        </div>
                    </article>
                </div>
            <?php endforeach; ?>
        </div>

        <?php if($toplam_sayfa > 1): ?>
        <nav class="mt-4 mb-5">
            <ul class="pagination justify-content-center">
                <?php for($i = 1; $i <= $toplam_sayfa; $i++): ?>
                    <li class="page-item <?= ($i == $sayfa) ? 'active' : '' ?>">
                        <a class="page-link shadow-sm" href="?slug=<?= $marka_slug ?>&sayfa=<?= $i ?>"><?= $i ?></a>
                    </li>
                <?php endfor; ?>
            </ul>
        </nav>
        <?php endif; ?>

    <?php else: ?>
        <div class="alert alert-secondary text-center py-5 shadow-sm border-0 rounded-4">
            <i class="bi bi-box-seam fs-1 text-muted d-block mb-3"></i>
            <h5 class="fw-bold">Bu markaya ait ürün bulunamadı.</h5>
        </div>
    <?php endif; ?>
</main>

<style>
.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; }
</style>

<script>
// Sepete ekleme butonu JS'niz (Diğer sayfalardaki ile aynı)
document.querySelectorAll('.sepete-ekle-btn').forEach(btn => {
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        const productId = this.getAttribute('data-id');
        const originalHTML = this.innerHTML;
        this.disabled = true;
        this.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>...';

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

        fetch('<?= $kok_dizin ?>sepet-islem.php', { method: 'POST', body: formData })
        .then(res => res.json())
        .then(data => {
            this.innerHTML = originalHTML;
            this.disabled = false;
            if(data.status === 'success') {
                if(document.getElementById('cartBadge')) document.getElementById('cartBadge').innerText = data.total_items;
                if(typeof Swal !== 'undefined') {
                    Swal.fire({icon: 'success', title: 'Eklendi', text: data.message, timer: 1500, showConfirmButton: false});
                } else { alert(data.message); }
            } else {
                if(typeof Swal !== 'undefined') Swal.fire('Hata!', data.message, 'warning'); else alert(data.message);
            }
        }).catch(err => { this.innerHTML = originalHTML; this.disabled = false; });
    });
});
</script>

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