<?php
/**
 * Evrensel Header (Tüm sayfalarda hatasız çalışır)
 */

// Dosya yollarını sabitlemek için __DIR__ kullanıyoruz
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';

// YENİ: En Üstteki Duyuru Bandını (Top Bar) Çek
$header_marquee = $db->query("SELECT content FROM marquees WHERE page_type = 'header' AND status = 1")->fetchColumn();

// Menüde göstermek için aktif kategorileri çek
$menuKategoriler = $db->query("SELECT * FROM categories WHERE status = 1 AND parent_id IS NULL ORDER BY name ASC")->fetchAll();

// Sepetteki ürün sayısını bul (Gerçek zamanlı)
$sepet_sayisi = 0;
$cart_token = $_COOKIE['cart_token'] ?? '';
if ($cart_token) {
    $c_stmt = $db->prepare("SELECT SUM(quantity) FROM cart_items ci JOIN carts c ON ci.cart_id = c.id WHERE c.session_token = ?");
    $c_stmt->execute([$cart_token]);
    $sepet_sayisi = $c_stmt->fetchColumn() ?: 0;
}

// Admin Mesaj Bildirim Sayısı (Sadece admin girişi varsa çalışır)
$yeni_mesaj_sayisi = 0;
if(isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin') {
    $mesaj_stmt = $db->query("SELECT COUNT(id) FROM contact_messages WHERE status = 'new'");
    $yeni_mesaj_sayisi = $mesaj_stmt->fetchColumn() ?: 0;
}

// BİLDİRİM SİSTEMİ (Kullanıcı giriş yapmışsa)
$bildirim_sayisi = 0;
$son_bildirimler = [];
if(isset($_SESSION['user_id'])) {
    $bildirim_sayisi = okunmamisBildirimSayisi($_SESSION['user_id']);
    
    // Açılır menü (dropdown) için son 5 bildirimi çek
    $bildirim_stmt = $db->prepare("SELECT * FROM user_notifications WHERE user_id = ? ORDER BY id DESC LIMIT 5");
    $bildirim_stmt->execute([$_SESSION['user_id']]);
    $son_bildirimler = $bildirim_stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Proje klasör adını bir değişkene atayalım (Evrensellik için kritik)
$site_kok_dizin = "/magaza/"; 
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= isset($page_title) ? htmlspecialchars($page_title) : "Sınav Koçu | Türkiye'nin Eğitim Mağazası" ?></title>
    
    <base href="/magaza/">
    
    <?php
    // --- GÜNCELLENEN: SOSYAL MEDYA PAYLAŞIM ÖNİZLEMELERİ (OPEN GRAPH) ---
    $og_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    
    if(isset($urun) && isset($ana_gorsel)) {
        // 1. DURUM: Ürün Detay Sayfasındaysak
        $og_image_path = ltrim($ana_gorsel, '/');
        $og_image = "https://" . $_SERVER['HTTP_HOST'] . $site_kok_dizin . $og_image_path;
        $og_title = htmlspecialchars($urun['name']);
        $og_desc = htmlspecialchars(mb_substr(strip_tags($urun['description'] ?? $urun['name']), 0, 120)) . "...";
        $og_type = "product";
    } else {
        // 2. DURUM: Takvim, Kategori, Anasayfa vb. Genel Sayfalardaysak
        $og_title = isset($page_title) ? htmlspecialchars($page_title) : "Sınav Koçu | Türkiye'nin Eğitim Mağazası";
        $og_desc = isset($meta_description) ? htmlspecialchars($meta_description) : "Türkiye'nin eğitim mağazası. YKS, LGS denemeleri ve fazlası.";
        
        // İlgili sayfada ($page_og_image) özel bir görsel belirtilmişse onu kullan, yoksa logonuzu/varsayılan görseli kullan
        // NOT: assets/img/logo.jpg kısmını kendi varsayılan sitenizin logosu veya görselinin adıyla değiştirmeyi unutmayın!
        $varsayilan_gorsel = "https://" . $_SERVER['HTTP_HOST'] . $site_kok_dizin . "uploads/sinavkocu-magaza-kitap-deneme-teknoloji.png"; 
        $og_image = isset($page_og_image) ? $page_og_image : $varsayilan_gorsel; 
        $og_type = "website";
    }

    // Etiketleri HTML'e Yazdır
    echo "<meta property=\"og:title\" content=\"{$og_title}\">\n";
    echo "    <meta property=\"og:description\" content=\"{$og_desc}\">\n";
    echo "    <meta property=\"og:image\" content=\"{$og_image}\">\n";
    echo "    <meta property=\"og:url\" content=\"{$og_url}\">\n";
    echo "    <meta property=\"og:type\" content=\"{$og_type}\">\n";
    
    // Twitter Kartı Etiketleri
    echo "    <meta name=\"twitter:card\" content=\"summary_large_image\">\n";
    echo "    <meta name=\"twitter:title\" content=\"{$og_title}\">\n";
    echo "    <meta name=\"twitter:description\" content=\"{$og_desc}\">\n";
    echo "    <meta name=\"twitter:image\" content=\"{$og_image}\">\n";
    // ----------------------------------------------------------------------
    ?>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <style>
        .navbar-brand { font-weight: 800; letter-spacing: -1px; }
        .product-card { transition: transform 0.2s; }
        .product-card:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.1); }
        .dropdown-menu { border: none; box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15); border-radius: 10px; }
        .dropdown-item { padding: 8px 20px; font-weight: 500; }
        .cursor-pointer { cursor: pointer; }
        /* Admin Menüsü için Özel Kapsayıcı */
        .admin-dropdown .dropdown-menu { min-width: 250px; }
        
        /* BİLDİRİM MENÜSÜ TASARIMI */
        .notification-dropdown { width: 320px; padding: 0; overflow: hidden; }
        .notification-item { border-bottom: 1px solid #f1f1f1; padding: 12px 15px; white-space: normal; transition: background 0.2s; display: block; text-decoration: none; color: inherit; }
        .notification-item:last-child { border-bottom: none; }
        .notification-item:hover { background-color: #f8f9fa; }
        .notification-item.unread { background-color: #f0f7ff; }
        .notification-icon { width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; border-radius: 50%; flex-shrink: 0; }
        .notification-text { font-size: 0.85rem; line-height: 1.3; }
        .notification-time { font-size: 0.7rem; color: #888; margin-top: 4px; display: block; }
    </style>
</head>
<body class="bg-light">

<?php if($header_marquee): ?>
<div class="bg-dark text-white text-center py-2 fw-bold" style="font-size: 15px; letter-spacing: 0.5px;">
    <?= $header_marquee ?>
</div>
<?php endif; ?>

<nav class="navbar navbar-expand-lg navbar-light bg-white shadow-sm sticky-top py-3">
    <div class="container">
        <a class="navbar-brand text-primary fs-3" href="<?= $site_kok_dizin ?>index.php">SINAVKOCU<span class="text-dark"> Mağaza</span></a>
        
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mainNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        
        <div class="collapse navbar-collapse" id="mainNav">
            <form action="<?= $site_kok_dizin ?>urun-kategori.php" method="GET" class="d-flex mx-auto w-50 my-2 my-lg-0">
                <div class="input-group">
                    <input class="form-control border-primary shadow-none" type="search" name="q" placeholder="Kitap, deneme, yayınevi ara..." required>
                    <button class="btn btn-primary" type="submit"><i class="bi bi-search"></i></button>
                </div>
            </form>

            <ul class="navbar-nav ms-auto align-items-center">
                
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle fw-bold text-dark" href="#" data-bs-toggle="dropdown">Kategoriler</a>
                    <ul class="dropdown-menu">
                        <?php foreach($menuKategoriler as $kat): ?>
                            <li><a class="dropdown-item" href="<?= $site_kok_dizin ?>kategori/<?= $kat['slug'] ?>"><?= htmlspecialchars($kat['name']) ?></a></li>
                        <?php endforeach; ?>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item text-danger fw-bold" href="<?= $site_kok_dizin ?>indirimli-urunler.php">İndirimli Ürünler</a></li>
                         <li><a class="dropdown-item text-green fw-bold" href="<?= $site_kok_dizin ?>deneme-sinav-takvimi.php">Deneme Takvimi</a></li>
                         <li><a class="dropdown-item text-green fw-bold" href="<?= $site_kok_dizin ?>blog.php">Blog</a></li>
                    </ul>
                </li>

                <?php if(isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin'): ?>
                <li class="nav-item dropdown admin-dropdown mx-2">
                    <a class="nav-link dropdown-toggle fw-bold text-danger bg-light rounded px-3" href="#" data-bs-toggle="dropdown">
                        <i class="bi bi-shield-lock-fill me-1"></i> Yönetim Paneli
                        <?php if($yeni_mesaj_sayisi > 0): ?>
                            <span class="position-absolute top-0 start-100 translate-middle p-1 bg-danger border border-light rounded-circle"></span>
                        <?php endif; ?>
                    </a>
                    <ul class="dropdown-menu shadow-lg border-0 mt-2">
                        <li><h6 class="dropdown-header text-uppercase text-muted fw-bold">Raporlar & Finans</h6></li>
                        <li><a class="dropdown-item" href="<?= $site_kok_dizin ?>admin/finans/index.php"><i class="bi bi-wallet2 text-success me-2"></i>Finans Dashboard</a></li>
                        <li><a class="dropdown-item" href="<?= $site_kok_dizin ?>admin/finans/dekontlar.php"><i class="bi bi-bank text-warning me-2"></i>Havale & Dekontlar</a></li>
                        <li><a class="dropdown-item" href="<?= $site_kok_dizin ?>admin/finans/faturalar.php"><i class="bi bi-file-earmark-pdf text-info me-2"></i>E-Fatura Merkezi</a></li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <li><h6 class="dropdown-header text-uppercase text-muted fw-bold">Operasyon Merkezi</h6></li>
                        <li><a class="dropdown-item" href="<?= $site_kok_dizin ?>admin/siparisler/index.php"><i class="bi bi-box-seam text-primary me-2"></i>Tüm Siparişler</a></li>
                        <li><a class="dropdown-item" href="<?= $site_kok_dizin ?>admin/abonelikler/teslimat_merkezi.php"><i class="bi bi-truck text-dark me-2"></i>Abonelik Lojistiği</a></li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <li><h6 class="dropdown-header text-uppercase text-muted fw-bold">İçerik & Mağaza</h6></li>
                        <li><a class="dropdown-item" href="<?= $site_kok_dizin ?>admin/sayfalar/index.php"><i class="bi bi-file-earmark-richtext text-secondary me-2"></i>Sayfalar (Kurumsal)</a></li>
                        <li><a class="dropdown-item" href="<?= $site_kok_dizin ?>admin/mesajlar/index.php">
                            <i class="bi bi-envelope-paper text-primary me-2"></i>Ziyaretçi Mesajları
                            <?php if($yeni_mesaj_sayisi > 0): ?>
                                <span class="badge bg-danger rounded-pill ms-2"><?= $yeni_mesaj_sayisi ?> Yeni</span>
                            <?php endif; ?>
                        </a></li>
                        <li><hr class="dropdown-divider"></li>
                        
                        <li><a class="dropdown-item fw-bold text-dark" href="<?= $site_kok_dizin ?>admin/ayarlar/index.php"><i class="bi bi-gear-fill me-2"></i>Genel Ayarlar</a></li>
                    </ul>
                </li>
                <?php endif; ?>

                <?php if(isset($_SESSION['user_id'])): ?>
                    
                    <li class="nav-item dropdown ms-lg-2 me-1">
                        <a class="nav-link position-relative text-dark px-2" href="#" data-bs-toggle="dropdown">
                            <i class="bi bi-bell fs-5"></i>
                            <?php if($bildirim_sayisi > 0): ?>
                                <span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger border border-light" style="font-size: 0.6rem; transform: translate(-30%, 30%) !important;">
                                    <?= $bildirim_sayisi > 9 ? '9+' : $bildirim_sayisi ?>
                                </span>
                            <?php endif; ?>
                        </a>
                        
                        <div class="dropdown-menu dropdown-menu-end shadow-lg notification-dropdown mt-2 border border-secondary border-opacity-10">
                            <div class="d-flex justify-content-between align-items-center bg-light px-3 py-2 border-bottom">
                                <h6 class="mb-0 fw-bold text-dark">Bildirimler</h6>
                                <?php if($bildirim_sayisi > 0): ?>
                                    <span class="badge bg-primary rounded-pill"><?= $bildirim_sayisi ?> Yeni</span>
                                <?php endif; ?>
                            </div>
                            
                            <div style="max-height: 300px; overflow-y: auto;">
                                <?php if(count($son_bildirimler) > 0): ?>
                                    <?php foreach($son_bildirimler as $bildirim): ?>
                                        <a href="<?= $site_kok_dizin ?>kullanici/bildirim-oku.php?id=<?= $bildirim['id'] ?>" class="notification-item <?= $bildirim['is_read'] ? '' : 'unread' ?>">
                                            <div class="d-flex align-items-start">
                                                <div class="notification-icon bg-primary bg-opacity-10 text-primary me-3">
                                                    <i class="bi <?= htmlspecialchars($bildirim['icon']) ?> fs-6"></i>
                                                </div>
                                                <div class="w-100">
                                                    <div class="fw-bold text-dark mb-1" style="font-size: 0.9rem;"><?= htmlspecialchars($bildirim['title']) ?></div>
                                                    <div class="notification-text text-muted"><?= htmlspecialchars($bildirim['message']) ?></div>
                                                    <span class="notification-time"><i class="bi bi-clock me-1"></i><?= formatDate($bildirim['created_at'], true) ?></span>
                                                </div>
                                            </div>
                                        </a>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <div class="p-4 text-center text-muted">
                                        <i class="bi bi-bell-slash fs-2 opacity-50 mb-2 d-block"></i>
                                        <p class="mb-0 small">Henüz bildiriminiz yok.</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="bg-light text-center border-top">
                                <a href="<?= $site_kok_dizin ?>kullanici/bildirimler.php" class="btn btn-link btn-sm text-decoration-none w-100 py-2 fw-bold text-primary">Tüm Bildirimleri Gör</a>
                            </div>
                        </div>
                    </li>
                    <li class="nav-item dropdown ms-lg-1">
                        <a class="nav-link dropdown-toggle fw-bold text-primary" href="#" data-bs-toggle="dropdown">
                            <i class="bi bi-person-circle fs-5 me-1"></i> <?= htmlspecialchars($_SESSION['user_name'] ?? 'Profilim') ?>
                        </a>
                        <ul class="dropdown-menu dropdown-menu-end shadow-sm mt-2 border border-secondary border-opacity-10">
                            <li><h6 class="dropdown-header text-muted">Hesabım</h6></li>
                            <li><a class="dropdown-item" href="<?= $site_kok_dizin ?>kullanici/index.php"><i class="bi bi-person me-2 text-muted"></i>Hesap Özeti</a></li>
                            <li><a class="dropdown-item" href="<?= $site_kok_dizin ?>kullanici/siparisler.php"><i class="bi bi-bag me-2 text-muted"></i>Siparişlerim</a></li>
                            <li><a class="dropdown-item fw-bold text-success" href="<?= $site_kok_dizin ?>kullanici/denemepaketim.php"><i class="bi bi-calendar-check me-2"></i>Deneme Paketlerim</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="<?= $site_kok_dizin ?>cikis.php"><i class="bi bi-box-arrow-right me-2"></i>Güvenli Çıkış</a></li>
                        </ul>
                    </li>
                <?php else: ?>
                    <li class="nav-item ms-lg-3">
                        <a class="nav-link fw-bold text-dark" href="<?= $site_kok_dizin ?>giris.php"><i class="bi bi-box-arrow-in-right me-1"></i> Giriş Yap</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link fw-bold text-primary" href="<?= $site_kok_dizin ?>kayit.php">Kayıt Ol</a>
                    </li>
                <?php endif; ?>

                <li class="nav-item ms-lg-2">
                    <a class="btn btn-outline-primary position-relative fw-bold px-3 ms-2 rounded-pill" href="<?= $site_kok_dizin ?>sepet.php">
                        <i class="bi bi-cart3"></i> Sepet
                        <span id="cartBadge" class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger shadow-sm border border-light">
                            <?= $sepet_sayisi ?>
                        </span>
                    </a>
                </li>
            </ul>
        </div>
    </div>
</nav>