<?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();
}

// ----------------------
// REMEMBER ME HELPERS
// ----------------------
function clearAdminRememberCookie(): void
{
    setcookie('ts_admin_remember', '', [
        'expires' => time() - 3600,
        'path' => '/admin',
        'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
        'httponly' => true,
        'samesite' => 'Lax'
    ]);
}

function attemptRememberMeLogin(PDO $pdo): void
{
    if (
        isset($_SESSION['admin_logged_in']) &&
        $_SESSION['admin_logged_in'] === true
    ) {
        return;
    }

    if (empty($_COOKIE['ts_admin_remember'])) {
        return;
    }

    $parts = explode(':', $_COOKIE['ts_admin_remember']);

    if (count($parts) !== 2) {
        clearAdminRememberCookie();
        return;
    }

    [$selector, $validator] = $parts;

    if (
        !ctype_xdigit($selector) ||
        !ctype_xdigit($validator) ||
        strlen($selector) !== 24 ||
        strlen($validator) !== 64
    ) {
        clearAdminRememberCookie();
        return;
    }

    try {
        $stmt = $pdo->prepare("
            SELECT
                art.id AS token_id,
                art.validator_hash,
                art.expires_at,
                au.id AS user_id,
                au.username,
                au.role,
                au.is_locked
            FROM admin_remember_tokens art
            INNER JOIN admin_users au
                ON au.id = art.user_id
            WHERE art.selector = ?
            LIMIT 1
        ");

        $stmt->execute([$selector]);
        $tokenRow = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$tokenRow) {
            clearAdminRememberCookie();
            return;
        }

        if (strtotime($tokenRow['expires_at']) < time()) {
            $deleteStmt = $pdo->prepare("
                DELETE FROM admin_remember_tokens
                WHERE id = ?
            ");

            $deleteStmt->execute([
                $tokenRow['token_id']
            ]);

            clearAdminRememberCookie();
            return;
        }

        if ((int)$tokenRow['is_locked'] === 1) {
            clearAdminRememberCookie();
            return;
        }

        if (!password_verify($validator, $tokenRow['validator_hash'])) {
            $deleteStmt = $pdo->prepare("
                DELETE FROM admin_remember_tokens
                WHERE id = ?
            ");

            $deleteStmt->execute([
                $tokenRow['token_id']
            ]);

            clearAdminRememberCookie();
            return;
        }

        session_regenerate_id(true);

        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_user_id'] = $tokenRow['user_id'];
        $_SESSION['admin_username'] = $tokenRow['username'];
        $_SESSION['admin_role'] = $tokenRow['role'];

        $updateStmt = $pdo->prepare("
            UPDATE admin_remember_tokens
            SET last_used_at = NOW()
            WHERE id = ?
        ");

        $updateStmt->execute([
            $tokenRow['token_id']
        ]);

    } catch (Exception $e) {
        clearAdminRememberCookie();
        return;
    }
}

// ----------------------
// AUTH CHECK
// ----------------------
attemptRememberMeLogin($pdo);

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

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

// ----------------------
// TERMS OF SERVICE
// ----------------------
$newsdeskTermsVersion = '1.0';
$mustAcceptNewsdeskTerms = false;

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

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

        if (!$userRow || (int)($userRow['is_locked'] ?? 0) === 1) {
            $_SESSION = [];
            session_destroy();

            header('Location: /admin/login.php?locked=1');
            exit;
        }

        $profileImage = $userRow['profile_image'] ?? '';

        $acceptedAt = $userRow['tos_accepted_at'] ?? null;
        $acceptedVersion = $userRow['tos_version'] ?? '';

        if (
            empty($acceptedAt) ||
            $acceptedVersion !== $newsdeskTermsVersion
        ) {
            $mustAcceptNewsdeskTerms = true;
        }

    } catch (PDOException $e) {
        $profileImage = '';
        $mustAcceptNewsdeskTerms = true;
    }
}

// ----------------------
// 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="admin-shell">

    <div class="admin-mobile-sidebar-overlay" id="adminMobileSidebarOverlay" aria-hidden="true"></div>

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

        <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="admin-content">

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

<div class="admin-topbar-left">
    <button
        type="button"
        class="admin-mobile-sidebar-toggle d-lg-none"
        id="adminMobileSidebarToggle"
        aria-controls="adminSidebar"
        aria-expanded="false"
        aria-label="Open admin menu"
    >
        <i class="bi bi-list"></i>
        <span>Menu</span>
    </button>

    <span class="admin-mobile-title d-lg-none">
        ThrillSense Newsdesk
    </span>
</div>

<div class="admin-topbar-actions d-flex align-items-center gap-3">

                <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>

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

<a 
    href="/admin/messages"
    class="admin-topbar-icon-link position-relative text-dark text-decoration-none"
    title="Inbox"
>
    <i class="bi bi-bell"></i>

    <?php if ($unreadCount > 0 || $newContactEnquiryCount > 0): ?>
        <span class="admin-topbar-notification-dot"></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="admin-main">

<?php if ($mustAcceptNewsdeskTerms): ?>

    <div
        class="modal fade"
        id="newsdeskTermsModal"
        tabindex="-1"
        aria-labelledby="newsdeskTermsModalLabel"
        aria-hidden="true"
        data-bs-backdrop="static"
        data-bs-keyboard="false"
    >
        <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">

                <div class="modal-header">
                    <h5 class="modal-title" id="newsdeskTermsModalLabel">
                        ThrillSense Newsdesk Access Agreement
                    </h5>
                </div>

                <div class="modal-body">

                    <div class="mb-4">
                        <h5 class="fw-bold mb-2">
                            ThrillSense Newsdesk - Terms of Use
                        </h5>

                        <p class="text-muted mb-0">
                            Effective version <?= htmlspecialchars($newsdeskTermsVersion, ENT_QUOTES, 'UTF-8') ?>
                        </p>
                    </div>

                    <p>
                        The ThrillSense Newsdesk ("the Platform") is an internal editorial
                        publishing system provided for authorised contributors, editors and
                        administrators of ThrillSense.
                    </p>

                    <p>
                        Access to the Platform is conditional upon compliance with the
                        following Terms of Use. By continuing to use the Platform, you agree
                        to these terms in full.
                    </p>

                    <hr>

                    <h6 class="fw-bold mb-3">
                        1. Authorised Use
                    </h6>

                    <p>
                        The Platform may only be used for legitimate editorial,
                        operational and media-related activities connected to ThrillSense.
                    </p>

                    <p>
                        Users must not:
                    </p>

                    <ul class="mb-4">
                        <li>Attempt to gain unauthorised access to accounts, data or administrative functions.</li>
                        <li>Upload malicious, harmful, deceptive or unlawful content.</li>
                        <li>Use the Platform in a manner that could damage, disrupt or compromise the operation of ThrillSense systems.</li>
                        <li>Share account access with unauthorised individuals.</li>
                    </ul>

                    <h6 class="fw-bold mb-3">
                        2. Editorial Standards
                    </h6>

                    <p>
                        ThrillSense content must meet appropriate editorial, factual and professional standards prior to publication.
                    </p>

                    <p>
                        Users are responsible for ensuring that submitted content:
                    </p>

                    <ul class="mb-4">
                        <li>Is factually accurate to the best of the contributor’s knowledge at the time of submission.</li>
                        <li>Is written in a clear, professional and publication-ready format.</li>
                        <li>Does not intentionally mislead readers through inaccurate, deceptive or exaggerated claims.</li>
                        <li>Does not contain defamatory, discriminatory, abusive, offensive or unlawful material.</li>
                        <li>Does not reproduce copyrighted material without appropriate permission or attribution.</li>
                        <li>Aligns with the editorial tone, standards and publishing approach of ThrillSense.</li>
                    </ul>

                    <p>
                        Contributors must make reasonable efforts to verify information,
                        particularly where content relates to announcements, construction,
                        rumours, operational changes, pricing, safety information or public statements.
                    </p>

                    <p>
                        ThrillSense reserves the right to edit, fact-check, reject,
                        unpublish or remove content at its discretion.
                    </p>

                    <p>
                        Publication approval is not guaranteed by submission alone,
                        and editorial decisions remain subject to final review.
                    </p>

                    <h6 class="fw-bold mb-3">
                        3. Media, Copyright & Licensing
                    </h6>

                    <p>
                        Users must ensure that all uploaded or published media,
                        including images, logos, graphics, videos and press materials,
                        are used with appropriate permission or licensing rights.
                    </p>

                    <p>
                        Users are solely responsible for ensuring that uploaded assets do not
                        infringe copyright, trademark or intellectual property rights belonging
                        to parks, attractions, brands, creators, photographers or third parties.
                    </p>

                    <h6 class="fw-bold mb-3">
                        4. Platform Oversight
                    </h6>

                    <p>
                        ThrillSense administrators may monitor, review and moderate activity
                        carried out within the Platform for editorial, operational and security purposes.
                    </p>

                    <p>
                        <span class="fw-bolder text-decoration-underline" style='font-size: 16px;'>Paul Tibble</span> Founder and Editor of Thrillsense retains final editorial authority regarding all
                        ThrillSense content, publishing decisions and Newsdesk operations.
                    </p>

                    <h6 class="fw-bold mb-3">
                        5. Account Access & Enforcement
                    </h6>

                    <p>
                        Access to the Platform is provided at the discretion of ThrillSense.
                    </p>

                    <p>
                        Accounts may be restricted, suspended or permanently revoked,
                        without prior notice, where misuse, security concerns or breaches
                        of these Terms of Use are identified.
                    </p>

                    <p>
                        ThrillSense reserves the right to amend these Terms of Use at any time.
                        Continued use of the Platform following updates constitutes acceptance
                        of the revised terms.
                    </p>

                    <div class="alert alert-warning mt-4 mb-0">
                        By selecting <strong>I Accept</strong>, you confirm that you have read,
                        understood and agreed to these Terms of Use.
                    </div>

                </div>

<div class="modal-footer">
    <form method="post" action="/admin/logout.php">
        <button type="submit" class="btn btn-danger fw-bold">
            Decline
        </button>
    </form>

    <form method="post" action="/admin/accept-newsdesk-terms.php">
        <input
            type="hidden"
            name="terms_version"
            value="<?= htmlspecialchars($newsdeskTermsVersion, ENT_QUOTES, 'UTF-8') ?>"
        >

        <button type="submit" class="btn btn-dark fw-bold">
            Accept
        </button>
    </form>
</div>

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

    <script>
        document.addEventListener('DOMContentLoaded', function () {

            const termsModalEl = document.getElementById('newsdeskTermsModal');

            if (termsModalEl) {

                const termsModal = new bootstrap.Modal(termsModalEl, {
                    backdrop: 'static',
                    keyboard: false
                });

                termsModal.show();
            }
        });
    </script>

<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const body = document.body;
    const toggle = document.getElementById('adminMobileSidebarToggle');
    const overlay = document.getElementById('adminMobileSidebarOverlay');
    const sidebar = document.getElementById('adminSidebar');

    function openSidebar() {
        body.classList.add('admin-mobile-sidebar-open');

        if (toggle) {
            toggle.setAttribute('aria-expanded', 'true');
        }
    }

    function closeSidebar() {
        body.classList.remove('admin-mobile-sidebar-open');

        if (toggle) {
            toggle.setAttribute('aria-expanded', 'false');
        }
    }

    if (toggle) {
        toggle.addEventListener('click', function () {
            if (body.classList.contains('admin-mobile-sidebar-open')) {
                closeSidebar();
            } else {
                openSidebar();
            }
        });
    }

    if (overlay) {
        overlay.addEventListener('click', closeSidebar);
    }

    if (sidebar) {
        sidebar.querySelectorAll('a').forEach(function (link) {
            link.addEventListener('click', closeSidebar);
        });
    }

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape') {
            closeSidebar();
        }
    });
});
</script>
