<?php
/**
 * SMM Paket Satış Scripti - Header
 * @version 1.0.4
 */

if (!defined('SITE_VERSION')) {
    require_once __DIR__ . '/config.php';
}

// AJAX isteği kontrolü
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    
    // Marquee kapatma
    if (isset($_POST['close_marquee'])) {
        $_SESSION['marquee_closed'] = true;
        header('Content-Type: application/json');
        echo json_encode(['success' => true]);
        exit;
    }
    
    if (isset($_POST['notification_action'])) {
        header('Content-Type: application/json');
        
        try {
            if (!isset($_SESSION['notification_session'])) {
                $_SESSION['notification_session'] = bin2hex(random_bytes(16));
            }
            $sessionId = $_SESSION['notification_session'];
            $userId = isLoggedIn() ? ($_SESSION['user_id'] ?? null) : null;
            
            if ($_POST['notification_action'] === 'mark_read' && isset($_POST['notification_id'])) {
                $notificationId = (int)$_POST['notification_id'];
                
                if ($userId) {
                    $checkStmt = $db->prepare("SELECT id FROM notification_reads WHERE notification_id = ? AND user_id = ?");
                    $checkStmt->execute([$notificationId, $userId]);
                } else {
                    $checkStmt = $db->prepare("SELECT id FROM notification_reads WHERE notification_id = ? AND session_id = ?");
                    $checkStmt->execute([$notificationId, $sessionId]);
                }
                
                if (!$checkStmt->fetch()) {
                    $insertStmt = $db->prepare("INSERT INTO notification_reads (notification_id, user_id, session_id, read_at) VALUES (?, ?, ?, NOW())");
                    $insertStmt->execute([$notificationId, $userId, $sessionId]);
                }
                
                echo json_encode(['success' => true]);
                exit;
            }
            
            if ($_POST['notification_action'] === 'mark_all_read') {
                if (isLoggedIn()) {
                    $targetCondition = "(target = 'all' OR target = 'users')";
                } else {
                    $targetCondition = "(target = 'all' OR target = 'guests')";
                }
                
                $stmt = $db->query("SELECT id FROM notifications WHERE is_active = 1 AND {$targetCondition}");
                $notificationIds = $stmt->fetchAll(PDO::FETCH_COLUMN);
                
                foreach ($notificationIds as $notificationId) {
                    if ($userId) {
                        $checkStmt = $db->prepare("SELECT id FROM notification_reads WHERE notification_id = ? AND user_id = ?");
                        $checkStmt->execute([$notificationId, $userId]);
                    } else {
                        $checkStmt = $db->prepare("SELECT id FROM notification_reads WHERE notification_id = ? AND session_id = ?");
                        $checkStmt->execute([$notificationId, $sessionId]);
                    }
                    
                    if (!$checkStmt->fetch()) {
                        $insertStmt = $db->prepare("INSERT INTO notification_reads (notification_id, user_id, session_id, read_at) VALUES (?, ?, ?, NOW())");
                        $insertStmt->execute([$notificationId, $userId, $sessionId]);
                    }
                }
                
                echo json_encode(['success' => true]);
                exit;
            }
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'error' => 'Database error']);
            exit;
        }
        
        echo json_encode(['success' => false]);
        exit;
    }
    
    // Fake bildirim verisi çek
    if (isset($_POST['get_fake_notification'])) {
        header('Content-Type: application/json');
        
        try {
            $nameStmt = $db->query("SELECT name FROM fake_notification_names WHERE is_active = 1 ORDER BY RAND() LIMIT 1");
            $name = $nameStmt->fetchColumn() ?: 'Müşteri';
            
            $cityStmt = $db->query("SELECT city FROM fake_notification_cities WHERE is_active = 1 ORDER BY RAND() LIMIT 1");
            $city = $cityStmt->fetchColumn() ?: 'Türkiye';
            
            $itemStmt = $db->query("SELECT * FROM fake_notification_items WHERE is_active = 1 ORDER BY RAND() LIMIT 1");
            $item = $itemStmt->fetch(PDO::FETCH_ASSOC);
            
            if ($item) {
                $quantity = rand($item['quantity_min'], $item['quantity_max']);
                $quantity = round($quantity / 500) * 500;
                if ($quantity < $item['quantity_min']) $quantity = $item['quantity_min'];
                
                echo json_encode([
                    'success' => true,
                    'data' => [
                        'name' => $name,
                        'city' => $city,
                        'platform' => $item['platform'],
                        'platform_icon' => $item['platform_icon'],
                        'platform_color' => $item['platform_color'],
                        'package_name' => $item['package_name'],
                        'quantity' => number_format($quantity, 0, ',', '.'),
                        'time_ago' => rand(1, 15) . ' dakika önce'
                    ]
                ]);
            } else {
                echo json_encode(['success' => false, 'error' => 'No items']);
            }
        } catch (PDOException $e) {
            echo json_encode(['success' => false, 'error' => 'Database error']);
        }
        exit;
    }
}

if ($settings->get('maintenance_mode') && !isAdmin()) {
    include __DIR__ . '/maintenance.php';
    exit;
}

$pageTitle = isset($pageTitle) ? $pageTitle . ' - ' . $settings->get('site_name') : $settings->get('site_title');
$pageDescription = isset($pageDescription) ? $pageDescription : $settings->get('site_description');

$menuItems = [
    ['url' => SITE_URL, 'title' => 'Ana Sayfa', 'icon' => 'fas fa-home'],
    ['url' => SITE_URL . '/#packages', 'title' => 'Paketler', 'icon' => 'fas fa-box'],
    ['url' => SITE_URL . '/siparis-sorgula.php', 'title' => 'Sipariş Sorgula', 'icon' => 'fas fa-search'],
    ['url' => SITE_URL . '/iletisim.php', 'title' => 'İletişim', 'icon' => 'fas fa-envelope']
];

$currentPage = basename($_SERVER['PHP_SELF']);

// Bildirimleri çek
$notifications = [];
$unreadNotificationCount = 0;
$readIds = [];

try {
    if (!isset($_SESSION['notification_session'])) {
        $_SESSION['notification_session'] = bin2hex(random_bytes(16));
    }
    $sessionId = $_SESSION['notification_session'];
    $userId = isLoggedIn() ? ($_SESSION['user_id'] ?? null) : null;
    
    if (isLoggedIn()) {
        $targetCondition = "(target = 'all' OR target = 'users')";
    } else {
        $targetCondition = "(target = 'all' OR target = 'guests')";
    }
    
    $stmt = $db->query("
        SELECT * FROM notifications 
        WHERE is_active = 1 
        AND {$targetCondition}
        AND (start_date IS NULL OR start_date <= NOW())
        AND (end_date IS NULL OR end_date >= NOW())
        ORDER BY sort_order ASC, created_at DESC
        LIMIT 10
    ");
    $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (!empty($notifications)) {
        $notificationIds = array_column($notifications, 'id');
        $placeholders = implode(',', array_fill(0, count($notificationIds), '?'));
        
        if ($userId) {
            $readStmt = $db->prepare("SELECT notification_id FROM notification_reads WHERE notification_id IN ({$placeholders}) AND user_id = ?");
            $readStmt->execute(array_merge($notificationIds, [$userId]));
        } else {
            $readStmt = $db->prepare("SELECT notification_id FROM notification_reads WHERE notification_id IN ({$placeholders}) AND session_id = ?");
            $readStmt->execute(array_merge($notificationIds, [$sessionId]));
        }
        
        $readIds = $readStmt->fetchAll(PDO::FETCH_COLUMN);
        $unreadNotificationCount = count(array_diff($notificationIds, $readIds));
    }
} catch (PDOException $e) {
    $notifications = [];
}

$openTicketCount = 0;
if (isLoggedIn()) {
    try {
        $ticketStmt = $db->prepare("SELECT COUNT(*) FROM support_tickets WHERE user_id = ? AND status IN ('open', 'answered')");
        $ticketStmt->execute([$_SESSION['user_id']]);
        $openTicketCount = $ticketStmt->fetchColumn();
    } catch (PDOException $e) {}
}

// Fake bildirim ayarlarını çek
$fakeNotifSettings = [
    'is_active' => 0,
    'interval_min' => 5,
    'interval_max' => 15,
    'display_duration' => 5,
    'position' => 'bottom-left',
    'show_on_mobile' => 1
];

try {
    $fakeStmt = $db->query("SELECT * FROM fake_notification_settings WHERE id = 1");
    $fakeData = $fakeStmt->fetch(PDO::FETCH_ASSOC);
    if ($fakeData) {
        $fakeNotifSettings = $fakeData;
    }
} catch (PDOException $e) {}

// Kayan Yazı (Marquee) Kampanyaları
$marqueeItems = [];
$marqueeSettings = [
    'is_active' => 0,
    'bg_color' => '#ef4444',
    'text_color' => '#ffffff',
    'speed' => 30,
    'show_on_mobile' => 1,
    'is_closable' => 1
];

try {
    // Ayarları çek
    $settingsStmt = $db->query("SELECT * FROM marquee_settings WHERE id = 1");
    $mSettings = $settingsStmt->fetch(PDO::FETCH_ASSOC);
    if ($mSettings) {
        $marqueeSettings = $mSettings;
    }
    
    // Aktif kampanyaları çek
    if ($marqueeSettings['is_active']) {
        $itemsStmt = $db->query("
            SELECT * FROM marquee_items 
            WHERE is_active = 1 
            AND (start_date IS NULL OR start_date <= NOW())
            AND (end_date IS NULL OR end_date >= NOW())
            ORDER BY sort_order ASC, id ASC
        ");
        $marqueeItems = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (PDOException $e) {
    $marqueeItems = [];
}

// Marquee kapatıldı mı kontrol et
$marqueeClosed = isset($_SESSION['marquee_closed']) && $_SESSION['marquee_closed'] === true;
if ($marqueeClosed && $marqueeSettings['is_closable']) {
    $marqueeItems = [];
}

// Header rengi
$headerBgColor = $theme['header_bg_color'] ?? '#0f172a';
$headerBgRgb = hexToRgb($headerBgColor);

// Marquee gösterilecek mi?
$showMarquee = $marqueeSettings['is_active'] && !empty($marqueeItems) && !$marqueeClosed;
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo clean($pageTitle); ?></title>
    <meta name="description" content="<?php echo clean($pageDescription); ?>">
    
    <?php if ($settings->getFaviconUrl()): ?>
    <link rel="icon" href="<?php echo clean($settings->getFaviconUrl()); ?>">
    <?php endif; ?>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://unpkg.com/aos@2.3.1/dist/aos.css" rel="stylesheet">
    
    <style>
    :root {
        --primary: <?php echo $theme['primary_color']; ?>;
        --secondary: <?php echo $theme['secondary_color']; ?>;
        --accent: <?php echo $theme['accent_color'] ?? '#22d3ee'; ?>;
        --bg: <?php echo $theme['background_color'] ?? '#0f172a'; ?>;
        --text: <?php echo $theme['text_color'] ?? '#f8fafc'; ?>;
        --header-bg: <?php echo $headerBgColor; ?>;
        --header-bg-rgb: <?php echo $headerBgRgb; ?>;
        --primary-rgb: <?php echo hexToRgb($theme['primary_color']); ?>;
        --secondary-rgb: <?php echo hexToRgb($theme['secondary_color']); ?>;
        --gradient: linear-gradient(135deg, var(--primary), var(--secondary));
        --shadow: 0 10px 40px rgba(var(--primary-rgb), 0.3);
        --radius: 12px;
    }

    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: 'Inter', sans-serif; background: var(--bg); color: var(--text); line-height: 1.6; }
    a { text-decoration: none; color: inherit; transition: all 0.3s ease; }
    .gradient-text { background: var(--gradient); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; }

    #preloader { position: fixed; inset: 0; background: var(--bg); display: flex; align-items: center; justify-content: center; z-index: 99999; transition: opacity 0.5s; }
    #preloader.fade-out { opacity: 0; pointer-events: none; }
    .spinner { width: 50px; height: 50px; border: 3px solid rgba(var(--primary-rgb), 0.2); border-top-color: var(--primary); border-radius: 50%; animation: spin 1s linear infinite; }
    @keyframes spin { to { transform: rotate(360deg); } }

    /* Kayan Yazı (Marquee) */
    .marquee-bar {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        z-index: 10001;
        height: 36px;
        overflow: hidden;
        display: flex;
        align-items: center;
    }
    
    .marquee-bar.hiding {
        animation: slideUpMarquee 0.3s ease forwards;
    }
    
    @keyframes slideUpMarquee {
        to { transform: translateY(-100%); }
    }
    
    .marquee-content {
        display: flex;
        animation: marqueeScroll var(--marquee-duration, 30s) linear infinite;
        white-space: nowrap;
    }
    
    .marquee-bar:hover .marquee-content {
        animation-play-state: paused;
    }
    
    @keyframes marqueeScroll {
        0% { transform: translateX(0); }
        100% { transform: translateX(-50%); }
    }
    
    .marquee-item {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 0 40px;
        font-size: 13px;
        font-weight: 600;
    }
    
    .marquee-item i {
        font-size: 14px;
    }
    
    .marquee-item a {
        text-decoration: underline;
        text-underline-offset: 2px;
    }
    
    .marquee-item a:hover {
        opacity: 0.8;
    }
    
    .marquee-close {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0,0,0,0.2);
        border: none;
        width: 22px;
        height: 22px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        font-size: 10px;
        transition: all 0.2s;
        z-index: 10;
    }
    
    .marquee-close:hover {
        background: rgba(0,0,0,0.3);
        transform: translateY(-50%) scale(1.1);
    }
    
    @media (max-width: 767px) {
        .marquee-bar.hide-mobile { display: none !important; }
        .marquee-bar { height: 32px; }
        .marquee-item { font-size: 12px; padding: 0 30px; }
    }
    
    /* Marquee varsa diğer elementleri aşağı it */
    body.has-marquee .navbar { top: 36px; }
    body.has-marquee .main-content { padding-top: 116px; }
    body.has-marquee .flash-toast { top: 136px; }
    body.has-marquee .fake-notif-container.top-left,
    body.has-marquee .fake-notif-container.top-right { top: 136px; }
    
    @media (max-width: 767px) {
        body.has-marquee .navbar { top: 32px; }
        body.has-marquee .main-content { padding-top: 112px; }
    }

    .navbar { background: rgba(var(--header-bg-rgb), 0.8); backdrop-filter: blur(20px); padding: 15px 0; border-bottom: 1px solid rgba(255,255,255,0.05); transition: all 0.3s; }
    .navbar.scrolled { background: rgba(var(--header-bg-rgb), 0.95); padding: 10px 0; box-shadow: 0 5px 30px rgba(0,0,0,0.3); }
    .navbar-brand { font-size: 24px; font-weight: 800; color: #fff !important; }
    .navbar-brand i { color: var(--primary); }
    .navbar-logo { height: 40px; }
    
    .navbar-nav .nav-link { color: rgba(255,255,255,0.8) !important; font-weight: 500; padding: 10px 20px !important; border-radius: 8px; transition: all 0.3s; white-space: nowrap; }
    .navbar-nav .nav-link:hover, .navbar-nav .nav-link.active { color: #fff !important; background: rgba(var(--primary-rgb), 0.15); }
    .navbar-toggler { border: none; padding: 10px; }
    .navbar-toggler:focus { box-shadow: none; }
    .navbar-toggler-icon { background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba%28255, 255, 255, 0.8%29' stroke-linecap='round' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e"); }

    .btn-primary-custom { background: var(--gradient); border: none; color: #fff; padding: 12px 28px; border-radius: 10px; font-weight: 600; box-shadow: var(--shadow); transition: all 0.3s; }
    .btn-primary-custom:hover { transform: translateY(-2px); box-shadow: 0 15px 40px rgba(var(--primary-rgb), 0.4); color: #fff; }
    .btn-outline-custom { border: 2px solid rgba(255,255,255,0.3); color: #fff; padding: 10px 25px; border-radius: 10px; font-weight: 600; background: transparent; }
    .btn-outline-custom:hover { background: #fff; color: var(--bg); border-color: #fff; }

    .notification-bell, .support-icon-btn { position: relative; width: 40px; height: 40px; background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.1); border-radius: 10px; display: flex; align-items: center; justify-content: center; color: rgba(255,255,255,0.8); cursor: pointer; transition: all 0.3s; flex-shrink: 0; }
    .notification-bell:hover, .support-icon-btn:hover { background: rgba(var(--primary-rgb), 0.2); color: #fff; }
    .notification-bell i, .support-icon-btn i { font-size: 16px; }
    .notif-badge, .support-badge { position: absolute; top: -4px; right: -4px; min-width: 16px; height: 16px; color: #fff; font-size: 9px; font-weight: 700; border-radius: 8px; display: flex; align-items: center; justify-content: center; padding: 0 4px; }
    .notif-badge { background: #ef4444; }
    .support-badge { background: #f59e0b; }
    
    .notification-panel { position: absolute; top: calc(100% + 8px); right: 0; width: 360px; max-height: 450px; background: var(--header-bg); border: 1px solid rgba(255,255,255,0.1); border-radius: 14px; box-shadow: 0 15px 40px rgba(0,0,0,0.4); display: none; z-index: 1055; overflow: hidden; }
    .notification-panel.active { display: block; }
    .notification-panel-header { padding: 14px 18px; border-bottom: 1px solid rgba(255,255,255,0.08); display: flex; align-items: center; justify-content: space-between; }
    .notification-panel-header h6 { margin: 0; font-size: 14px; font-weight: 700; color: #fff; }
    .notification-panel-header h6 i { color: var(--primary); margin-right: 8px; }
    .notification-mark-read { font-size: 11px; color: var(--primary); cursor: pointer; padding: 4px 8px; border-radius: 4px; transition: all 0.2s; background: none; border: none; }
    .notification-mark-read:hover { background: rgba(var(--primary-rgb), 0.15); }
    .notification-panel-body { max-height: 380px; overflow-y: auto; }
    .notif-item { display: flex; gap: 12px; padding: 14px 18px; border-bottom: 1px solid rgba(255,255,255,0.05); cursor: pointer; transition: background 0.2s; }
    .notif-item:hover { background: rgba(var(--primary-rgb), 0.08); }
    .notif-item:last-child { border-bottom: none; }
    .notif-item.unread { background: rgba(var(--primary-rgb), 0.05); }
    .notif-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 16px; flex-shrink: 0; }
    .notif-content { flex: 1; min-width: 0; }
    .notif-title { font-size: 13px; font-weight: 600; color: #fff; margin-bottom: 2px; }
    .notif-text { font-size: 12px; color: rgba(255,255,255,0.6); line-height: 1.4; }
    .notif-link { font-size: 11px; color: var(--primary); margin-top: 6px; display: inline-block; }
    .notif-empty { padding: 30px; text-align: center; color: rgba(255,255,255,0.4); }
    .notif-empty i { font-size: 32px; margin-bottom: 10px; display: block; }

    .support-icon-btn { display: none; }
    @media (min-width: 768px) {
        .support-icon-btn { display: flex; }
        .support-mobile-link { display: none !important; }
    }

    .user-btn { display: flex; align-items: center; gap: 10px; background: rgba(255,255,255,0.05); border: none; padding: 8px 15px 8px 8px; border-radius: 10px; color: #fff; cursor: pointer; flex-shrink: 0; }
    .user-btn:hover { background: rgba(255,255,255,0.1); }
    .user-avatar { width: 35px; height: 35px; background: var(--gradient); border-radius: 8px; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 14px; flex-shrink: 0; }
    .user-menu { background: var(--header-bg); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; padding: 8px; min-width: 200px; position: absolute; top: calc(100% + 8px); right: 0; z-index: 1055; display: none; }
    .user-menu.active { display: block; }
    .user-menu a { color: rgba(255,255,255,0.8); padding: 10px 15px; border-radius: 8px; display: flex; align-items: center; justify-content: space-between; }
    .user-menu a i { width: 20px; opacity: 0.7; }
    .user-menu a:hover { background: rgba(var(--primary-rgb), 0.15); color: #fff; }
    .user-menu hr { border-color: rgba(255,255,255,0.1); margin: 5px 0; }
    .menu-badge { background: rgba(245, 158, 11, 0.2); color: #f59e0b; font-size: 10px; font-weight: 700; padding: 2px 7px; border-radius: 8px; }

    .navbar-actions-right { display: flex; align-items: center; gap: 8px; flex-shrink: 0; flex-wrap: nowrap; }

    .main-content { padding-top: 80px; min-height: 100vh; }
    .flash-toast { position: fixed; top: 100px; right: 20px; z-index: 9999; max-width: 400px; }

    /* Fake Bildirim Stilleri */
    .fake-notif-container { position: fixed; z-index: 9998; pointer-events: none; }
    .fake-notif-container.bottom-left { bottom: 20px; left: 20px; }
    .fake-notif-container.bottom-right { bottom: 20px; right: 20px; }
    .fake-notif-container.top-left { top: 100px; left: 20px; }
    .fake-notif-container.top-right { top: 100px; right: 20px; }
    
    .fake-notif-toast { background: var(--header-bg); border: 1px solid rgba(255,255,255,0.1); border-radius: 14px; padding: 16px; min-width: 320px; max-width: 380px; box-shadow: 0 15px 50px rgba(0,0,0,0.4); display: flex; gap: 14px; align-items: flex-start; pointer-events: auto; opacity: 0; transform: translateY(30px) scale(0.95); transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1); }
    .fake-notif-toast.show { opacity: 1; transform: translateY(0) scale(1); }
    .fake-notif-toast.hide { opacity: 0; transform: translateY(-20px) scale(0.95); }
    
    .fake-notif-icon { width: 48px; height: 48px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 22px; flex-shrink: 0; }
    .fake-notif-body { flex: 1; min-width: 0; }
    .fake-notif-title { font-size: 14px; font-weight: 700; color: #fff; margin-bottom: 4px; display: flex; align-items: center; gap: 8px; }
    .fake-notif-title .verified { color: #22c55e; font-size: 14px; }
    .fake-notif-text { font-size: 13px; color: rgba(255,255,255,0.7); line-height: 1.5; margin-bottom: 6px; }
    .fake-notif-meta { font-size: 11px; color: rgba(255,255,255,0.4); display: flex; align-items: center; gap: 6px; }
    .fake-notif-meta i { font-size: 10px; }
    .fake-notif-close { position: absolute; top: 10px; right: 10px; background: none; border: none; color: rgba(255,255,255,0.3); font-size: 14px; cursor: pointer; padding: 4px; transition: color 0.2s; }
    .fake-notif-close:hover { color: #fff; }
    .fake-notif-toast { position: relative; }
    
    @media (max-width: 767px) {
        .fake-notif-container.hide-mobile { display: none !important; }
        .fake-notif-container { left: 10px !important; right: 10px !important; bottom: 10px !important; }
        .fake-notif-toast { min-width: auto; max-width: 100%; }
    }

    @media (max-width: 991px) {
        .navbar-collapse { background: var(--header-bg); margin-top: 15px; padding: 20px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.1); }
        .navbar-actions { margin-top: 15px; padding-top: 15px; border-top: 1px solid rgba(255,255,255,0.1); display: flex; flex-direction: column; gap: 10px; }
        .notification-panel { position: fixed; top: 70px; right: 10px; left: 10px; width: auto; max-height: calc(100vh - 90px); }
        .notification-panel-body { max-height: calc(100vh - 160px); }
    }
    @media (max-width: 767px) {
        .support-icon-btn { display: none !important; }
        .support-mobile-link { display: block !important; }
    }
    @media (max-width: 576px) {
        .notification-panel { right: 5px; left: 5px; }
    }
    </style>
</head>
<body<?php if ($showMarquee): ?> class="has-marquee"<?php endif; ?>>

<div id="preloader"><div class="spinner"></div></div>

<?php if ($showMarquee): ?>
<!-- Kayan Yazı Banner -->
<div class="marquee-bar <?php echo !$marqueeSettings['show_on_mobile'] ? 'hide-mobile' : ''; ?>" 
     id="marqueeBar"
     style="background: <?php echo clean($marqueeSettings['bg_color']); ?>; color: <?php echo clean($marqueeSettings['text_color']); ?>; --marquee-duration: <?php echo (int)$marqueeSettings['speed']; ?>s;">
    
    <div class="marquee-content">
        <?php 
        // İçeriği 2 kez tekrarla (seamless loop için)
        for ($repeat = 0; $repeat < 2; $repeat++): 
            foreach ($marqueeItems as $item): 
        ?>
        <span class="marquee-item">
            <?php if (!empty($item['icon'])): ?>
            <i class="<?php echo clean($item['icon']); ?>"></i>
            <?php endif; ?>
            <span>
                <?php echo clean($item['text']); ?>
                <?php if (!empty($item['link']) && !empty($item['link_text'])): ?>
                <a href="<?php echo clean($item['link']); ?>" style="color: inherit;"><?php echo clean($item['link_text']); ?></a>
                <?php endif; ?>
            </span>
        </span>
        <?php 
            endforeach; 
        endfor; 
        ?>
    </div>
    
    <?php if ($marqueeSettings['is_closable']): ?>
    <button type="button" class="marquee-close" id="closeMarquee" style="color: <?php echo clean($marqueeSettings['text_color']); ?>;">
        <i class="fas fa-times"></i>
    </button>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php if ($flash = getFlash()): ?>
<div class="flash-toast">
    <div class="alert alert-<?php echo $flash['type'] === 'error' ? 'danger' : $flash['type']; ?> alert-dismissible fade show">
        <i class="fas fa-<?php echo $flash['type'] === 'success' ? 'check-circle' : 'exclamation-circle'; ?> me-2"></i>
        <?php echo clean($flash['message']); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
</div>
<?php endif; ?>

<!-- Fake Bildirim Container -->
<?php if ($fakeNotifSettings['is_active']): ?>
<div class="fake-notif-container <?php echo $fakeNotifSettings['position']; ?> <?php echo !$fakeNotifSettings['show_on_mobile'] ? 'hide-mobile' : ''; ?>" id="fakeNotifContainer">
    <div class="fake-notif-toast" id="fakeNotifToast">
        <button type="button" class="fake-notif-close" id="fakeNotifClose"><i class="fas fa-times"></i></button>
        <div class="fake-notif-icon" id="fakeNotifIcon">
            <i class="fab fa-instagram"></i>
        </div>
        <div class="fake-notif-body">
            <div class="fake-notif-title">
                <span id="fakeNotifName">Ahmet Y.</span>
                <i class="fas fa-check-circle verified"></i>
            </div>
            <div class="fake-notif-text" id="fakeNotifText">
                <strong>10.000</strong> Instagram Takipçi satın aldı
            </div>
            <div class="fake-notif-meta">
                <i class="fas fa-map-marker-alt"></i>
                <span id="fakeNotifCity">İstanbul</span>
                <span>•</span>
                <i class="fas fa-clock"></i>
                <span id="fakeNotifTime">2 dakika önce</span>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<nav class="navbar navbar-expand-lg fixed-top" id="navbar">
    <div class="container">
        <a class="navbar-brand" href="<?php echo SITE_URL; ?>">
            <?php if ($settings->getLogoUrl()): ?>
                <img src="<?php echo clean($settings->getLogoUrl()); ?>" alt="<?php echo clean(SITE_NAME); ?>" class="navbar-logo">
            <?php else: ?>
                <i class="fas fa-bolt me-2"></i><?php echo clean(SITE_NAME); ?>
            <?php endif; ?>
        </a>
        
        <div class="navbar-actions-right order-lg-last">
            <!-- Bildirim -->
            <div class="position-relative" id="notifWrapper">
                <div class="notification-bell" id="notifBell">
                    <i class="fas fa-bell"></i>
                    <?php if ($unreadNotificationCount > 0): ?>
                    <span class="notif-badge" id="notifBadge"><?php echo $unreadNotificationCount; ?></span>
                    <?php endif; ?>
                </div>
                
                <div class="notification-panel" id="notifPanel">
                    <div class="notification-panel-header">
                        <h6><i class="fas fa-bell"></i>Bildirimler</h6>
                        <?php if ($unreadNotificationCount > 0): ?>
                        <button type="button" class="notification-mark-read" id="markAllRead">Tümünü okundu işaretle</button>
                        <?php endif; ?>
                    </div>
                    <div class="notification-panel-body">
                        <?php if (empty($notifications)): ?>
                        <div class="notif-empty">
                            <i class="fas fa-bell-slash"></i>
                            <p>Henüz bildirim yok</p>
                        </div>
                        <?php else: ?>
                            <?php foreach ($notifications as $n): ?>
                            <div class="notif-item <?php echo !in_array($n['id'], $readIds) ? 'unread' : ''; ?>" data-id="<?php echo $n['id']; ?>" data-link="<?php echo clean($n['link'] ?? ''); ?>">
                                <div class="notif-icon" style="background:<?php echo clean($n['icon_color']); ?>22;color:<?php echo clean($n['icon_color']); ?>">
                                    <i class="<?php echo clean($n['icon']); ?>"></i>
                                </div>
                                <div class="notif-content">
                                    <div class="notif-title"><?php echo clean($n['title']); ?></div>
                                    <div class="notif-text"><?php echo clean($n['message']); ?></div>
                                    <?php if (!empty($n['link_text'])): ?>
                                    <span class="notif-link"><?php echo clean($n['link_text']); ?> <i class="fas fa-arrow-right"></i></span>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Destek İkonu (Masaüstü/Tablet) -->
            <a href="<?php echo SITE_URL; ?>/destek.php" class="support-icon-btn" title="Destek">
                <i class="fas fa-headset"></i>
                <?php if (isLoggedIn() && $openTicketCount > 0): ?>
                <span class="support-badge"><?php echo $openTicketCount; ?></span>
                <?php endif; ?>
            </a>
            
            <?php if (isLoggedIn()): ?>
            <div class="position-relative" id="userWrapper">
                <div class="user-btn" id="userBtn">
                    <span class="user-avatar"><?php echo strtoupper(substr($_SESSION['user_name'] ?? 'U', 0, 1)); ?></span>
                    <span class="d-none d-lg-inline"><?php echo clean($_SESSION['user_name'] ?? 'Kullanıcı'); ?></span>
                    <i class="fas fa-chevron-down ms-1 d-none d-lg-inline" style="font-size: 10px; opacity: 0.6;"></i>
                </div>
                <div class="user-menu" id="userMenu">
                    <a href="<?php echo SITE_URL; ?>/hesabim.php"><i class="fas fa-user me-2"></i>Hesabım</a>
                    <a href="<?php echo SITE_URL; ?>/siparislerim.php"><i class="fas fa-box me-2"></i>Siparişlerim</a>
                    <?php if (isAdmin()): ?>
                    <hr>
                    <a href="<?php echo SITE_URL; ?>/admin/" class="text-warning"><i class="fas fa-cog me-2"></i>Admin Panel</a>
                    <?php endif; ?>
                    <hr>
                    <a href="<?php echo SITE_URL; ?>/cikis.php" class="text-danger"><i class="fas fa-sign-out-alt me-2"></i>Çıkış</a>
                </div>
            </div>
            <?php else: ?>
            <div class="d-none d-lg-flex gap-2">
                <a href="<?php echo SITE_URL; ?>/giris.php" class="btn btn-outline-custom btn-sm"><i class="fas fa-sign-in-alt me-1"></i> Giriş</a>
                <a href="<?php echo SITE_URL; ?>/kayit.php" class="btn btn-primary-custom btn-sm"><i class="fas fa-user-plus me-1"></i> Kayıt Ol</a>
            </div>
            <?php endif; ?>
            
            <button class="navbar-toggler" type="button" id="navbarToggler">
                <span class="navbar-toggler-icon"></span>
            </button>
        </div>
        
        <div class="navbar-collapse collapse" id="navbarNav">
            <ul class="navbar-nav mx-auto">
                <?php foreach ($menuItems as $item): 
                    $isActive = ($item['url'] === SITE_URL && $currentPage === 'index.php');
                ?>
                <li class="nav-item">
                    <a class="nav-link <?php echo $isActive ? 'active' : ''; ?>" href="<?php echo $item['url']; ?>">
                        <i class="<?php echo $item['icon']; ?> me-1"></i> <?php echo $item['title']; ?>
                    </a>
                </li>
                <?php endforeach; ?>
                
                <!-- Destek Linki (Sadece Mobilde) -->
                <li class="nav-item support-mobile-link">
                    <a class="nav-link <?php echo $currentPage === 'destek.php' ? 'active' : ''; ?>" href="<?php echo SITE_URL; ?>/destek.php">
                        <i class="fas fa-headset me-1"></i> Destek
                        <?php if (isLoggedIn() && $openTicketCount > 0): ?>
                        <span class="menu-badge ms-2"><?php echo $openTicketCount; ?></span>
                        <?php endif; ?>
                    </a>
                </li>
            </ul>
            
            <?php if (!isLoggedIn()): ?>
            <div class="navbar-actions d-lg-none">
                <a href="<?php echo SITE_URL; ?>/giris.php" class="btn btn-outline-custom w-100"><i class="fas fa-sign-in-alt me-1"></i> Giriş Yap</a>
                <a href="<?php echo SITE_URL; ?>/kayit.php" class="btn btn-primary-custom w-100"><i class="fas fa-user-plus me-1"></i> Kayıt Ol</a>
            </div>
            <?php endif; ?>
        </div>
    </div>
</nav>

<main class="main-content">

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
(function() {
    var currentPageUrl = window.location.href.split('?')[0];
    
    // ==========================================
    // KAYAN YAZI KAPATMA
    // ==========================================
    var closeMarqueeBtn = document.getElementById('closeMarquee');
    var marqueeBar = document.getElementById('marqueeBar');
    
    if (closeMarqueeBtn && marqueeBar) {
        closeMarqueeBtn.addEventListener('click', function() {
            marqueeBar.classList.add('hiding');
            
            fetch(currentPageUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: 'close_marquee=1'
            });
            
            setTimeout(function() {
                marqueeBar.remove();
                document.body.classList.remove('has-marquee');
            }, 300);
        });
    }
    
    var notifBell = document.getElementById('notifBell');
    var notifPanel = document.getElementById('notifPanel');
    var notifBadge = document.getElementById('notifBadge');
    var markAllBtn = document.getElementById('markAllRead');
    var notifWrapper = document.getElementById('notifWrapper');
    
    var userBtn = document.getElementById('userBtn');
    var userMenu = document.getElementById('userMenu');
    var userWrapper = document.getElementById('userWrapper');
    
    var navbarToggler = document.getElementById('navbarToggler');
    var navbarNav = document.getElementById('navbarNav');
    
    if (navbarToggler && navbarNav) {
        navbarToggler.addEventListener('click', function() {
            navbarNav.classList.toggle('show');
        });
        
        var navLinks = navbarNav.querySelectorAll('.nav-link');
        navLinks.forEach(function(link) {
            link.addEventListener('click', function() {
                navbarNav.classList.remove('show');
            });
        });
        
        var authBtns = navbarNav.querySelectorAll('.navbar-actions .btn');
        authBtns.forEach(function(btn) {
            btn.addEventListener('click', function() {
                navbarNav.classList.remove('show');
            });
        });
    }
    
    if (notifBell && notifPanel) {
        notifBell.addEventListener('click', function(e) {
            e.stopPropagation();
            if (userMenu) userMenu.classList.remove('active');
            notifPanel.classList.toggle('active');
        });
    }
    
    if (userBtn && userMenu) {
        userBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            if (notifPanel) notifPanel.classList.remove('active');
            userMenu.classList.toggle('active');
        });
    }
    
    var notifItems = document.querySelectorAll('.notif-item');
    notifItems.forEach(function(item) {
        item.addEventListener('click', function() {
            var id = this.getAttribute('data-id');
            var link = this.getAttribute('data-link');
            var self = this;
            
            var formData = new FormData();
            formData.append('notification_action', 'mark_read');
            formData.append('notification_id', id);
            
            fetch(currentPageUrl, {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    self.classList.remove('unread');
                    updateBadge();
                }
            })
            .catch(function(err) { console.error(err); });
            
            if (link && link !== '') {
                window.location.href = link;
            }
        });
    });
    
    if (markAllBtn) {
        markAllBtn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            var self = this;
            var formData = new FormData();
            formData.append('notification_action', 'mark_all_read');
            
            fetch(currentPageUrl, {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                if (data.success) {
                    document.querySelectorAll('.notif-item.unread').forEach(function(el) {
                        el.classList.remove('unread');
                    });
                    if (notifBadge) notifBadge.style.display = 'none';
                    self.style.display = 'none';
                }
            })
            .catch(function(err) { console.error(err); });
        });
    }
    
    function updateBadge() {
        var count = document.querySelectorAll('.notif-item.unread').length;
        if (notifBadge) {
            notifBadge.textContent = count;
            notifBadge.style.display = count > 0 ? 'flex' : 'none';
        }
    }
    
    document.addEventListener('click', function(e) {
        if (notifWrapper && !notifWrapper.contains(e.target) && notifPanel) {
            notifPanel.classList.remove('active');
        }
        if (userWrapper && !userWrapper.contains(e.target) && userMenu) {
            userMenu.classList.remove('active');
        }
        var navbar = document.getElementById('navbar');
        if (navbarNav && navbar && !navbar.contains(e.target)) {
            navbarNav.classList.remove('show');
        }
    });
    
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            if (notifPanel) notifPanel.classList.remove('active');
            if (userMenu) userMenu.classList.remove('active');
            if (navbarNav) navbarNav.classList.remove('show');
        }
    });
    
    window.addEventListener('load', function() {
        var preloader = document.getElementById('preloader');
        if (preloader) preloader.classList.add('fade-out');
    });
    
    window.addEventListener('scroll', function() {
        var navbar = document.getElementById('navbar');
        if (navbar) {
            navbar.classList.toggle('scrolled', window.scrollY > 50);
        }
    });
    
    <?php if ($fakeNotifSettings['is_active']): ?>
    (function() {
        var fakeNotifContainer = document.getElementById('fakeNotifContainer');
        var fakeNotifToast = document.getElementById('fakeNotifToast');
        var fakeNotifClose = document.getElementById('fakeNotifClose');
        var fakeNotifIcon = document.getElementById('fakeNotifIcon');
        var fakeNotifName = document.getElementById('fakeNotifName');
        var fakeNotifText = document.getElementById('fakeNotifText');
        var fakeNotifCity = document.getElementById('fakeNotifCity');
        var fakeNotifTime = document.getElementById('fakeNotifTime');
        
        if (!fakeNotifContainer || !fakeNotifToast) return;
        
        var intervalMin = <?php echo (int)$fakeNotifSettings['interval_min']; ?> * 1000;
        var intervalMax = <?php echo (int)$fakeNotifSettings['interval_max']; ?> * 1000;
        var displayDuration = <?php echo (int)$fakeNotifSettings['display_duration']; ?> * 1000;
        
        var isVisible = false;
        var hideTimeout = null;
        var nextTimeout = null;
        
        function getRandomInterval() {
            return Math.floor(Math.random() * (intervalMax - intervalMin + 1)) + intervalMin;
        }
        
        function showNotification(data) {
            if (isVisible) return;
            
            fakeNotifIcon.innerHTML = '<i class="' + data.platform_icon + '"></i>';
            fakeNotifIcon.style.background = data.platform_color + '22';
            fakeNotifIcon.style.color = data.platform_color;
            fakeNotifName.textContent = data.name;
            fakeNotifText.innerHTML = '<strong>' + data.quantity + '</strong> ' + data.platform + ' ' + data.package_name + ' satın aldı';
            fakeNotifCity.textContent = data.city;
            fakeNotifTime.textContent = data.time_ago;
            
            fakeNotifToast.classList.remove('hide');
            fakeNotifToast.classList.add('show');
            isVisible = true;
            
            hideTimeout = setTimeout(function() {
                hideNotification();
            }, displayDuration);
        }
        
        function hideNotification() {
            fakeNotifToast.classList.remove('show');
            fakeNotifToast.classList.add('hide');
            isVisible = false;
            scheduleNext();
        }
        
        function fetchAndShow() {
            var formData = new FormData();
            formData.append('get_fake_notification', '1');
            
            fetch(currentPageUrl, {
                method: 'POST',
                body: formData,
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(function(response) { return response.json(); })
            .then(function(result) {
                if (result.success && result.data) {
                    showNotification(result.data);
                } else {
                    scheduleNext();
                }
            })
            .catch(function(err) {
                console.error('Fake notification error:', err);
                scheduleNext();
            });
        }
        
        function scheduleNext() {
            if (nextTimeout) clearTimeout(nextTimeout);
            nextTimeout = setTimeout(function() {
                fetchAndShow();
            }, getRandomInterval());
        }
        
        if (fakeNotifClose) {
            fakeNotifClose.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                if (hideTimeout) clearTimeout(hideTimeout);
                hideNotification();
            });
        }
        
        setTimeout(function() {
            fetchAndShow();
        }, Math.floor(Math.random() * 5000) + 3000);
    })();
    <?php endif; ?>
})();
</script>