<?php
// Establish connection using your standard path
require_once "include/db.php"; 

// Fallback for safety if the main page hasn't defined the user yet
if (!isset($currentUser)) {
    $currentUser = [
        'full_name' => 'User', 
        'balance' => 0, 
        'theme' => '#0ea5e9',
        'profile_photo' => ''
    ];
}

// ═══════════════════════════════════════════════════════════════
// THEME & PERSISTENCE CONFIG
// ═══════════════════════════════════════════════════════════════
$db_theme_color = !empty($currentUser['theme']) ? $currentUser['theme'] : '#0ea5e9';

// ═══════════════════════════════════════════════════════════════
// PROFILE PHOTO HELPER
// ═══════════════════════════════════════════════════════════════
function getProfilePhoto($user, $size = 32) {
    if (!empty($user['profile_photo']) && file_exists($user['profile_photo'])) {
        return '<img src="' . htmlspecialchars($user['profile_photo']) . '" alt="Profile" class="w-' . $size . ' h-' . $size . ' rounded-full object-cover border-2 border-white/20 shadow-lg">';
    }
    $initials = strtoupper(substr($user['full_name'] ?? 'U', 0, 1));
    if (!empty($user['full_name'])) {
        $parts = explode(' ', $user['full_name']);
        $initials = strtoupper(substr($parts[0], 0, 1) . (isset($parts[1]) ? substr($parts[1], 0, 1) : ''));
    }
    return '<div class="w-' . $size . ' h-' . $size . ' rounded-full bg-theme flex items-center justify-center text-white text-sm font-bold shadow-lg">' . $initials . '</div>';
}

// ═══════════════════════════════════════════════════════════════
// CRITICAL SAFETY FUNCTIONS
// ═══════════════════════════════════════════════════════════════
if (!function_exists('timeAgo')) {
    function timeAgo($datetime) {
        $diff = time() - strtotime($datetime);
        if ($diff < 60) return 'Just now';
        if ($diff < 3600) return floor($diff/60) . 'm ago';
        if ($diff < 86400) return floor($diff/3600) . 'h ago';
        return date('M d, Y', strtotime($datetime));
    }
}

if (!function_exists('e')) {
    function e($v) {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

// ═══════════════════════════════════════════════════════════════
// NOTIFICATION ENGINE (Native MySQLi)
// ═══════════════════════════════════════════════════════════════
$userNotices = [];
$notificationCount = 0;

if (isset($_SESSION['user_id'])) {
    $nav_userId = intval($_SESSION['user_id']);
    
    // 1. Admin Notices from User Table
    if (!empty($currentUser['admin_notice_title']) && ($currentUser['admin_notice_status'] ?? '') === 'active') {
        $userNotices[] = [
            'type' => 'notice', 
            'title' => $currentUser['admin_notice_title'], 
            'message' => $currentUser['admin_notice_message'],
            'time' => strtotime($currentUser['admin_notice_created_at'] ?? 'now'), 
            'time_display' => timeAgo($currentUser['admin_notice_created_at'] ?? 'now'),
            'icon' => 'megaphone', 'color' => 'amber',
            'url' => '#'
        ];
    }

    // 2. Fetch Deposits/Withdrawals
    $depQ = mysqli_query($conn, "SELECT amount, status, created_at FROM deposits WHERE user_id = $nav_userId ORDER BY created_at DESC LIMIT 3");
    if ($depQ) {
        while ($r = mysqli_fetch_assoc($depQ)) {
            $userNotices[] = [
                'type' => 'deposit', 
                'title' => 'Deposit ' . ucfirst($r['status']), 
                'message' => 'Your deposit of $' . number_format($r['amount'], 2) . ' is ' . $r['status'] . '.',
                'time' => strtotime($r['created_at']), 
                'time_display' => timeAgo($r['created_at']),
                'icon' => $r['status'] === 'completed' ? 'check-circle' : 'clock', 
                'color' => $r['status'] === 'completed' ? 'green' : 'amber',
                'url' => 'accounthistory.php'
            ];
        }
    }
    
    $witQ = mysqli_query($conn, "SELECT amount, status, created_at FROM withdrawals WHERE user_id = $nav_userId ORDER BY created_at DESC LIMIT 3");
    if ($witQ) {
        while ($r = mysqli_fetch_assoc($witQ)) {
            $userNotices[] = [
                'type' => 'withdrawal', 
                'title' => 'Withdrawal ' . ucfirst($r['status']), 
                'message' => 'Your withdrawal of $' . number_format($r['amount'], 2) . ' is ' . $r['status'] . '.',
                'time' => strtotime($r['created_at']), 
                'time_display' => timeAgo($r['created_at']),
                'icon' => $r['status'] === 'completed' ? 'check-circle' : 'clock', 
                'color' => $r['status'] === 'completed' ? 'blue' : 'amber',
                'url' => 'accounthistory.php'
            ];
        }
    }
    
    // Sort and slice
    usort($userNotices, function($a, $b) { return $b['time'] - $a['time']; });
    $notificationCount = count($userNotices);
    $userNotices = array_slice($userNotices, 0, 5);
}
?>

<style>
    :root {
        --primary-theme: <?php echo $db_theme_color; ?>;
    }
    .text-theme { color: var(--primary-theme) !important; }
    .bg-theme { background-color: var(--primary-theme) !important; }
    .border-theme { border-color: var(--primary-theme) !important; }
    .shadow-theme { box-shadow: 0 10px 15px -3px rgba(var(--primary-theme), 0.1); }
</style>

<nav x-data="{
        navBal: <?= isset($currentUser['balance']) ? (float)$currentUser['balance'] : 0 ?>,
        hideBalance: localStorage.getItem('hideBalance') === 'true',
        darkMode: localStorage.getItem('darkMode') === 'dark' || (!('darkMode' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches),
        
        init() {
            if (this.darkMode) {
                document.documentElement.classList.add('dark');
            } else {
                document.documentElement.classList.remove('dark');
            }
        },
        toggleDarkMode() {
            this.darkMode = !this.darkMode;
            localStorage.setItem('darkMode', this.darkMode ? 'dark' : 'light');
            if (this.darkMode) {
                document.documentElement.classList.add('dark');
            } else {
                document.documentElement.classList.remove('dark');
            }
        },
        toggleBalance() {
            this.hideBalance = !this.hideBalance;
            localStorage.setItem('hideBalance', this.hideBalance);
            window.dispatchEvent(new CustomEvent('balance-toggled', { detail: { hidden: this.hideBalance } }));
        },
        get formattedBal() {
            return this.navBal.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }
     }"
     @update-balance.window="navBal = $event.detail.balance"
     @balance-toggled.window="hideBalance = $event.detail.hidden"
     class="sticky top-0 z-50 bg-white dark:bg-[#0b111a] glass-effect border-b border-slate-200 dark:border-slate-800/50 transition-all duration-300">
     
  <div class="max-w-screen-2xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="flex items-center justify-between h-16 gap-4">

      <!-- Logo -->
      <a href="dashboard.php" class="flex items-center gap-3 shrink-0 group">
        <div class="relative">
          <img src="logo.png" class="h-9 w-auto transition-transform duration-300 group-hover:scale-105" alt="Logo">
          <div class="absolute inset-0 bg-blue-500/20 blur-xl rounded-full opacity-0 group-hover:opacity-100 transition-opacity"></div>
        </div>
        <div class="hidden sm:block">
          <div class="text-sm font-bold text-slate-900 dark:text-white leading-tight tracking-tight">Theinteractivebrokers</div>
          <div class="text-[10px] text-slate-500 font-medium tracking-wide">PROFESSIONAL TRADING</div>
        </div>
      </a>

      <!-- Live Ticker -->
      <div class="hidden lg:flex items-center gap-6 text-xs" x-data="cryptoPrices()" x-init="fetchPrices()">
        <div class="flex items-center gap-2 px-3 py-1.5 rounded-full bg-slate-100 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700/50">
          <span class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
          <span class="text-slate-500 dark:text-slate-400 font-medium">LIVE</span>
        </div>
        <div class="flex items-center gap-4">
          <div class="flex items-center gap-2">
            <span class="text-slate-500 font-medium">BTC</span>
            <span class="font-mono font-semibold" :class="btcChange >= 0 ? 'text-emerald-500' : 'text-rose-500'" x-text="btcPrice ? '$'+btcPrice.toLocaleString() : '—'"></span>
          </div>
          <div class="flex items-center gap-2">
            <span class="text-slate-500 font-medium">ETH</span>
            <span class="font-mono font-semibold" :class="ethChange >= 0 ? 'text-emerald-500' : 'text-rose-500'" x-text="ethPrice ? '$'+ethPrice.toLocaleString() : '—'"></span>
          </div>
        </div>
      </div>

      <!-- Right cluster -->
      <div class="flex items-center gap-2 shrink-0">
        
        <!-- Balance Quick View -->
        <div class="hidden md:flex items-center gap-3 px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-800/50 border border-slate-200 dark:border-slate-700/50 hover:border-slate-300 dark:hover:border-slate-600 transition-colors cursor-pointer"
             @click="window.location.href='accounthistory.php'">
          <div class="text-right">
            <div class="text-[10px] text-slate-500 dark:text-slate-400 font-medium uppercase tracking-wider">Balance</div>
            <div class="text-sm font-bold text-theme" :class="hideBalance ? 'blur-sm' : ''">
              $<span x-text="hideBalance ? '••••••' : formattedBal"><?= number_format((float)($currentUser['balance'] ?? 0), 2) ?></span>
            </div>
          </div>
          <button @click.stop="toggleBalance()" class="p-1.5 rounded-lg hover:bg-slate-200 dark:hover:bg-slate-700/50 transition-colors">
            <i data-lucide="eye" x-show="!hideBalance" class="w-4 h-4 text-slate-500 dark:text-slate-400"></i>
            <i data-lucide="eye-off" x-show="hideBalance" class="w-4 h-4 text-slate-400 dark:text-slate-500" x-cloak></i>
          </button>
        </div>

        <!-- Notifications -->
        <div class="relative" x-data="{ notifOpen: false }">
          <button @click="notifOpen = !notifOpen"
                  class="relative p-2.5 text-slate-500 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800/50 rounded-xl transition-all">
            <i data-lucide="bell" class="w-5 h-5"></i>
            <?php if ($notificationCount > 0): ?>
            <span class="absolute -top-1 -right-1 min-w-[18px] h-[18px] flex items-center justify-center bg-rose-500 text-white text-[10px] font-bold rounded-full px-1">
              <?= $notificationCount ?>
            </span>
            <?php endif; ?>
          </button>
          
          <div x-show="notifOpen" @click.away="notifOpen = false" x-cloak
               x-transition:enter="transition ease-out duration-200" x-transition:enter-start="opacity-0 scale-95 translate-y-2"
               class="absolute right-0 top-full mt-3 w-80 max-w-[90vw] bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-2xl shadow-2xl z-50 overflow-hidden">
            <div class="px-4 py-3 border-b border-slate-200 dark:border-slate-800 flex items-center justify-between bg-slate-50 dark:bg-slate-800/30">
              <span class="text-sm font-semibold text-slate-900 dark:text-white">Notifications</span>
            </div>
            
            <div class="max-h-64 overflow-y-auto">
              <?php if (empty($userNotices)): ?>
              <div class="px-4 py-8 text-center text-slate-500"><p class="text-sm">No notifications</p></div>
              <?php else: ?>
              <div class="divide-y divide-slate-100 dark:divide-slate-800">
              <?php foreach ($userNotices as $notif): ?>
              <a href="<?= e($notif['url']) ?>" class="flex items-start gap-3 px-4 py-3 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors">
                <span class="shrink-0 w-8 h-8 rounded-lg flex items-center justify-center mt-1 bg-slate-100 dark:bg-slate-800">
                  <i data-lucide="<?= e($notif['icon']) ?>" class="w-4 h-4 text-theme"></i>
                </span>
                <div>
                  <p class="text-xs font-semibold text-slate-900 dark:text-slate-200"><?= e($notif['title']) ?></p>
                  <p class="text-[11px] text-slate-500 mt-0.5 line-clamp-2"><?= e($notif['message']) ?></p>
                  <p class="text-[10px] text-slate-400 mt-1"><?= e($notif['time_display']) ?></p>
                </div>
              </a>
              <?php endforeach; ?>
              </div>
              <?php endif; ?>
            </div>
          </div>
        </div>

        <!-- Dark mode toggle -->
        <button @click="toggleDarkMode()"
                class="p-2.5 text-slate-500 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800/50 rounded-xl transition-all">
          <i data-lucide="sun" x-show="!darkMode" class="w-5 h-5"></i>
          <i data-lucide="moon" x-show="darkMode" class="w-5 h-5" x-cloak></i>
        </button>

        <!-- Profile -->
        <div class="relative" x-data="{ profileOpen: false }">
          <button @click="profileOpen = !profileOpen" class="flex items-center gap-2 p-1.5 hover:bg-slate-100 dark:hover:bg-slate-800/50 rounded-xl transition-all">
            <?= getProfilePhoto($currentUser, 8) ?>
            <i data-lucide="chevron-down" class="w-4 h-4 text-slate-500 transition-transform" :class="profileOpen ? 'rotate-180' : ''"></i>
          </button>
          
          <div x-show="profileOpen" @click.away="profileOpen = false" x-cloak
               x-transition:enter="transition ease-out duration-200"
               class="absolute right-0 top-full mt-3 w-64 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-2xl shadow-2xl z-50 overflow-hidden">
            <div class="p-4 border-b border-slate-200 dark:border-slate-800 bg-slate-50 dark:bg-slate-800/30">
              <div class="flex items-center gap-3">
                <?= getProfilePhoto($currentUser, 10) ?>
                <div>
                  <div class="text-sm font-semibold text-slate-900 dark:text-white"><?= e($currentUser['full_name'] ?? 'User') ?></div>
                  <div class="text-xs text-theme font-bold mt-1">$<?= number_format((float)($currentUser['balance'] ?? 0), 2) ?></div>
                </div>
              </div>
            </div>
            <div class="p-2">
              <a href="ProfileSettings.php" class="flex items-center gap-3 px-3 py-2.5 text-sm text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800/50 rounded-xl transition-colors">
                <i data-lucide="settings" class="w-4 h-4"></i>Settings
              </a>
              <form method="POST" action="logout.php">
                <button type="submit" class="w-full flex items-center gap-3 px-3 py-2.5 text-sm text-rose-500 hover:bg-rose-50 dark:hover:bg-rose-500/10 rounded-xl transition-colors text-left">
                  <i data-lucide="log-out" class="w-4 h-4"></i>Sign Out
                </button>
              </form>
            </div>
          </div>
        </div>

        <!-- Mobile hamburger -->
        <button @click="sidebarOpen = !sidebarOpen"
                class="md:hidden p-2.5 text-slate-500 dark:text-slate-400 hover:bg-slate-100 dark:hover:bg-slate-800/50 rounded-xl transition-all">
          <i data-lucide="menu" x-show="!sidebarOpen" class="w-5 h-5"></i>
          <i data-lucide="x" x-show="sidebarOpen" class="w-5 h-5" x-cloak></i>
        </button>
      </div>
    </div>
  </div>
</nav>

<script>
document.addEventListener('alpine:init', () => {
    if (!Alpine.data('cryptoPrices')) {
        Alpine.data('cryptoPrices', () => ({
            btcPrice: null, ethPrice: null, btcChange: 0, ethChange: 0,
            async fetchPrices() {
                try {
                    const r = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum&vs_currencies=usd&include_24hr_change=true');
                    const d = await r.json();
                    this.btcPrice = Math.round(d.bitcoin.usd); 
                    this.ethPrice = Math.round(d.ethereum.usd);
                    this.btcChange = d.bitcoin.usd_24h_change || 0; 
                    this.ethChange = d.ethereum.usd_24h_change || 0;
                } catch (e) {}
                setTimeout(() => this.fetchPrices(), 30000);
            }
        }));
    }
});
</script>