<?php
// This header contains all necessary logic for the dashboard.
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/helpers.php'; // Ensures format_price() is always available

// Security check: Ensure a user is logged in and their role is 'customer'.
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'customer') {
    header("Location: ../login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    session_destroy();
    header("Location: ../login.php?error=invalid_session");
    exit();
}

// Fetch global site settings
$settings_result = $conn->query("SELECT * FROM site_settings");
$site_settings = [];
if ($settings_result) {
    while ($row = $settings_result->fetch_assoc()) {
        $site_settings[$row['setting_name']] = $row['setting_value'];
    }
}

// Fetch unread message count
$unread_messages_count = 0;
$stmt_msg = $conn->prepare("SELECT COUNT(m.id) as total FROM messages m JOIN conversations c ON m.conversation_id = c.id WHERE c.user_id = ? AND m.sender_type = 'admin' AND m.is_read = 0");
$stmt_msg->bind_param("i", $user_id);
$stmt_msg->execute();
$unread_messages_count = $stmt_msg->get_result()->fetch_assoc()['total'];
$stmt_msg->close();

// Fetch currency data for the switcher
$currencies_result = $conn->query("SELECT code, symbol FROM currencies WHERE is_active = 1 ORDER BY code ASC");
$available_currencies = $currencies_result->fetch_all(MYSQLI_ASSOC);
$current_currency_code = $_SESSION['currency'] ?? ($site_settings['site_base_currency'] ?? 'PHP');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Dashboard - <?php echo htmlspecialchars($site_settings['site_name'] ?? ''); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link rel="stylesheet" href="/css/style.css">
    
    <style>
        .avatar-initial { display: inline-block; width: 32px; height: 32px; line-height: 32px; text-align: center; border-radius: 50%; background-color: var(--bs-secondary-bg-subtle); color: var(--bs-emphasis-color); font-weight: bold; }
        main { background-color: var(--bs-body-bg); }
        .user-menu .dropdown-menu { width: 280px; }
    </style>
</head>
<body>

<script>
    (() => {
        'use strict';
        const getStoredTheme = () => localStorage.getItem('theme');
        const setStoredTheme = theme => localStorage.setItem('theme', theme);
        const getPreferredTheme = () => {
            const storedTheme = getStoredTheme();
            if (storedTheme) return storedTheme;
            return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
        };
        const setTheme = theme => {
            document.documentElement.setAttribute('data-bs-theme', theme);
        };
        setTheme(getPreferredTheme());
    })();
</script>

<nav class="navbar sticky-top shadow-sm border-bottom">
  <div class="container-fluid">
    <a class="navbar-brand d-flex align-items-center" href="../index.php">
        <?php if (!empty($site_settings['site_logo_url'])): ?>
            <img src="../<?php echo htmlspecialchars($site_settings['site_logo_url']); ?>" alt="Logo" style="max-height: 40px; margin-right: 10px;">
        <?php endif; ?>
    </a>
    <div class="d-flex align-items-center">
        <div class="dropdown me-2">
            <a class="btn btn-sm btn-outline-secondary dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown"><?php echo htmlspecialchars($current_currency_code); ?></a>
            <ul class="dropdown-menu dropdown-menu-end">
                <?php foreach ($available_currencies as $currency): ?>
                    <li><a class="dropdown-item" href="../set-currency.php?currency=<?php echo htmlspecialchars($currency['code']); ?>"><?php echo htmlspecialchars($currency['symbol']); ?> <?php echo htmlspecialchars($currency['code']); ?></a></li>
                <?php endforeach; ?>
            </ul>
        </div>
        
        <button class="btn btn-link nav-link me-2" id="theme-toggler" type="button">
            <i class="bi bi-sun-fill theme-icon-sun d-none"></i>
            <i class="bi bi-moon-stars-fill theme-icon-moon d-none"></i>
        </button>

        <div class="dropdown user-menu">
            <a href="#" class="d-flex align-items-center text-decoration-none dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                <?php if (!empty($user['profile_image_url'])): ?>
                    <img src="../<?php echo htmlspecialchars($user['profile_image_url']); ?>" alt="Profile" width="32" height="32" class="rounded-circle me-2" style="object-fit: cover;">
                <?php else: ?>
                    <div class="avatar-initial me-2"><?php echo strtoupper(substr($user['full_name'], 0, 1)); ?></div>
                <?php endif; ?>
                <strong class="d-none d-sm-inline"><?php echo htmlspecialchars($user['full_name']); ?></strong>
            </a>
            <ul class="dropdown-menu dropdown-menu-end text-small shadow p-2">
                <li><h6 class="dropdown-header">Main Menu</h6></li>
                <li><a class="dropdown-item rounded" href="index.php"><i class="bi bi-grid-1x2-fill me-2"></i> Dashboard</a></li>
                <li><a class="dropdown-item rounded d-flex justify-content-between align-items-center" href="messages.php"><span><i class="bi bi-chat-dots-fill me-2"></i> Messages</span> <?php if($unread_messages_count > 0) echo '<span class="badge bg-danger rounded-pill">'.$unread_messages_count.'</span>'; ?></a></li>
                <li><hr class="dropdown-divider"></li>
                <li><h6 class="dropdown-header">My Bookings</h6></li>
                <li><a class="dropdown-item rounded" href="my-tour-bookings.php"><i class="bi bi-card-list me-2"></i> Tours & Services</a></li>
                <li><a class="dropdown-item rounded" href="my-hotel-bookings.php"><i class="bi bi-building me-2"></i> Hotels</a></li>
                <li><a class="dropdown-item rounded" href="my-flight-bookings.php"><i class="bi bi-airplane me-2"></i> Flights</a></li>
                <li><a class="dropdown-item rounded" href="my-ferry-bookings.php"><i class="bi bi-tsunami me-2"></i> Ferries</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><h6 class="dropdown-header">My Account</h6></li>
                <li><a class="dropdown-item rounded" href="edit-profile.php"><i class="bi bi-person-fill-gear me-2"></i> Edit Profile</a></li>
                <li><a class="dropdown-item rounded" href="my-reviews.php"><i class="bi bi-star-fill me-2"></i> My Reviews</a></li>
                <li><a class="dropdown-item rounded" href="affiliate.php"><i class="bi bi-people-fill me-2"></i> Affiliate Program</a></li>
                <li><a class="dropdown-item rounded" href="top-up.php"><i class="bi bi-wallet2 me-2"></i> Top-Up Wallet</a></li>
                <li><a class="dropdown-item rounded" href="transactions.php"><i class="bi bi-clock-history me-2"></i> Transactions</a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item rounded text-danger" href="../logout.php"><i class="bi bi-box-arrow-right me-2"></i> Log Out</a></li>
            </ul>
        </div>
    </div>
  </div>
</nav>

<main class="container py-4">

<script>
    document.addEventListener('DOMContentLoaded', () => {
        const getStoredTheme = () => localStorage.getItem('theme');
        const themeToggler = document.getElementById('theme-toggler');
        const sunIcon = document.querySelector('.theme-icon-sun');
        const moonIcon = document.querySelector('.theme-icon-moon');
        const updateIcon = (theme) => {
            if (theme === 'dark') {
                sunIcon.classList.remove('d-none');
                moonIcon.classList.add('d-none');
            } else {
                sunIcon.classList.add('d-none');
                moonIcon.classList.remove('d-none');
            }
        };
        themeToggler.addEventListener('click', () => {
            const currentTheme = getStoredTheme() || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light');
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';
            localStorage.setItem('theme', newTheme);
            document.documentElement.setAttribute('data-bs-theme', newTheme);
            updateIcon(newTheme);
        });
        updateIcon(getStoredTheme() || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'));
    });
</script>
