<?php
/**
 * User Header Template - Fixed
 */

// Start output buffering
ob_start();

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

// Installation check removed

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/Auth.php';

// Check if user is logged in using session directly
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'user') {
    header('Location: login.php');
    exit;
}

// Get user from database
$user = dbFetch("SELECT * FROM users WHERE id = ?", [$_SESSION['user_id']]);
if (!$user || $user['status'] !== 'active') {
    // Clear session and redirect
    session_destroy();
    header('Location: login.php');
    exit;
}

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

// Get wallet
$wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = ?", [$user['id']]);
if (!$wallet) {
    dbInsert('user_wallets', [
        'user_id' => $user['id'],
        'balance' => 0,
        'demo_balance' => defined('DEMO_BALANCE') ? DEMO_BALANCE : 10000
    ]);
    $wallet = ['balance' => 0, 'demo_balance' => 10000];
}

$accountType = $_SESSION['account_type'] ?? 'demo';
$pendingData = dbFetch("SELECT COALESCE(SUM(amount), 0) as total FROM withdrawals WHERE user_id = ? AND status = 'pending'", [$user['id']]);
$pendingAmount = (float)($pendingData['total'] ?? 0);
$currentBalance = $accountType === 'demo' ? ($wallet['demo_balance'] ?? 10000) : max(0, (($wallet['balance'] ?? 0) + ($wallet['bonus_balance'] ?? 0) - $pendingAmount));

// Site settings
$siteName = defined('APP_NAME') ? APP_NAME : 'BinaryPro';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle ?? 'Dashboard') ?> - <?= htmlspecialchars($siteName) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;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{--bg-primary:#0a0e17;--bg-secondary:#12171f;--bg-card:#1a1f2a;--bg-tertiary:#252b3b;--bg-hover:#2a3142;--text-primary:#fff;--text-secondary:#8b92a8;--text-muted:#6b7280;--border-color:#2a3344;--border-light:#3d4555;--green:#00d09c;--red:#ff4757;--accent-green:#00d09c;--accent-red:#ff4757;--accent-yellow:#fbbf24;--accent-blue:#3b82f6;--radius-sm:4px;--radius-md:8px;--radius-lg:12px;--radius-xl:16px;--radius-full:9999px;--font-mono:'JetBrains Mono','Fira Code',monospace;--shadow-lg:0 10px 40px rgba(0,0,0,.3);--transition-fast:0.15s ease;--gradient-green:linear-gradient(135deg,#00d09c,#00a87a)}
        *{margin:0;padding:0;box-sizing:border-box}
        body{font-family:'Inter',sans-serif;background:var(--bg-primary);color:var(--text-primary);min-height:100vh}
        .app-container{display:flex;min-height:100vh}
        .sidebar{width:260px;background:var(--bg-secondary);border-right:1px solid var(--border-color);position:fixed;height:100vh;overflow-y:auto}
        .sidebar-header{padding:20px;border-bottom:1px solid var(--border-color)}
        .sidebar-title{font-size:1.5rem;font-weight:700;color:var(--green)}
        .sidebar-nav{padding:12px}
        .nav-item{display:flex;align-items:center;gap:12px;padding:12px 16px;color:var(--text-secondary);text-decoration:none;border-radius:8px;margin-bottom:4px;transition:all .2s}
        .nav-item:hover,.nav-item.active{background:var(--bg-card);color:var(--text-primary)}
        .nav-item.active{color:var(--green)}
        .nav-item i{width:20px}
        .main-content{flex:1;margin-left:260px;padding:24px}
        .top-bar{display:flex;justify-content:space-between;align-items:center;margin-bottom:24px}
        .page-title{font-size:1.5rem;font-weight:600}
        .balance-box{display:flex;align-items:center;gap:16px}
        .balance-item{background:var(--bg-card);padding:10px 16px;border-radius:8px;border:1px solid var(--border-color)}
        .balance-label{font-size:.75rem;color:var(--text-secondary)}
        .balance-value{font-size:1.1rem;font-weight:600}
        .balance-value.demo{color:var(--green)}
        .balance-value.live{color:#fbbf24}
        .btn{padding:10px 20px;border:none;border-radius:8px;font-weight:600;cursor:pointer;text-decoration:none;display:inline-flex;align-items:center;gap:8px}
        .btn-primary{background:var(--green);color:#000}
        .btn-secondary{background:var(--bg-card);color:var(--text-primary);border:1px solid var(--border-color)}
        .card{background:var(--bg-card);border:1px solid var(--border-color);border-radius:12px;padding:20px;margin-bottom:20px}
        .card-title{font-size:1rem;font-weight:600;margin-bottom:16px}
        .stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:16px}
        .stat-card{background:var(--bg-secondary);border:1px solid var(--border-color);border-radius:10px;padding:16px}
        .stat-label{font-size:.8rem;color:var(--text-secondary);margin-bottom:4px}
        .stat-value{font-size:1.5rem;font-weight:700}
        .stat-value.green{color:var(--green)}
        .stat-value.red{color:var(--red)}
        @media(max-width:768px){
            .sidebar{transform:translateX(-100%);transition:transform .3s ease;display:block;z-index:1000}
            .sidebar.active{transform:translateX(0)}
            .main-content{margin-left:0}
            .sidebar-toggle{display:block!important}
        }
        .sidebar-toggle{display:none;background:none;border:none;color:var(--text-primary);font-size:1.5rem;cursor:pointer;margin-right:1rem}
        .sidebar-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:999}
        .sidebar-overlay.active{display:block}

        /* Form controls */
        .form-group{margin-bottom:1rem}
        .form-label{display:block;font-size:.875rem;font-weight:500;color:var(--text-secondary);margin-bottom:.375rem}
        .form-control{width:100%;padding:.625rem .875rem;background:var(--bg-primary);border:1px solid var(--border-color);border-radius:var(--radius-md);color:var(--text-primary);font-size:.9rem;font-family:inherit;outline:none;transition:border-color var(--transition-fast)}
        .form-control:focus{border-color:var(--accent-green)}
        .form-control:disabled{opacity:.6;cursor:not-allowed}
        select.form-control{appearance:none;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='%236b7280' viewBox='0 0 16 16'%3E%3Cpath d='M8 11L3 6h10z'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right .75rem center}
        .form-row{display:grid;grid-template-columns:1fr 1fr;gap:1rem}
        .form-text{font-size:.8rem;color:var(--text-muted);margin-top:.25rem}
        /* Alerts */
        .alert{padding:.875rem 1rem;border-radius:var(--radius-md);margin-bottom:1rem;font-size:.9rem;display:flex;align-items:center;gap:.5rem}
        .alert-success{background:rgba(0,208,156,.1);border:1px solid rgba(0,208,156,.3);color:var(--accent-green)}
        .alert-danger{background:rgba(255,71,87,.1);border:1px solid rgba(255,71,87,.3);color:var(--accent-red)}
        .alert-warning{background:rgba(251,191,36,.1);border:1px solid rgba(251,191,36,.3);color:var(--accent-yellow)}
        .alert-info{background:rgba(59,130,246,.1);border:1px solid rgba(59,130,246,.3);color:var(--accent-blue)}
        /* Badges */
        .badge{display:inline-flex;align-items:center;padding:.2rem .6rem;border-radius:var(--radius-full);font-size:.75rem;font-weight:600}
        .badge-success{background:rgba(0,208,156,.15);color:var(--accent-green)}
        .badge-danger{background:rgba(255,71,87,.15);color:var(--accent-red)}
        .badge-warning{background:rgba(251,191,36,.15);color:var(--accent-yellow)}
        /* Buttons */
        .btn-block{width:100%;justify-content:center}
        .btn-primary:hover{opacity:.9}
        .btn-secondary:hover{background:var(--bg-tertiary)}
        /* Card sub-parts */
        .card-header{padding:0 0 1rem;border-bottom:1px solid var(--border-color);margin-bottom:1rem}
        .card-body{/* already card padded */}
        .card-body.p-0{margin:-20px;padding:0}
        /* Table */
        .table{width:100%;border-collapse:collapse}
        .table th{text-align:left;padding:.75rem 1rem;font-size:.75rem;text-transform:uppercase;color:var(--text-muted);letter-spacing:.05em;background:var(--bg-tertiary)}
        .table td{padding:.75rem 1rem;font-size:.875rem;border-top:1px solid var(--border-color)}
        .table tbody tr:hover{background:var(--bg-hover)}
        .table-responsive{overflow-x:auto}
        /* Text utilities */
        .text-green{color:var(--accent-green)!important}
        .text-red{color:var(--accent-red)!important}
        .text-yellow{color:var(--accent-yellow)!important}
        .text-muted{color:var(--text-muted)!important}
        .text-center{text-align:center}
        .font-semibold{font-weight:600}
        .font-mono{font-family:var(--font-mono)}
        /* Layout utilities */
        .d-flex{display:flex}
        .align-items-center{align-items:center}
        .justify-content-between{justify-content:space-between}
        .gap-2{gap:.5rem}
        .gap-3{gap:.75rem}
        .flex-1{flex:1}
        .mb-3{margin-bottom:1rem}
        .py-4{padding-top:1.5rem;padding-bottom:1.5rem}
        /* Stat icon */
        .stat-icon{width:48px;height:48px;border-radius:var(--radius-md);display:flex;align-items:center;justify-content:center;font-size:1.2rem}
        .stat-icon.yellow{background:rgba(251,191,36,.15);color:var(--accent-yellow)}
        .stat-icon.green{background:rgba(0,208,156,.15);color:var(--accent-green)}
        .stat-icon.red{background:rgba(255,71,87,.15);color:var(--accent-red)}
        
        @media (max-width: 768px) {
            .balance-box { flex-direction: column; width: 100%; align-items: stretch; gap: 8px; margin-top: 15px; }
            .top-bar { flex-direction: column; align-items: stretch; }
            .main-content { padding: 16px; }
            .btn-primary { width: 100%; justify-content: center; }
            .balance-item { display: flex; justify-content: space-between; align-items: center; }
        }
        .d-portrait-only { display: none !important; }
        .d-landscape-only { display: none !important; }
        @media (orientation: portrait) {
            .d-portrait-only { display: inline-flex !important; margin-left: auto; }
            #topLeftArea { width: 100%; }
        }
        @media (orientation: landscape) {
            .d-landscape-only { display: block !important; }
            #topLeftArea { width: auto; }
        }
    </style>
</head>
<body>
<div class="app-container">
    <div class="sidebar-overlay" id="sidebarOverlay" onclick="document.getElementById('sidebar').classList.remove('active');this.classList.remove('active');"></div>
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <div class="sidebar-title">∫ <?= htmlspecialchars($siteName) ?></div>
        </div>
        <nav class="sidebar-nav">
            <a href="dashboard.php" class="nav-item <?= $currentPage==='dashboard'?'active':'' ?>"><i class="fas fa-th-large"></i> Dashboard</a>
            <a href="trade.php" class="nav-item <?= $currentPage==='trade'?'active':'' ?>"><i class="fas fa-chart-line"></i> Trade</a>
            <a href="history.php" class="nav-item <?= $currentPage==='history'?'active':'' ?>"><i class="fas fa-clock"></i> History</a>
            <a href="deposit.php" class="nav-item <?= $currentPage==='deposit'?'active':'' ?>"><i class="fas fa-plus-circle"></i> Deposit</a>
            <a href="withdraw.php" class="nav-item <?= $currentPage==='withdraw'?'active':'' ?>"><i class="fas fa-minus-circle"></i> Withdraw</a>
            <a href="profile.php" class="nav-item <?= $currentPage==='profile'?'active':'' ?>"><i class="fas fa-user"></i> Profile</a>
            <a href="logout.php" class="nav-item"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </nav>
    </aside>
    <main class="main-content">
        <div class="top-bar" id="topBar">
            <div class="d-flex align-items-center" id="topLeftArea">
                <button id="sidebarToggle" class="sidebar-toggle"><i class="fas fa-bars"></i></button>
                <h1 class="page-title"><?= htmlspecialchars($pageTitle ?? 'Dashboard') ?></h1>
                <a href="#" class="btn btn-primary d-portrait-only btn-full-display" style="padding: 6px 12px; font-size: 0.8rem; width: auto;">
                     Full Display
                </a>
            </div>
            
            <div class="d-landscape-only" style="flex: 1; text-align: center; margin: 0 15px;">
                <a href="#" class="btn btn-primary btn-full-display" style="width: auto;">
                     Full Display
                </a>
            </div>

            <div class="balance-box">
                <div class="balance-item">
                    <div class="balance-label">Demo Balance</div>
                    <div class="balance-value demo"><?= CURRENCY_SYMBOL ?><?= number_format($wallet['demo_balance'] ?? 10000, 2) ?></div>
                </div>
                <div class="balance-item">
                    <div class="balance-label">Real Balance</div>
                    <div class="balance-value live"><?= CURRENCY_SYMBOL ?><?= number_format(max(0, ($wallet['balance'] ?? 0) + ($wallet['bonus_balance'] ?? 0) - $pendingAmount), 2) ?></div>
                </div>
                <a href="trade.php" class="btn btn-primary"><i class="fas fa-play"></i> Trade Now</a>
            </div>
        </div>
