<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/db.php'; 

// Definir constante de URL base si no existe para que los links no se rompan
if (!defined('BASE_URL')) {
    define('BASE_URL', 'http://localhost/vvault/');
}

// --- SALDO REAL (LEDGER) ---
$user_balance = 0.00;
if(isset($_SESSION['user_id'])) {
    $stmt_b = $pdo->prepare("SELECT SUM(CASE WHEN entry_type = 'credit' THEN amount ELSE -amount END) FROM ledger WHERE user_id = ?");
    $stmt_b->execute([$_SESSION['user_id']]);
    $user_balance = $stmt_b->fetchColumn() ?: 0.00;
}

try {
    $stmt_settings = $pdo->query("SELECT setting_key, setting_value FROM site_settings");
    $site_cfg = $stmt_settings->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (Exception $e) { $site_cfg = []; }

$primary_color = $site_cfg['primary_color'] ?? '#00ff88';
$bg_dark       = $site_cfg['background_color'] ?? '#090b0f';
$nav_bg        = $site_cfg['nav_bg'] ?? '#11141b';
$txt1          = $site_cfg['logo_text_1'] ?? 'V';
$txt2          = $site_cfg['logo_text_2'] ?? 'VAULT';

$meta_title = isset($page_title) ? $page_title . " | VVault" : "VVault | Marketplace";
$current_role = $_SESSION['role'] ?? $_SESSION['user_role'] ?? 'user';
?>
<!DOCTYPE html>
<html lang="en"> 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <base href="<?php echo BASE_URL; ?>">
    <title><?php echo $meta_title; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;700;900&family=Syncopate:wght@700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        :root {
            --primary: <?php echo $primary_color; ?>;
            --bg-dark: <?php echo $bg_dark; ?>;
            --nav-bg: <?php echo $nav_bg; ?>;
            --border: #2d333b;
            --text-gray: #8b949e;
            --card-bg: #161b22; 
            --gold: #d4af37;
        }

        body { background: var(--bg-dark); color: white; font-family: 'Inter', sans-serif; margin: 0; }
        
        nav { 
            background: var(--nav-bg); border-bottom: 1px solid var(--border); 
            padding: 0 40px; display: flex; align-items: center; justify-content: space-between;
            position: sticky; top: 0; z-index: 1000; height: 75px; box-sizing: border-box;
        }

        .logo { display: flex; align-items: center; font-family: 'Syncopate', sans-serif; font-size: 22px; font-weight: 700; color: white; text-decoration: none; }
        .logo .p1 { color: var(--primary); }

        .nav-search-container { position: relative; width: 350px; margin: 0 20px; }
        .nav-search-container input {
            width: 100%; background: rgba(255,255,255,0.05); border: 1px solid var(--border);
            padding: 10px 15px 10px 40px; border-radius: 8px; color: white; font-size: 13px; outline: none;
        }
        .nav-search-container input:focus { border-color: var(--primary); }
        .nav-search-container i { position: absolute; left: 15px; top: 50%; transform: translateY(-50%); color: var(--text-gray); }

        #search-results-dropdown {
            position: absolute; top: 55px; left: 0; width: 100%; background: #1c2128;
            border: 1px solid var(--border); border-radius: 8px; display: none; z-index: 9999;
            box-shadow: 0 10px 30px rgba(0,0,0,0.8);
            max-height: 400px; overflow-y: auto;
        }
        .search-item { padding: 12px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 12px; text-decoration: none; color: white; transition: 0.2s; }
        .search-item:hover { background: rgba(255,255,255,0.08); }
        .search-item img { width: 38px; height: 38px; object-fit: cover; border-radius: 6px; background: #000; }

        .nav-links { display: flex; align-items: center; gap: 15px; }
        .nav-links a { color: var(--text-gray); text-decoration: none; font-size: 13px; font-weight: 600; transition: 0.2s; }
        .nav-links a:hover { color: white; }

        .nav-dropdown { position: relative; height: 75px; display: flex; align-items: center; }
        .nav-drop-title { color: var(--text-gray); font-size: 13px; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 6px; }
        .nav-drop-content {
            display: none; position: absolute; top: 75px; left: 0; background: var(--card-bg); 
            min-width: 180px; border: 1px solid var(--border); border-radius: 0 0 8px 8px; overflow: hidden;
        }
        .nav-drop-content a { color: #adbac7 !important; padding: 12px 18px; border-bottom: 1px solid var(--border); display: block; }
        .nav-dropdown:hover .nav-drop-content { display: block; }

        .admin-badge {
            color: var(--gold) !important; background: rgba(212, 175, 55, 0.1);
            padding: 6px 12px; border-radius: 6px; border: 1px solid rgba(212, 175, 55, 0.3);
            font-size: 11px !important; font-weight: 800; display: flex; align-items: center; gap: 5px;
        }

        .balance-badge {
            background: rgba(0, 255, 136, 0.05); padding: 6px 12px; border-radius: 6px;
            border: 1px solid rgba(0, 255, 136, 0.2); font-weight: 800; color: white !important;
        }
        .balance-badge span { color: var(--primary); }

        .link-account {
            display: flex; align-items: center; gap: 8px; background: rgba(255,255,255,0.05);
            padding: 8px 15px; border-radius: 8px; border: 1px solid var(--border); color: white !important;
        }
    </style>
</head>
<body>

<nav>
    <a href="./" class="logo">
        <span class="p1"><?php echo htmlspecialchars($txt1); ?></span><span class="p2"><?php echo htmlspecialchars($txt2); ?></span>
    </a>

    <div class="nav-search-container">
        <i class="fa-solid fa-magnifying-glass"></i>
        <input type="text" id="header-search-input" placeholder="Search games..." autocomplete="off">
        <div id="search-results-dropdown"></div>
    </div>

    <div class="nav-links">
        <div class="nav-dropdown">
            <div class="nav-drop-title">Support <i class="fa-solid fa-chevron-down" style="font-size: 9px;"></i></div>
            <div class="nav-drop-content">
                <a href="support.php?section=rules"><i class="fa-solid fa-book-open"></i> Rules</a>
                <a href="support.php?section=center"><i class="fa-solid fa-headset"></i> Help Center</a>
            </div>
        </div>

        <?php if(isset($_SESSION['user_id'])): ?>
            <a href="my_orders.php">Purchases</a>
            
            <a href="balance.php" class="balance-badge">
                <?php echo number_format($user_balance, 2); ?> <span>$</span>
            </a>

            <?php if($current_role === 'admin'): ?>
                <a href="admin/" class="admin-badge">
                    <i class="fa-solid fa-crown"></i> ADMIN
                </a>
            <?php endif; ?>

            <a href="dashboard.php" class="link-account">
                <i class="fa-solid fa-circle-user" style="color: var(--primary);"></i> 
                <?php echo htmlspecialchars($_SESSION['username'] ?? 'User'); ?>
            </a>
            
            <a href="logout.php" style="color: #ff4d4d; margin-left: 10px;"><i class="fa-solid fa-power-off"></i></a>
        <?php else: ?>
            <a href="login.php">Login</a>
            <a href="register.php" style="background: var(--primary); color: black; padding: 10px 20px; border-radius: 8px; font-weight: 800;">Join Now</a>
        <?php endif; ?>
    </div>
</nav>

<script>
document.getElementById('header-search-input').addEventListener('input', function() {
    let query = this.value.trim();
    let resultsBox = document.getElementById('search-results-dropdown');
    
    if (query.length < 2) {
        resultsBox.style.display = 'none';
        return;
    }

    // Usamos la URL absoluta para el fetch también
    fetch('includes/ajax_search.php?q=' + encodeURIComponent(query))
        .then(res => res.json())
        .then(data => {
            resultsBox.innerHTML = '';
            if (data.length > 0) {
                data.forEach(game => {
                    resultsBox.innerHTML += `
                        <a href="catalog.php?game=${game.slug}" class="search-item">
                            <img src="assets/img/${game.image_icon}" onerror="this.src='assets/img/default_game.png'">
                            <div>
                                <div style="font-size:13px; font-weight:bold; color:white;">${game.name}</div>
                                <div style="font-size:11px; color:var(--primary);">View Marketplace</div>
                            </div>
                        </a>`;
                });
                resultsBox.style.display = 'block';
            } else {
                resultsBox.innerHTML = '<div style="padding:15px; font-size:12px; color:gray; text-align:center;">No games found.</div>';
                resultsBox.style.display = 'block';
            }
        });
});

document.addEventListener('click', function(e) {
    if (!document.querySelector('.nav-search-container').contains(e.target)) {
        document.getElementById('search-results-dropdown').style.display = 'none';
    }
});
</script>