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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ----------------------
// AUTH CHECK
// ----------------------
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$username = $_SESSION['admin_username'] ?? 'Admin';
$userId = $_SESSION['admin_user_id'] ?? 0;
$profileImage = '';

if ($userId) {
    try {
        $userStmt = $pdo->prepare("
            SELECT profile_image
            FROM admin_users
            WHERE id = ?
            LIMIT 1
        ");

        $userStmt->execute([$userId]);
        $userRow = $userStmt->fetch(PDO::FETCH_ASSOC);

        $profileImage = $userRow['profile_image'] ?? '';
    } catch (PDOException $e) {
        $profileImage = '';
    }
}

// ----------------------
// UNREAD MESSAGES
// ----------------------
$unreadCount = 0;

if ($userId) {
    $stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM messages 
        WHERE recipient_id = ? 
        AND is_read = 0
    ");

    $stmt->execute([$userId]);

    $unreadCount = (int)$stmt->fetchColumn();
}

// ----------------------
// NEW CONTACT ENQUIRIES
// ----------------------
$newContactEnquiryCount = 0;

try {
    $contactStmt = $pdo->prepare("
        SELECT COUNT(*)
        FROM contact_enquiries
        WHERE status = 'new'
    ");

    $contactStmt->execute();

    $newContactEnquiryCount = (int)$contactStmt->fetchColumn();
} catch (PDOException $e) {
    $newContactEnquiryCount = 0;
}

// ----------------------
// ACTIVE NAV HELPER
// ----------------------
$currentPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

function isActiveAdminLink(string $path, string $currentPath): string
{
    return str_starts_with($currentPath, $path) ? 'active' : '';
}

require_once __DIR__ . '/includes/header.php';
?>

<div class="d-flex">

    <!-- SIDEBAR -->
<nav class="sidebar text-white d-flex flex-column">

    <div class="sidebar-brand">
        <a href="/admin/dashboard">
            <img src="/admin/img/thrillsense-sm.png" style="width: 110px" alt="ThrillSense">
        </a>
    </div>

    <ul class="nav flex-column">

        <li class="nav-item mb-1">
            <a href="/admin/dashboard" class="nav-link <?= isActiveAdminLink('/admin/dashboard', $currentPath) ?>">
                <span class="admin-nav-label">
                    <i class="bi bi-speedometer2"></i>
                    <span>Dashboard</span>
                </span>
            </a>
        </li>

        <li class="nav-item mb-1">
            <a href="/admin/messages" class="nav-link <?= isActiveAdminLink('/admin/messages', $currentPath) ?>">
                <span class="admin-nav-label">
                    <i class="bi bi-inbox"></i>
                    <span>Messages</span>
                </span>

                <?php if ($unreadCount > 0): ?>
                    <span class="admin-nav-badge"><?= (int)$unreadCount ?></span>
                <?php endif; ?>
            </a>
        </li>

        <li class="nav-item mb-1">
            <a href="/admin/contact-enquiries" class="nav-link <?= isActiveAdminLink('/admin/contact-enquiries', $currentPath) ?>">
                <span class="admin-nav-label">
                    <i class="bi bi-envelope-paper"></i>
                    <span>Enquiries</span>
                </span>

                <?php if ($newContactEnquiryCount > 0): ?>
                    <span class="admin-nav-badge"><?= (int)$newContactEnquiryCount ?></span>
                <?php endif; ?>
            </a>
        </li>
        
                <li class="nav-item mb-1">
            <a href="/admin/upload-media" class="nav-link <?= isActiveAdminLink('/admin/upload-media', $currentPath) ?>">
                <span class="admin-nav-label">
                <i class="bi bi-file-earmark-image"></i>
                    <span>Media</span>
                </span>
            </a>
        </li>

        <li class="nav-item mb-1">
            <a href="/admin/posts" class="nav-link <?= isActiveAdminLink('/admin/posts', $currentPath) ?>">
                <span class="admin-nav-label">
                    <i class="bi bi-file-earmark-text"></i>
                    <span>Posts</span>
                </span>
            </a>
        </li>

        <li class="nav-item mb-1">
            <a href="/admin/parks" class="nav-link <?= isActiveAdminLink('/admin/parks', $currentPath) ?>">
                <span class="admin-nav-label">
                    <i class="bi bi-map"></i>
                    <span>Parks</span>
                </span>
            </a>
        </li>

        <li class="nav-item mb-1">
            <a href="/admin/rides" class="nav-link <?= isActiveAdminLink('/admin/rides', $currentPath) ?>">
                <span class="admin-nav-label">
                    <i class="bi bi-stars"></i>
                    <span>Rides</span>
                </span>
            </a>
        </li>

        <li class="nav-item mb-1">
            <a href="/admin/tags" class="nav-link <?= isActiveAdminLink('/admin/tags', $currentPath) ?>">
                <span class="admin-nav-label">
                    <i class="bi bi-tags"></i>
                    <span>Tags</span>
                </span>
            </a>
        </li>


        <li class="nav-item mb-1">
            <a href="/admin/users" class="nav-link <?= isActiveAdminLink('/admin/users', $currentPath) ?>">
                <span class="admin-nav-label">
                    <i class="bi bi-people"></i>
                    <span>Users</span>
                </span>
            </a>
        </li>

    </ul>

</nav>

    <!-- RIGHT SIDE -->
    <div class="flex-grow-1 d-flex flex-column">

        <!-- TOPBAR -->
        <div class="topbar d-flex justify-content-between align-items-center p-3 bg-white border-bottom">

            <!-- LEFT -->
            <div></div>

            <!-- RIGHT -->
            <div class="d-flex align-items-center gap-3">

                <!-- SEARCH -->
                <form 
                    class="d-none d-md-block"
                    method="GET"
                    action="/admin/posts"
                >
                    <input 
                        type="text" 
                        name="search"
                        class="form-control form-control-sm"
                        placeholder="Search posts..."
                        style="width: 220px;"
                    >
                </form>

                <!-- NEW POST BUTTON -->
                <a 
                    href="/admin/create-post"
                    class="btn btn-sm btn-dark admin-topbar-button"
                >
                    + New Post
                </a>

                <!-- INBOX / NOTIFICATIONS -->
                <a 
                    href="/admin/messages"
                    class="position-relative text-dark text-decoration-none"
                    style="font-size: 1.15rem;"
                    title="Inbox"
                >
                    <i class="bi bi-bell"></i>

                    <?php if ($unreadCount > 0 || $newContactEnquiryCount > 0): ?>
                        <span 
                            style="
                                position:absolute;
                                top:8px;
                                right:-2px;
                                width:8px;
                                height:8px;
                                background:#dc3545;
                                border-radius:50%;
                                display:block;
                            "
                        ></span>
                    <?php endif; ?>
                </a>

<!-- USER MENU -->
<div class="dropdown admin-user-menu">
    <button
        class="admin-user-menu-button dropdown-toggle"
        type="button"
        id="adminUserMenu"
        data-bs-toggle="dropdown"
        aria-expanded="false"
    >
        <?php if (!empty($profileImage)): ?>
            <img
                src="/<?= htmlspecialchars(ltrim($profileImage, '/'), ENT_QUOTES, 'UTF-8') ?>"
                alt="<?= htmlspecialchars($username, ENT_QUOTES, 'UTF-8') ?>"
                class="admin-user-menu-avatar-img"
            >
        <?php else: ?>
            <span class="admin-user-menu-avatar">
                <?= htmlspecialchars(strtoupper(substr($username, 0, 1)), ENT_QUOTES, 'UTF-8') ?>
            </span>
        <?php endif; ?>

        <span class="admin-user-menu-name d-none d-md-inline">
            <?= htmlspecialchars($username, ENT_QUOTES, 'UTF-8') ?>
        </span>
    </button>

    <ul class="dropdown-menu dropdown-menu-end admin-user-dropdown" aria-labelledby="adminUserMenu">
        <li class="dropdown-header">
            Signed in as<br>
            <strong><?= htmlspecialchars($username, ENT_QUOTES, 'UTF-8') ?></strong>
        </li>

        <li><hr class="dropdown-divider"></li>

        <li>
            <a class="dropdown-item" href="/admin/edit-user?id=<?= (int)$userId ?>">
                <i class="bi bi-person me-2"></i>
                Profile
            </a>
        </li>

        <li>
            <a class="dropdown-item" href="/admin/users">
                <i class="bi bi-people me-2"></i>
                Users
            </a>
        </li>

        <li><hr class="dropdown-divider"></li>

        <li>
            <a class="dropdown-item text-danger" href="/admin/logout">
                <i class="bi bi-box-arrow-right me-2"></i>
                Logout
            </a>
        </li>
    </ul>
</div>

            </div>

        </div>

        <!-- MAIN CONTENT -->
        <main class="p-4 overflow-auto bg-light">

            <!-- Your page content goes here -->