<?php
/**
 * include/sidebar.php
 */

// ── Page permissions load karo — session cache se ya DB se ──────────────
function _load_page_perms(): array {
    if (isset($_SESSION['admin_page_perms'])) {
        return $_SESSION['admin_page_perms'];
    }

    $uid = (int)($_SESSION['admin_user_id'] ?? 0);
    if (!$uid) {
        $_SESSION['admin_page_perms'] = [];
        return [];
    }

    // $pdo global nahi, isliye direct DB connection banao
    $perms = [];
    try {
        // db.php ka config path use karo
        $dsn  = 'mysql:host=' . (defined('DB_HOST') ? DB_HOST : '127.0.0.1')
              . ';dbname=' . (defined('DB_NAME') ? DB_NAME : '')
              . ';charset=utf8mb4';
        $user = defined('DB_USER') ? DB_USER : '';
        $pass = defined('DB_PASS') ? DB_PASS : '';

        // Agar $pdo already global scope mein hai toh use karo
        if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
            $st = $GLOBALS['pdo']->prepare(
                "SELECT permission_key FROM admin_user_permissions WHERE user_id = ?"
            );
            $st->execute([$uid]);
            $perms = $st->fetchAll(PDO::FETCH_COLUMN);
        } elseif ($dsn) {
            $conn = new PDO($dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
            $st   = $conn->prepare(
                "SELECT permission_key FROM admin_user_permissions WHERE user_id = ?"
            );
            $st->execute([$uid]);
            $perms = $st->fetchAll(PDO::FETCH_COLUMN);
        }
    } catch (\Throwable $e) {
        $perms = [];
    }

    $_SESSION['admin_page_perms'] = $perms;
    return $perms;
}

if (!function_exists('has_page_access')) {
    function has_page_access(string $file): bool {
        $role = $_SESSION['admin_role'] ?? '';

        // superadmin aur admin ko sab allow
        if (in_array($role, ['superadmin', 'admin'], true)) return true;

        // dashboard hamesha allow
        if ($file === 'admin_dashboard.php') return true;

        // subadmin ke liye check karo
        $perms = _load_page_perms();
        return in_array($file, $perms, true);
    }
}

$SIDEBAR_NAV = [
    'Overview' => [
        'admin_dashboard.php'    => ['label' => 'Dashboard',            'icon' => 'fa-th-large'],
        'submissions.php'        => ['label' => 'Submissions',          'icon' => 'fa-file-alt'],
        'final_submissions.php'  => ['label' => 'Final Submissions',    'icon' => 'fa-file-contract'],
        'resubmissions.php'      => ['label' => 'ReSubmissions',        'icon' => 'fa-redo-alt'],
        'reviewer-due-dates.php' => ['label' => 'Reviewer Due Dates',   'icon' => 'fa-calendar-alt'],
        'reminders.php'          => ['label' => 'Reminders',            'icon' => 'fa-bell'],
        'live_feedback.php'      => ['label' => 'Live Feedbacks',       'icon' => 'fa-comments'],
        'reviewer_tickets.php'   => ['label' => 'Reviewer Tickets',     'icon' => 'fa-ticket-alt'],
        'author_tickets.php'     => ['label' => 'Author Tickets',       'icon' => 'fa-ticket-alt'],
        'all_payments.php'       => ['label' => 'All Payments',         'icon' => 'fa-credit-card'],
        'stripe-payments.php'    => ['label' => 'Stripe Payments',      'icon' => 'fa-stripe-s'],
    ],
    'People' => [
        'reviewers_applications.php' => ['label' => 'Reviewers Applications', 'icon' => 'fa-user-check'],
        'suggested_reviewers.php'    => ['label' => 'Suggested Reviewers',    'icon' => 'fa-users'],
        'editorial_applications.php' => ['label' => 'Editorial Applications', 'icon' => 'fa-star'],
        'conference_proceedings.php' => ['label' => 'Conference Proceedings', 'icon' => 'fa-chalkboard-teacher'],
        'subscribers.php'            => ['label' => 'Subscribers',            'icon' => 'fa-envelope'],
        'users.php'                  => ['label' => 'Users',                  'icon' => 'fa-user'],
        'manage_users.php'           => ['label' => 'Manage Admin Users',     'icon' => 'fa-user-cog'],
    ],
    'Website' => [
        'pages.php'           => ['label' => 'Pages',                 'icon' => 'fa-file'],
        'categories.php'      => ['label' => 'Journals Category',     'icon' => 'fa-folder'],
        'journals.php'        => ['label' => 'Journals',              'icon' => 'fa-book'],
        'website-details.php' => ['label' => 'Website Details',       'icon' => 'fa-globe'],
        'admin_homepage.php'  => ['label' => 'Main Website Homepage', 'icon' => 'fa-home'],
        'bfooter.php'         => ['label' => 'Footer',                'icon' => 'fa-bars'],
    ],
];

$currentPage = basename($_SERVER['PHP_SELF']);

// Force fresh load for subadmin (session clear karo)
$_role = $_SESSION['admin_role'] ?? '';
if (!in_array($_role, ['superadmin', 'admin'], true)) {
    // Har page load pe fresh DB se load karo (cache bypass)
    unset($_SESSION['admin_page_perms']);
    _load_page_perms();
}
?>
<style>
.sidebar-nav-group{padding:10px 16px 4px;font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:#6b7280;margin-top:6px;}
.sidebar-nav-link{display:flex;align-items:center;gap:10px;padding:9px 16px;color:#d1d5db;text-decoration:none;font-size:13px;font-weight:500;transition:all .15s;border-left:3px solid transparent;white-space:nowrap;}
.sidebar-nav-link:hover{background:#374151;color:#fff;}
.sidebar-nav-link.active{background:#374151;color:#60a5fa;border-left-color:#3b82f6;}
.sidebar-nav-link .nav-fa{width:18px;text-align:center;flex-shrink:0;font-size:13px;}
.sidebar-nav-link span{overflow:hidden;text-overflow:ellipsis;}
.sidebar.collapsed .sidebar-nav-link span{display:none;}
.sidebar.collapsed .sidebar-nav-group{display:none;}
.sidebar-logo{padding:14px 16px;border-bottom:1px solid #374151;display:flex;align-items:center;gap:10px;flex-shrink:0;}
.sidebar-logo-text{font-size:14px;font-weight:700;color:#fff;white-space:nowrap;}
.sidebar.collapsed .sidebar-logo-text{display:none;}
.sidebar-footer{position:absolute;bottom:0;left:0;right:0;padding:12px 16px;border-top:1px solid #374151;display:flex;align-items:center;gap:10px;background:#2d3748;flex-shrink:0;}
.sidebar.collapsed .sidebar-footer-text{display:none;}
</style>

<div class="sidebar" id="sidebar">

    <div class="sidebar-logo">
        <div style="width:32px;height:32px;background:#2563eb;border-radius:8px;display:flex;align-items:center;justify-content:center;flex-shrink:0;">
            <i class="fas fa-shield-alt" style="color:white;font-size:14px;"></i>
        </div>
        <span class="sidebar-logo-text">Admin Panel</span>
    </div>

    <nav style="padding-bottom:70px;overflow-y:auto;height:calc(100% - 120px);">
    <?php foreach ($SIDEBAR_NAV as $groupName => $pages):

        $visiblePages = array_filter(
            $pages,
            fn($file) => has_page_access($file),
            ARRAY_FILTER_USE_KEY
        );

        if (empty($visiblePages)) continue;
    ?>
        <div class="sidebar-nav-group"><?= htmlspecialchars($groupName) ?></div>

        <?php foreach ($visiblePages as $file => $info): ?>
        <a href="<?= htmlspecialchars($file) ?>"
           class="sidebar-nav-link <?= $currentPage === $file ? 'active' : '' ?>">
            <i class="fas <?= $info['icon'] ?> nav-fa"></i>
            <span><?= htmlspecialchars($info['label']) ?></span>
        </a>
        <?php endforeach; ?>

    <?php endforeach; ?>
    </nav>

    <div class="sidebar-footer">
        <div style="width:32px;height:32px;border-radius:50%;background:#2563eb;display:flex;align-items:center;justify-content:center;color:white;font-size:12px;font-weight:700;flex-shrink:0;">
            <?= strtoupper(substr($_SESSION['admin_first_name'] ?? 'A', 0, 1)) ?>
        </div>
        <div class="sidebar-footer-text" style="overflow:hidden;flex:1;min-width:0;">
            <div style="font-size:12px;font-weight:600;color:#e5e7eb;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                <?= htmlspecialchars(trim(($_SESSION['admin_first_name'] ?? '') . ' ' . ($_SESSION['admin_last_name'] ?? ''))) ?>
            </div>
            <div style="font-size:10px;color:#9ca3af;margin-top:1px;">
                <?= ucfirst($_SESSION['admin_role'] ?? '') ?>
            </div>
        </div>
        <a href="logout.php" title="Logout" style="color:#9ca3af;font-size:14px;flex-shrink:0;">
            <i class="fas fa-sign-out-alt"></i>
        </a>
    </div>

</div>

