<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/v292_admin_portal_helpers.php';
$admin = current_admin();
$adminTitle = $adminTitle ?? 'Admin';
$currentFile = basename($_SERVER['SCRIPT_NAME'] ?? 'dashboard.php');
if (!function_exists('mj_admin_nav_active')) {
function mj_admin_nav_active(string $file): string {
    $current = basename($_SERVER['SCRIPT_NAME'] ?? '');
    return $current === $file ? ' active' : '';
}
}
if (!function_exists('mj_admin_nav_item')) {
function mj_admin_nav_item(string $file, string $icon, string $label, string $badge = ''): void {
    $active = mj_admin_nav_active($file);
    echo '<li class="nav-item"><a href="'.e($file).'" class="nav-link'.$active.'"><i class="nav-icon '.$icon.'"></i><p>'.e($label);
    if ($badge !== '') { echo '<span class="right badge badge-danger">'.e($badge).'</span>'; }
    echo '</p></a></li>';
}
}
if (!function_exists('mj_admin_nav_tree')) {
function mj_admin_nav_tree(string $label, string $icon, array $items, string $badge = ''): void {
    $current = basename($_SERVER['SCRIPT_NAME'] ?? '');
    $files = array_map(fn($i) => (string)($i[0] ?? ''), $items);
    $open = in_array($current, $files, true);
    echo '<li class="nav-item has-treeview'.($open?' menu-open':'').'">';
    echo '<a href="#" class="nav-link'.($open?' active':'').'"><i class="nav-icon '.$icon.'"></i><p>'.e($label);
    if ($badge !== '') { echo '<span class="right badge badge-danger">'.e($badge).'</span>'; }
    echo '<i class="right fas fa-angle-left"></i></p></a><ul class="nav nav-treeview">';
    foreach ($items as $item) {
        $file = (string)($item[0] ?? '#'); $itemIcon = (string)($item[1] ?? 'far fa-circle'); $itemLabel = (string)($item[2] ?? $file); $itemBadge = (string)($item[3] ?? '');
        echo '<li class="nav-item"><a href="'.e($file).'" class="nav-link'.mj_admin_nav_active($file).'"><i class="'.$itemIcon.' nav-icon"></i><p>'.e($itemLabel);
        if ($itemBadge !== '') { echo '<span class="right badge badge-info">'.e($itemBadge).'</span>'; }
        echo '</p></a></li>';
    }
    echo '</ul></li>';
}
}
$approvalBadge = function_exists('mj_v289_sidebar_badge') ? mj_v289_sidebar_badge('approval') : '';
$paymentBadge = function_exists('mj_v289_sidebar_badge') ? mj_v289_sidebar_badge('payments') : '';
$supportBadge = function_exists('mj_v289_sidebar_badge') ? mj_v289_sidebar_badge('support') : '';
$reportBadge = function_exists('mj_v289_sidebar_badge') ? mj_v289_sidebar_badge('reports') : '';
$errorBadge = function_exists('mj_v289_sidebar_badge') ? mj_v289_sidebar_badge('errors') : '';
$bookingBadge = function_exists('mj_v289_sidebar_badge') ? mj_v289_sidebar_badge('bookings') : '';
if ($admin && function_exists('mj292_ensure_schema')) { mj292_ensure_schema(); }
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="robots" content="noindex,nofollow">
    <title><?= e($adminTitle) ?> | MJ Marketplace Admin</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="<?= e('assets/admin-stable.css?v=' . filemtime(__DIR__ . '/assets/admin-stable.css')) ?>">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/datatables.net-bs4@1.13.8/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/datatables.net-responsive-bs4@2.5.0/css/responsive.bootstrap4.min.css">
    <link rel="stylesheet" href="<?= e(asset_versioned('css/admin-stable-mj.css')) ?>">
    <link rel="stylesheet" href="<?= e(asset_versioned('css/admin.css')) ?>">
    <link rel="stylesheet" href="<?= e(asset_versioned('css/admin-v292.css')) ?>">
    <script>window.MJ_BASE_URL = <?= json_encode(rtrim(base_url('/'), '/')) ?>; window.MJ_CSRF_TOKEN = <?= json_encode(function_exists('mj427_form_token') ? mj427_form_token() : csrf_token()) ?>; window.MJ_FORM_TOKEN = window.MJ_CSRF_TOKEN; window.MJ_NOTIFICATION_POLL_MS = <?= (int)setting('global_notification_poll_seconds','25')*1000 ?>; window.MJ_DEBUG_MODE = <?= function_exists('mj428_admin_can_debug') && mj428_admin_can_debug() ? 'true' : 'false' ?>;</script>
    <link rel="stylesheet" href="<?= e(asset_versioned('css/ultimate-mj.css')) ?>">
    <link rel="stylesheet" href="<?= e(asset_versioned('css/listing-module.css')) ?>">
    <link rel="stylesheet" href="<?= e(asset_versioned('css/v3-upgrade.css')) ?>">
    <link rel="stylesheet" href="<?= e(asset_versioned('css/mj-v304.css')) ?>">
  <link rel="stylesheet" href="<?= e(asset_versioned('css/mj-v30427-forms-location.css')) ?>">
  <link rel="stylesheet" href="<?= e(asset_versioned('css/mj-v30428-popup-speed.css')) ?>">
</head>
<?php if (!$admin): ?>
<body class="mj-admin-login-page">
<div class="login-page-shell">
<?php show_flash(); ?>
<?php else: ?>
<body class="mj-admin-stable-body mj-admin-pro-v290">
<div class="wrapper">
    <nav class="main-header navbar navbar-expand navbar-white navbar-light mj-topbar">
        <ul class="navbar-nav">
            <li class="nav-item"><a class="nav-link" data-mj-sidebar-toggle="1" href="#" role="button"><i class="fas fa-bars"></i></a></li>
            <li class="nav-item d-none d-sm-inline-block"><a href="dashboard.php" class="nav-link"><i class="fas fa-tachometer-alt mr-1"></i>Dashboard</a></li>
            <li class="nav-item d-none d-md-inline-block"><a href="action-queue.php" class="nav-link"><i class="fas fa-tasks mr-1"></i>Action Queue <?php if($approvalBadge): ?><span class="badge badge-danger ml-1"><?= e($approvalBadge) ?></span><?php endif; ?></a></li>
            <li class="nav-item d-none d-md-inline-block"><a href="control-center.php" class="nav-link"><i class="fas fa-th-large mr-1"></i>Control Center</a></li>
            <li class="nav-item d-none d-lg-inline-block"><a href="admin-tasks.php" class="nav-link"><i class="fas fa-clipboard-check mr-1"></i>Tasks</a></li>
            <li class="nav-item d-none d-sm-inline-block"><a href="../index.php" target="_blank" class="nav-link"><i class="fas fa-external-link-alt mr-1"></i>View Website</a></li>
        </ul>
        <form class="form-inline ml-3 d-none d-md-flex" method="get" action="admin-search.php">
            <div class="input-group input-group-sm mj-top-search">
                <input class="form-control form-control-navbar" type="search" name="q" value="<?= e($_GET['q'] ?? '') ?>" placeholder="Search users, listings, companies, payments..." aria-label="Search">
                <div class="input-group-append"><button class="btn btn-navbar" type="submit"><i class="fas fa-search"></i></button></div>
            </div>
        </form>
        <ul class="navbar-nav ml-auto">
            <li class="nav-item"><a class="nav-link mj-v3-notification-btn" href="notifications.php" title="Notifications"><i class="far fa-bell"></i><span class="mj-v3-badge" data-mj-notification-count>0</span></a></li>
            <li class="nav-item d-none d-lg-block"><a class="nav-link" href="system-health.php" title="System Health"><i class="fas fa-heartbeat"></i></a></li>
            <li class="nav-item d-none d-lg-block"><a class="nav-link" href="finance-summary.php" title="Finance"><i class="fas fa-chart-line"></i><?php if($paymentBadge): ?><span class="badge badge-success navbar-badge"><?= e($paymentBadge) ?></span><?php endif; ?></a></li>
            <?php $alertCount = mj_admin_unread_alert_count(); $latestAlerts = mj_admin_latest_alerts(6); ?>
            <li class="nav-item dropdown">
              <a class="nav-link" data-toggle="dropdown" href="#" title="Admin Alerts"><i class="far fa-bell"></i><?php if($alertCount>0): ?><span class="badge badge-danger navbar-badge"><?= e($alertCount>99?'99+':$alertCount) ?></span><?php endif; ?></a>
              <div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
                <span class="dropdown-item dropdown-header"><?= e($alertCount) ?> unread alerts</span><div class="dropdown-divider"></div>
                <?php foreach($latestAlerts as $al): ?><a href="<?= e($al['action_url'] ?: 'alerts.php') ?>" class="dropdown-item"><i class="fas fa-exclamation-circle mr-2 text-<?= e(($al['priority']??'normal')==='critical'?'danger':(($al['priority']??'normal')==='urgent'?'warning':'info')) ?>"></i><?= e(mb_strimwidth($al['title'] ?? 'Alert',0,34,'...')) ?><span class="float-right text-muted text-sm"><?= e(date('H:i', strtotime($al['created_at'] ?? 'now'))) ?></span></a><div class="dropdown-divider"></div><?php endforeach; ?>
                <?php if(!$latestAlerts): ?><span class="dropdown-item text-muted text-center">No alerts</span><div class="dropdown-divider"></div><?php endif; ?>
                <a href="alerts.php" class="dropdown-item dropdown-footer">View All Alerts</a>
              </div>
            </li>
            <li class="nav-item d-none d-sm-block"><a class="nav-link" href="settings.php"><i class="fas fa-cog"></i></a></li>
            <li class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#"><i class="far fa-user-circle mr-1"></i><?= e($admin['name'] ?? 'Admin') ?></a>
                <div class="dropdown-menu dropdown-menu-right">
                    <span class="dropdown-item-text small text-muted">Role: <?= e($admin['role'] ?? 'super_admin') ?></span>
                    <div class="dropdown-divider"></div>
                    <a href="settings.php" class="dropdown-item"><i class="fas fa-cogs mr-2"></i>Settings</a>
                    <a href="logout.php" class="dropdown-item text-danger"><i class="fas fa-sign-out-alt mr-2"></i>Logout</a>
                </div>
            </li>
        </ul>
    </nav>

    <aside class="main-sidebar sidebar-dark-primary elevation-4 mj-sidebar">
        <a href="dashboard.php" class="brand-link mj-brand-link">
            <span class="brand-image mj-brand-mark elevation-2">MJ</span>
            <span class="brand-text font-weight-light"><b>MJ</b> Marketplace</span>
        </a>
        <div class="sidebar">
            <div class="user-panel mt-3 pb-3 mb-3 d-flex">
                <div class="image"><span class="mj-user-avatar"><i class="fas fa-user-shield"></i></span></div>
                <div class="info"><a href="settings.php" class="d-block"><?= e($admin['name'] ?? 'Admin User') ?></a><small class="text-muted"><?= e(ucwords(str_replace('_',' ', $admin['role'] ?? 'super_admin'))) ?></small></div>
            </div>
            <nav class="mt-2">
                <ul class="nav nav-pills nav-sidebar flex-column nav-compact mj-v292-sidebar" data-widget="treeview" role="menu" data-accordion="false">
                    <?php mj_admin_nav_item('dashboard.php','fas fa-tachometer-alt','Dashboard'); ?>
                    <?php mj_admin_nav_item('control-center.php','fas fa-compass','Control Center'); ?>
                    <?php mj_admin_nav_item('action-queue.php','fas fa-clipboard-check','Action Queue',$approvalBadge); ?>
                    <?php mj_admin_nav_item('update-reviews.php','fas fa-code-branch','Update Reviews'); ?>

                    <li class="nav-header">OPERATIONS</li>
                    <?php mj_admin_nav_tree('Users & Accounts','fas fa-users', [
                        ['users.php','fas fa-users','All Users'], ['user-view.php','fas fa-user-circle','User 360'], ['user-limits.php','fas fa-user-lock','User Limits'], ['payment-center.php?tab=wallet','fas fa-wallet','User Wallet'], ['user-activity.php','fas fa-history','User Activity'], ['support.php','fas fa-headset','Support Tickets',$supportBadge]
                    ], $supportBadge); ?>
                    <?php mj_admin_nav_tree('Listings & Companies','fas fa-store', [
                        ['listings.php','fas fa-tags','All Listings'], ['listings.php?status=pending','fas fa-clock','Pending Listings'], ['listing-revisions.php','fas fa-code-branch','Listing Updates'], ['company-revisions.php','fas fa-code-branch','Company Updates'], ['expired-listings.php','fas fa-hourglass-end','Expired Listings'], ['reported-listings.php','fas fa-flag','Reported Listings',$reportBadge], ['listing-renewals.php','fas fa-redo','Renewals'], ['companies.php','fas fa-building','Companies'], ['company-claims.php','fas fa-handshake','Company Claims'], ['categories.php','fas fa-layer-group','Categories'], ['category-fields.php','fas fa-list-alt','Smart Fields']
                    ], $reportBadge); ?>
                    <?php mj_admin_nav_tree('Payments & Billing','fas fa-money-check-alt', [
                        ['payment-center.php','fas fa-credit-card','Payment Center',$paymentBadge], ['payment-center.php?tab=invoices','fas fa-file-invoice','Invoices / Receipts'], ['payment-center.php?tab=wallet','fas fa-wallet','Wallet Top-up / Credits'], ['cart-abandoned.php','fas fa-shopping-cart','Service Carts'], ['finance-summary.php','fas fa-chart-line','Finance Summary'], ['finance-reconciliation.php','fas fa-balance-scale','Finance Reconciliation'], ['activation-checker.php','fas fa-bolt','Activation Checker'], ['invoice-settings.php','fas fa-cog','Invoice Settings'], ['upgrade-payment-settings.php','fas fa-money-check-alt','Payment Settings']
                    ], $paymentBadge); ?>

                    <li class="nav-header">REPORTS & INSIGHT</li>
                    <?php mj_admin_nav_tree('Reports','fas fa-chart-pie', [
                        ['reports.php','fas fa-chart-line','Report Dashboard'], ['report-users.php','fas fa-users','Users'], ['report-listings.php','fas fa-tags','Listings'], ['report-companies.php','fas fa-building','Companies'], ['report-payments.php','fas fa-credit-card','Payments'], ['report-invoices.php','fas fa-file-invoice','Invoices'], ['report-wallets.php','fas fa-wallet','Wallets'], ['report-receipts.php','fas fa-receipt','Receipts'], ['report-revenue.php','fas fa-coins','Revenue'], ['report-expiry.php','fas fa-hourglass-half','Expiry'], ['leads.php','fas fa-user-friends','Leads Inbox'], ['report-leads.php','fas fa-mouse-pointer','Lead Tracking'], ['report-admin-activity.php','fas fa-history','Admin Activity'], ['report-reset-logs.php','fas fa-undo','Reset Logs']
                    ]); ?>
                    <?php mj_admin_nav_tree('Trust & Growth','fas fa-shield-alt', [
                        ['leads.php','fas fa-user-friends','Leads Inbox'], ['exception-center.php','fas fa-exclamation-triangle','Exception Center'], ['safety-dashboard.php','fas fa-shield-virus','Trust & Safety'], ['fraud-dashboard.php','fas fa-user-secret','Fraud Dashboard'], ['reviews.php','fas fa-star','Reviews'], ['seller-performance.php','fas fa-medal','Seller Performance'], ['sponsored-performance.php','fas fa-bullhorn','Sponsored Performance'], ['admin-search.php','fas fa-search','Global Search'], ['broadcast.php','fas fa-bullhorn','Broadcast']
                    ], ($reportBadge ?: $errorBadge)); ?>

                    <li class="nav-header">CONTENT & SETUP</li>
                    <?php mj_admin_nav_tree('Location & Content','fas fa-globe-asia', [
                        ['countries.php','fas fa-globe-asia','Countries'], ['locations.php','fas fa-map-marked-alt','States / Cities'], ['location-import.php','fas fa-file-import','Import Locations'], ['content.php','fas fa-file-alt','Pages'], ['seo.php','fas fa-search','SEO Center'], ['seo-pages.php','fas fa-heading','SEO Pages'], ['sitemap-manager.php','fas fa-sitemap','Sitemap'], ['redirects.php','fas fa-route','Redirects']
                    ]); ?>
                    <?php mj_admin_nav_tree('Deals / Services','fas fa-fire', [
                        ['deals.php','fas fa-fire','All Deals'], ['deal-create.php','fas fa-plus-circle','Add Deal'], ['deal-import.php','fas fa-file-import','Import Deals'], ['deal-upgrade-settings.php','fas fa-coins','Deal Upgrade Settings'], ['deals.php?status=pending','fas fa-clock','Pending Deals'], ['deal-revisions.php','fas fa-code-branch','Deal Updates'], ['deal-enquiries.php','fas fa-envelope-open-text','Deal Enquiries'], ['report-deals.php','fas fa-chart-line','Deal Reports'], ['report-deal-limits.php','fas fa-layer-group','Deal Limits'], ['promotions.php','fas fa-percent','Promotions'], ['coupons.php','fas fa-ticket-alt','Coupons'], ['services.php','fas fa-concierge-bell','Services'], ['quote-requests.php','fas fa-file-invoice-dollar','RFQ / Quotes'], ['bookings.php','fas fa-calendar-check','Bookings',$bookingBadge]
                    ], $bookingBadge); ?>
                    <?php mj_admin_nav_tree('Notifications','fas fa-bell', [
                        ['notifications.php','fas fa-bell','Notification Center'], ['notification-settings.php','fas fa-sliders-h','Notification Settings'], ['smtp-settings.php','fas fa-server','SMTP Settings'], ['notification-templates.php','fas fa-envelope-open-text','Notification Templates'], ['email-templates.php','fas fa-envelope','Email Templates'], ['alerts.php','fas fa-exclamation-circle','Admin Alerts']
                    ], $errorBadge); ?>

                    <li class="nav-header">SYSTEM</li>
                    <?php mj_admin_nav_tree('Automation & Tools','fas fa-robot', [
                        ['automation-center.php','fas fa-robot','Automation Center'], ['automation-settings.php','fas fa-toggle-on','Automation Settings'], ['automation-logs.php','fas fa-list','Automation Logs'], ['admin-tasks.php','fas fa-clipboard-check','Admin Tasks'], ['import-center.php','fas fa-upload','Import / Export'], ['link-health.php','fas fa-link','Link Health'], ['system-health.php','fas fa-heartbeat','System Health'], ['system-test.php','fas fa-vial','System Test'], ['auto-repair.php','fas fa-tools','Auto Repair'], ['error-logs.php','fas fa-bug','Error Logs'], ['migration-status.php','fas fa-code-branch','Migration Status'], ['cron-monitor.php','fas fa-clock','Cron Monitor']
                    ]); ?>
                    <?php if (is_super_admin($admin)): ?>
                    <?php mj_admin_nav_tree('Super Admin','fas fa-user-shield', [
                        ['super-admin.php','fas fa-user-shield','Super Admin'], ['admin-users.php','fas fa-users-cog','Admin Users'], ['admin-roles.php','fas fa-user-lock','Role Permissions'], ['audit-logs.php','fas fa-history','Audit Logs'], ['backup.php','fas fa-database','Backup / Health'], ['system-reset.php','fas fa-exclamation-triangle','Safe Reset System'], ['version.php','fas fa-code-branch','Version']
                    ]); ?>
                    <?php endif; ?>
                    <?php mj_admin_nav_item('settings.php','fas fa-cogs','Settings'); ?>
                    <li class="nav-item mt-2"><a href="../index.php" target="_blank" class="nav-link mj-view-site"><i class="nav-icon fas fa-external-link-alt"></i><p>View Marketplace</p></a></li>
                </ul>
            </nav>
        </div>
    </aside>

    <div class="content-wrapper">
        <section class="content-header mj-content-header">
            <div class="container-fluid">
                <div class="row mb-2 align-items-center">
                    <div class="col-sm-7"><h1><?= e($adminTitle) ?></h1><p class="text-muted mb-0"><?= e($adminSubtitle ?? 'Manage your global marketplace, users, listings, companies, payments, approvals and automation.') ?></p></div>
                    <div class="col-sm-5"><ol class="breadcrumb float-sm-right"><li class="breadcrumb-item"><a href="dashboard.php">Admin</a></li><li class="breadcrumb-item active"><?= e($adminTitle) ?></li></ol></div>
                </div>
                <?php show_flash(); ?>
            </div>
        </section>
        <section class="content">
            <div class="container-fluid">
<?php endif; ?>
