<?php
/**
 * M-Pesa Agency Banking System — Sidebar
 * Schema: roles, role_permissions, permissions, users, user_locations
 */

// ============================================
// LOAD USER + ROLE FROM CORRECT TABLES
// ============================================

$userRole    = 'guest';
$userPerms   = [];
$user_details = null;
$current_page = basename($_SERVER['PHP_SELF']);

if (isset($_SESSION['user_id'])) {
    $uid  = (int) $_SESSION['user_id'];

    $stmt = $conn->prepare(
        "SELECT u.*, r.role_name
         FROM   users u
         INNER JOIN roles r ON r.id = u.role_id
         WHERE  u.id = ? AND u.status = 'active'
         LIMIT 1"
    );
    $stmt->bind_param("i", $uid);
    $stmt->execute();
    $user_details = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($user_details) {
        $userRole = $user_details['role_name'];

        // Load permission names for this role
        $pstmt = $conn->prepare(
            "SELECT p.permission_name
             FROM   role_permissions rp
             JOIN   permissions p ON p.id = rp.permission_id
             WHERE  rp.role_id = ?"
        );
        $pstmt->bind_param("i", $user_details['role_id']);
        $pstmt->execute();
        $pres = $pstmt->get_result();
        while ($row = $pres->fetch_assoc()) {
            $userPerms[] = $row['permission_name'];
        }
        $pstmt->close();
    }
}

// ============================================
// PERMISSION HELPER
// ============================================

function hasPerm(array $perms, string $perm, string $role): bool {
    return $role === 'super_admin' || in_array($perm, $perms, true);
}

function isActive(string $page): string {
    return basename($_SERVER['PHP_SELF']) === $page ? 'active' : '';
}

function isGroupActive(array $pages): string {
    $cur = basename($_SERVER['PHP_SELF']);
    foreach ($pages as $p) {
        if (basename($p) === $cur) return 'active';
    }
    return '';
}

function isGroupOpen(array $pages): string {
    $cur = basename($_SERVER['PHP_SELF']);
    foreach ($pages as $p) {
        if (basename($p) === $cur) return 'show';
    }
    return '';
}

// ============================================
// DASHBOARD URL BY ROLE
// ============================================

$dashboards = [
    'super_admin' => 'index.php',
    'manager'     => 'index.php',
    'agent'       => 'index.php',
    'auditor'     => 'reports.php',
];
$roleDashboard = $dashboards[$userRole] ?? 'index.php';
?>

<!-- ===================== SIDEBAR ===================== -->
<div class="sidebar">
    <nav>
        <!-- Logo -->
        <div class="app-logo">
            <a class="logo d-inline-block" href="<?= $roleDashboard ?>">
                <img src="assets/images/logo/nelcare.png" alt="M-Pesa System"
                     class="img-fluid" style="max-height:40px;">
            </a>
            <span class="bg-light-primary toggle-semi-nav ms-2">
                <i class="ti ti-chevrons-right f-s-20"></i>
            </span>
        </div>

        <div class="app-nav" id="app-simple-bar">

            <!-- User Info -->
            <?php if ($user_details): ?>
            <div class="user-info-sidebar">
                <div class="user-avatar">
                    <?= strtoupper(substr($user_details['full_name'], 0, 2)) ?>
                </div>
                <div class="user-details">
                    <div class="user-name"><?= htmlspecialchars($user_details['full_name']) ?></div>
                    <div class="user-role"><?= htmlspecialchars($userRole) ?></div>
                    <div class="user-permissions"><?= count($userPerms) ?> permissions</div>
                </div>
            </div>
            <?php endif; ?>

            <ul class="main-nav p-0 mt-2">

                <!-- ── MAIN MENU ── -->
                <li class="menu-title"><span>Main Menu</span></li>

                <?php if (hasPerm($userPerms, 'view_dashboard', $userRole)): ?>
                <li class="no-sub">
                    <a href="<?= $roleDashboard ?>" class="<?= isActive($roleDashboard) ?>">
                        <i class="ph-duotone ph-chart-line"></i> Dashboard
                    </a>
                </li>
                <?php endif; ?>

                <!-- ── TRANSACTIONS ── -->
                <?php if (hasPerm($userPerms, 'capture_transaction', $userRole)): ?>
                <li class="menu-title"><span>Transactions</span></li>

                <?php
                $txnPages = ['mpesa_transaction.php','agency_banking.php','airtime_sale.php'];
                ?>
                <li>
                    <a class="<?= isGroupActive($txnPages) ?>"
                       data-bs-toggle="collapse" href="#txnMenu"
                       aria-expanded="<?= isGroupOpen($txnPages) ? 'true' : 'false' ?>">
                        <i class="ph-duotone ph-arrows-left-right"></i>
                        Record Transaction
                        <span class="item-count">3</span>
                    </a>
                    <ul class="collapse <?= isGroupOpen($txnPages) ?>" id="txnMenu">
                        <li><a href="mpesa_transaction.php" class="<?= isActive('mpesa_transaction.php') ?>">M-Pesa</a></li>
                        <li><a href="agency_banking.php"    class="<?= isActive('agency_banking.php') ?>">Agency Banking</a></li>
                        <li><a href="airtime_sale.php"      class="<?= isActive('airtime_sale.php') ?>">Airtime Sale</a></li>
                    </ul>
                </li>
                <?php endif; ?>

                <?php if (hasPerm($userPerms, 'void_transaction', $userRole)): ?>
                <li class="no-sub">
                    <a href="void_transaction.php" class="<?= isActive('void_transaction.php') ?>">
                        <i class="ph-duotone ph-x-circle"></i> Void Transaction
                    </a>
                </li>
                <?php endif; ?>

                <!-- ── SESSION MANAGEMENT ── -->
                <?php if (hasPerm($userPerms, 'open_session', $userRole) ||
                          hasPerm($userPerms, 'close_session', $userRole)): ?>
                <li class="menu-title"><span>Sessions</span></li>

                <?php if (hasPerm($userPerms, 'open_session', $userRole)): ?>
                <li class="no-sub">
                    <a href="open_session.php" class="<?= isActive('open_session.php') ?>">
                        <i class="ph-duotone ph-play-circle"></i> Open Session
                    </a>
                </li>
                <?php endif; ?>

                <?php if (hasPerm($userPerms, 'close_session', $userRole)): ?>
                <li class="no-sub">
                    <a href="close_session.php" class="<?= isActive('close_session.php') ?>">
                        <i class="ph-duotone ph-stop-circle"></i> Close Session
                    </a>
                </li>
                <?php endif; ?>

                <?php if (hasPerm($userPerms, 'approve_reconciliation', $userRole)): ?>
                <li class="no-sub">
                    <a href="reconciliation.php" class="<?= isActive('reconciliation.php') ?>">
                        <i class="ph-duotone ph-check-circle"></i> Reconciliation
                    </a>
                </li>
                <?php endif; ?>
                <?php endif; ?>

                <!-- ── FLOAT MANAGEMENT ── -->
                <?php if (hasPerm($userPerms, 'manage_float', $userRole) ||
                          hasPerm($userPerms, 'transfer_float', $userRole)): ?>
                <li class="menu-title"><span>Float</span></li>

                <?php
                $floatPages = ['float_accounts.php','float_movement.php','float_transfer.php'];
                ?>
                <li>
                    <a class="<?= isGroupActive($floatPages) ?>"
                       data-bs-toggle="collapse" href="#floatMenu"
                       aria-expanded="<?= isGroupOpen($floatPages) ? 'true' : 'false' ?>">
                        <i class="ph-duotone ph-wallet"></i>
                        Float Management
                        <span class="item-count">3</span>
                    </a>
                    <ul class="collapse <?= isGroupOpen($floatPages) ?>" id="floatMenu">
                        <?php if (hasPerm($userPerms, 'manage_float', $userRole)): ?>
                        <li><a href="float_accounts.php"  class="<?= isActive('float_accounts.php') ?>">Float Accounts</a></li>
                        <li><a href="float_movement.php"  class="<?= isActive('float_movement.php') ?>">Float Movements</a></li>
                        <?php endif; ?>
                        <?php if (hasPerm($userPerms, 'transfer_float', $userRole)): ?>
                        <li><a href="float_transfer.php"  class="<?= isActive('float_transfer.php') ?>">Transfer Float</a></li>
                        <?php endif; ?>
                    </ul>
                </li>
                <?php endif; ?>

                <!-- ── REPORTS ── -->
                <?php if (hasPerm($userPerms, 'view_reports', $userRole)): ?>
                <li class="menu-title"><span>Reports</span></li>

                <?php
                $rptPages = ['reports.php','branch_report.php','agent_report.php','commission_report.php'];
                ?>
                <li>
                    <a class="<?= isGroupActive($rptPages) ?>"
                       data-bs-toggle="collapse" href="#reportsMenu"
                       aria-expanded="<?= isGroupOpen($rptPages) ? 'true' : 'false' ?>">
                        <i class="ph-duotone ph-file-text"></i>
                        Reports
                        <span class="item-count">4</span>
                    </a>
                    <ul class="collapse <?= isGroupOpen($rptPages) ?>" id="reportsMenu">
                        <li><a href="reports.php"           class="<?= isActive('reports.php') ?>">Daily Summary</a></li>
                        <li><a href="branch_report.php"     class="<?= isActive('branch_report.php') ?>">Branch Comparison</a></li>
                        <li><a href="agent_report.php"      class="<?= isActive('agent_report.php') ?>">Agent Performance</a></li>
                        <li><a href="commission_report.php" class="<?= isActive('commission_report.php') ?>">Commissions</a></li>
                    </ul>
                </li>
                <?php endif; ?>

                <!-- ── ADMINISTRATION ── -->
                <?php if (hasPerm($userPerms, 'manage_users', $userRole)     ||
                          hasPerm($userPerms, 'manage_locations', $userRole)  ||
                          hasPerm($userPerms, 'manage_businesses', $userRole) ||
                          hasPerm($userPerms, 'view_audit_log', $userRole)): ?>
                <li class="menu-title"><span>Administration</span></li>

                <?php
                $adminPages = ['users.php','locations.php','businesses.php','audit_log.php','commission_rates.php'];
                ?>
                <li>
                    <a class="<?= isGroupActive($adminPages) ?>"
                       data-bs-toggle="collapse" href="#adminMenu"
                       aria-expanded="<?= isGroupOpen($adminPages) ? 'true' : 'false' ?>">
                        <i class="ph-duotone ph-gear"></i>
                        Administration
                        <span class="item-count">5</span>
                    </a>
                    <ul class="collapse <?= isGroupOpen($adminPages) ?>" id="adminMenu">
                        <?php if (hasPerm($userPerms, 'manage_users', $userRole)): ?>
                        <li><a href="users.php"            class="<?= isActive('users.php') ?>">Users</a></li>
                        <?php endif; ?>
                        <?php if (hasPerm($userPerms, 'manage_locations', $userRole)): ?>
                        <li><a href="locations.php"        class="<?= isActive('locations.php') ?>">Locations</a></li>
                        <?php endif; ?>
                        <?php if (hasPerm($userPerms, 'manage_businesses', $userRole)): ?>
                        <li><a href="businesses.php"       class="<?= isActive('businesses.php') ?>">Businesses</a></li>
                        <li><a href="commission_rates.php" class="<?= isActive('commission_rates.php') ?>">Commission Rates</a></li>
                        <?php endif; ?>
                        <?php if (hasPerm($userPerms, 'view_audit_log', $userRole)): ?>
                        <li><a href="audit_log.php"        class="<?= isActive('audit_log.php') ?>">Audit Log</a></li>
                        <?php endif; ?>
                    </ul>
                </li>
                <?php endif; ?>

                <!-- ── MY ACCOUNT ── -->
                <li class="menu-title"><span>My Account</span></li>

                <li class="no-sub">
                    <a href="profile.php" class="<?= isActive('profile.php') ?>">
                        <i class="ph-duotone ph-user"></i> My Profile
                    </a>
                </li>
                <li class="no-sub">
                    <a href="change_password.php" class="<?= isActive('change_password.php') ?>">
                        <i class="ph-duotone ph-lock-key"></i> Change Password
                    </a>
                </li>
                <li class="no-sub">
                    <a href="logout.php" class="text-danger">
                        <i class="ph-duotone ph-sign-out"></i> Logout
                    </a>
                </li>

            </ul>
        </div>
    </nav>
</div>

<!-- ===================== STYLES ===================== -->
<style>
.sidebar {
    width: 280px; background: #fff;
    box-shadow: 2px 0 10px rgba(0,0,0,.1);
    height: 100vh; position: fixed;
    left: 0; top: 0; z-index: 1000; overflow-y: auto;
}
.app-logo {
    padding: 1rem; border-bottom: 1px solid #e9ecef;
    display: flex; align-items: center; justify-content: space-between;
}
.user-info-sidebar {
    padding: 1rem 1.5rem; border-bottom: 1px solid #e9ecef;
    display: flex; align-items: center; gap: .75rem;
}
.user-avatar {
    width: 40px; height: 40px; border-radius: 50%;
    background: linear-gradient(135deg,#667eea 0%,#764ba2 100%);
    color: #fff; display: flex; align-items: center;
    justify-content: center; font-weight: 600; font-size: .875rem;
}
.user-details { flex: 1; }
.user-name   { font-weight: 600; color: #495057; font-size: .875rem; margin-bottom: .25rem; }
.user-role   { font-size: .75rem; color: #6c757d; text-transform: uppercase; letter-spacing: .5px; }
.user-permissions { font-size: .65rem; color: #8391a2; margin-top: .25rem; }
.main-nav    { list-style: none; padding: 0; margin: 0; }
.menu-title  { padding: 1rem 1.5rem .5rem; font-size: .75rem; font-weight: 600;
               text-transform: uppercase; color: #6c757d; letter-spacing: .5px; }
.main-nav > li > a {
    display: flex; align-items: center;
    padding: .75rem 1.5rem; color: #495057; text-decoration: none;
    transition: all .3s; border-left: 3px solid transparent;
}
.main-nav > li > a:hover,
.main-nav > li > a.active {
    background: #f8f9fa; color: #0d6efd; border-left-color: #0d6efd;
}
.main-nav > li > a i { margin-right: .75rem; font-size: 1.25rem; width: 20px; }
.item-count {
    margin-left: auto; background: #e9ecef; color: #6c757d;
    font-size: .75rem; padding: .25rem .5rem; border-radius: 1rem; font-weight: 600;
}
.main-nav > li > a.active .item-count { background: #0d6efd; color: #fff; }
.main-nav ul { list-style: none; padding: 0; margin: 0; background: #f8f9fa; }
.main-nav ul li a {
    display: block; padding: .5rem 1.5rem .5rem 3.5rem;
    color: #6c757d; text-decoration: none; transition: all .3s; position: relative;
}
.main-nav ul li a:hover,
.main-nav ul li a.active { color: #0d6efd; background: #e3f2fd; }
.main-nav ul li a.active::before {
    content: ''; position: absolute; left: 3rem; top: 50%;
    transform: translateY(-50%); width: 4px; height: 4px;
    background: #0d6efd; border-radius: 50%;
}
.toggle-semi-nav { cursor: pointer; padding: .25rem .5rem; border-radius: .25rem; transition: all .3s; }
.toggle-semi-nav:hover { background: #e9ecef; }
.text-danger { color: #dc3545 !important; }
.text-danger:hover { color: #bb2d3b !important; background: #f8d7da !important; }
@media (max-width: 768px) {
    .sidebar { transform: translateX(-100%); transition: transform .3s; }
    .sidebar.show { transform: translateX(0); }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Mobile toggle
    const toggleBtn = document.querySelector('.toggle-semi-nav');
    const sidebar   = document.querySelector('.sidebar');
    if (toggleBtn && sidebar) {
        toggleBtn.addEventListener('click', e => { e.preventDefault(); sidebar.classList.toggle('show'); });
    }
    document.addEventListener('click', e => {
        if (window.innerWidth <= 768 && sidebar && !sidebar.contains(e.target))
            sidebar.classList.remove('show');
    });
});
</script>