<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$host = "localhost";
$dbname = "liongate";
$user = "root";
$pass = "";

// Database Connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
if (!$conn) {
    http_response_code(500);
    exit("Database connection failed: " . mysqli_connect_error());
}
mysqli_set_charset($conn, "utf8mb4");

// Fetch User Data
$sql = "SELECT * FROM users WHERE id = ? LIMIT 1";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "i", $_SESSION['user_id']);
mysqli_stmt_execute($stmt);
$currentUser = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

if (!$currentUser) {
    session_destroy();
    header("Location: login.html");
    exit;
}

// TimeAgo Helper Function
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));
    }
}

// Gather all notifications
$allNotices = [];

// 1. Admin Notices
if (!empty($currentUser['admin_notice_title']) && $currentUser['admin_notice_status'] === 'active') {
    $allNotices[] = [
        'type' => 'notice', 
        'title' => $currentUser['admin_notice_title'], 
        'message' => $currentUser['admin_notice_message'],
        'time' => strtotime($currentUser['admin_notice_created_at']), 
        'time_display' => timeAgo($currentUser['admin_notice_created_at']),
        'icon' => 'megaphone', 'color' => 'amber'
    ];
}

// 2. Deposits (Up to 20 recent)
$depStmt = mysqli_prepare($conn, "SELECT amount, status, created_at FROM deposits WHERE user_id = ? ORDER BY created_at DESC LIMIT 20");
mysqli_stmt_bind_param($depStmt, "i", $_SESSION['user_id']);
mysqli_stmt_execute($depStmt);
$depRes = mysqli_stmt_get_result($depStmt);

while ($row = mysqli_fetch_assoc($depRes)) {
    $icon = $row['status'] === 'completed' ? 'check-circle' : 'clock';
    $color = $row['status'] === 'completed' ? 'green' : 'amber';
    $allNotices[] = [
        'type' => 'deposit', 
        'title' => 'Deposit ' . ucfirst($row['status']), 
        'message' => 'Your deposit request of $' . number_format($row['amount'], 2) . ' is currently ' . $row['status'] . '.',
        'time' => strtotime($row['created_at']), 
        'time_display' => timeAgo($row['created_at']),
        'icon' => $icon, 'color' => $color
    ];
}

// 3. Withdrawals (Up to 20 recent)
$witStmt = mysqli_prepare($conn, "SELECT amount, status, created_at FROM withdrawals WHERE user_id = ? ORDER BY created_at DESC LIMIT 20");
mysqli_stmt_bind_param($witStmt, "i", $_SESSION['user_id']);
mysqli_stmt_execute($witStmt);
$witRes = mysqli_stmt_get_result($witStmt);

while ($row = mysqli_fetch_assoc($witRes)) {
    $icon = $row['status'] === 'completed' ? 'check-circle' : 'clock';
    $color = $row['status'] === 'completed' ? 'blue' : 'amber';
    $allNotices[] = [
        'type' => 'withdrawal', 
        'title' => 'Withdrawal ' . ucfirst($row['status']), 
        'message' => 'Your withdrawal request for $' . number_format($row['amount'], 2) . ' is currently ' . $row['status'] . '.',
        'time' => strtotime($row['created_at']), 
        'time_display' => timeAgo($row['created_at']),
        'icon' => $icon, 'color' => $color
    ];
}

// Sort all notices from newest to oldest
usort($allNotices, function($a, $b) { 
    return $b['time'] - $a['time']; 
});

// Variables specifically required for the nav.php to render the dropdown properly
$notificationCount = count($allNotices);
$userNotices = array_slice($allNotices, 0, 5);
?>

<!DOCTYPE html>
<html lang="en" class="dark bg-slate-950">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notifications — Lion Gate Capitals</title>
    <link href="https://liongatecapitals.com/storage/app/public/photos/M896e8Qn8JaC9WWPKDgFzcVDFmrVdo7iXZu09ITL.png" rel="icon" type="image/x-icon">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
    tailwind.config = {
      darkMode: 'class',
      theme: {
        extend: {
          fontFamily: { sans: ['Inter','sans-serif'] },
          colors: { slate: { 950: '#020617', 900: '#0f172a', 850: '#0b1221', 800: '#1e293b', 750: '#1a2234', 700: '#334155' } },
        }
      }
    }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js" defer></script>
    <script src="https://unpkg.com/lucide@latest/dist/umd/lucide.js"></script>
    <style>
      [x-cloak] { display: none !important; }
      .scroll-thin::-webkit-scrollbar { width: 4px; height: 4px; }
      .scroll-thin::-webkit-scrollbar-thumb { background: #475569; border-radius: 99px; }
      .glass-effect { background: rgba(30, 41, 59, 0.7); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); }
    </style>
</head>

<body x-data="{ darkMode: localStorage.theme === 'dark' || !localStorage.theme, sidebarOpen: false }" 
      x-init="$watch('darkMode', val => { localStorage.setItem('theme', val ? 'dark' : 'light'); document.documentElement.classList.toggle('dark', val); })" 
      :class="{ dark: darkMode }" class="dark bg-slate-950 text-slate-100 font-sans antialiased" x-cloak>

<!-- NAVBAR -->
<?php include "include/nav.php"?>

<div class="flex min-h-screen">
  <!-- SIDEBAR -->
  <?php include "include/sidebar.php"?>

  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8">
    <div class="max-w-3xl mx-auto px-4 sm:px-6 py-8">

      <div class="mb-8">
        <h1 class="text-2xl sm:text-3xl font-bold text-slate-900 dark:text-white tracking-tight">Your Notifications</h1>
        <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Stay updated on your account activity and announcements.</p>
      </div>

      <div class="bg-white dark:bg-slate-900 rounded-2xl shadow-xl border border-slate-200 dark:border-slate-800 overflow-hidden">
        
        <?php if (empty($allNotices)): ?>
        <div class="p-12 text-center">
            <div class="w-16 h-16 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mx-auto mb-4">
                <i data-lucide="bell-off" class="w-8 h-8 text-slate-400"></i>
            </div>
            <h3 class="text-lg font-bold text-slate-900 dark:text-white mb-1">You're all caught up!</h3>
            <p class="text-slate-500 dark:text-slate-400 text-sm">There are no new notifications to display right now.</p>
        </div>
        <?php else: ?>
        <div class="divide-y divide-slate-100 dark:divide-slate-800">
            <?php foreach ($allNotices as $notif): 
                // Determine Colors
                $iconColors = [
                  'amber' => 'bg-amber-100 text-amber-600 dark:bg-amber-500/10 dark:text-amber-400',
                  'green' => 'bg-emerald-100 text-emerald-600 dark:bg-emerald-500/10 dark:text-emerald-400',
                  'blue' => 'bg-blue-100 text-blue-600 dark:bg-blue-500/10 dark:text-blue-400',
                  'red' => 'bg-rose-100 text-rose-600 dark:bg-rose-500/10 dark:text-rose-400'
                ];
                $colorClass = $iconColors[$notif['color']] ?? $iconColors['blue'];
            ?>
            <div class="flex items-start gap-4 p-5 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors">
                <div class="shrink-0 w-12 h-12 rounded-2xl <?= $colorClass ?> flex items-center justify-center shadow-inner">
                    <i data-lucide="<?= htmlspecialchars($notif['icon'], ENT_QUOTES, 'UTF-8') ?>" class="w-6 h-6"></i>
                </div>
                <div class="min-w-0 flex-1 pt-1">
                    <div class="flex justify-between items-start gap-4 mb-1">
                        <h4 class="text-base font-semibold text-slate-900 dark:text-white">
                            <?= htmlspecialchars($notif['title'], ENT_QUOTES, 'UTF-8') ?>
                        </h4>
                        <span class="text-[11px] font-medium text-slate-400 dark:text-slate-500 shrink-0 flex items-center gap-1.5 bg-slate-100 dark:bg-slate-800 px-2 py-1 rounded-lg">
                            <i data-lucide="clock" class="w-3 h-3"></i> <?= htmlspecialchars($notif['time_display'], ENT_QUOTES, 'UTF-8') ?>
                        </span>
                    </div>
                    <p class="text-sm text-slate-600 dark:text-slate-400 leading-relaxed">
                        <?= htmlspecialchars($notif['message'], ENT_QUOTES, 'UTF-8') ?>
                    </p>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

      </div>

    </div>
  </main>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => { 
        if (typeof lucide !== 'undefined') lucide.createIcons(); 
    });
</script>
</body>
</html>