<?php
ob_start();
if (session_status() === PHP_SESSION_NONE) {
    @session_start();
}
$currentPage = basename($_SERVER['PHP_SELF']);
$user = $_SESSION['user'] ?? null;

if ($user && isset($user['id'])) {
    if (!isset($conn)) {
        require_once __DIR__ . '/db.php';
    }
    if (isset($conn)) {
        $stmt = $conn->prepare("SELECT permissions, status FROM users WHERE id = ?");
        $stmt->bind_param('i', $user['id']);
        $stmt->execute();
        $db_user = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if ($db_user) {
            $user['permissions'] = json_decode($db_user['permissions'], true) ?: [];
            $user['status'] = $db_user['status'];
            $_SESSION['user'] = $user;
        }
    }
}

function hasPagePermission($pageKey) {
    global $user;
    if (!$user) return false;
    if (isset($user['username']) && strtolower($user['username']) === 'admin') {
        return true;
    }
    return isset($user['permissions'][$pageKey]['view']) && $user['permissions'][$pageKey]['view'] === true;
}
?>
<!-- Sidebar Menu -->
<aside class="sidebar">
    <div class="sidebar-brand">
        <i class="fa-solid fa-layer-group brand-icon"></i>
        <h2>لوحة التحكم</h2>
        <button class="sidebar-close-btn" id="sidebar-close-btn">&times;</button>
    </div>
    <nav class="sidebar-menu">
        <?php if (hasPagePermission('index')): ?>
        <a href="index.php" class="menu-item <?php echo $currentPage == 'index.php' ? 'active' : ''; ?>"><i class="fa-solid fa-chart-pie"></i> الرئيسية</a>
        <?php endif; ?>

        <?php if (hasPagePermission('forms')): ?>
        <a href="forms.php" class="menu-item <?php echo $currentPage == 'forms.php' ? 'active' : ''; ?>"><i class="fa-solid fa-file-signature"></i> الاستمارات</a>
        <?php endif; ?>

        <?php if (hasPagePermission('debts')): ?>
        <a href="debts.php" class="menu-item <?php echo $currentPage == 'debts.php' ? 'active' : ''; ?>"><i class="fa-solid fa-file-invoice-dollar"></i> إدارة الديون</a>
        <?php endif; ?>

        <?php if (hasPagePermission('materials')): ?>
        <a href="materials.php" class="menu-item <?php echo $currentPage == 'materials.php' ? 'active' : ''; ?>"><i class="fa-solid fa-boxes-stacked"></i> إضافة المادة</a>
        <?php endif; ?>

        <?php if (hasPagePermission('materials_report')): ?>
        <a href="materials_report.php" class="menu-item <?php echo $currentPage == 'materials_report.php' ? 'active' : ''; ?>"><i class="fa-solid fa-clipboard-list"></i> كشف المواد</a>
        <?php endif; ?>

        <?php if (hasPagePermission('gatherers_report')): ?>
        <a href="gatherers_report.php" class="menu-item <?php echo $currentPage == 'gatherers_report.php' ? 'active' : ''; ?>"><i class="fa-solid fa-truck-fast"></i> كشف الجلابين</a>
        <?php endif; ?>

        <?php if (hasPagePermission('settlements')): ?>
        <a href="settlements.php" class="menu-item <?php echo $currentPage == 'settlements.php' ? 'active' : ''; ?>"><i class="fa-solid fa-scale-balanced"></i> التسويات المالية</a>
        <?php endif; ?>

        <?php if (hasPagePermission('calibration')): ?>
        <a href="calibration.php" class="menu-item <?php echo $currentPage == 'calibration.php' ? 'active' : ''; ?>"><i class="fa-solid fa-sliders"></i> المعايرة</a>
        <?php endif; ?>

        <?php if (hasPagePermission('gatherers')): ?>
        <a href="gatherers.php" class="menu-item <?php echo $currentPage == 'gatherers.php' ? 'active' : ''; ?>"><i class="fa-solid fa-people-carry-box"></i> إدارة الجلابين</a>
        <?php endif; ?>

        <?php if (hasPagePermission('pricing')): ?>
        <a href="pricing.php" class="menu-item <?php echo $currentPage == 'pricing.php' ? 'active' : ''; ?>"><i class="fa-solid fa-tag"></i> تسعير الاستمارات</a>
        <?php endif; ?>

        <?php if (hasPagePermission('customers')): ?>
        <a href="customers.php" class="menu-item <?php echo $currentPage == 'customers.php' ? 'active' : ''; ?>"><i class="fa-solid fa-users"></i> إدارة العملاء</a>
        <?php endif; ?>

        <?php if (hasPagePermission('safes')): ?>
        <a href="safes.php" class="menu-item <?php echo $currentPage == 'safes.php' ? 'active' : ''; ?>"><i class="fa-solid fa-vault"></i> صناديق الأموال</a>
        <?php endif; ?>

        <?php if (hasPagePermission('users')): ?>
        <a href="users.php" class="menu-item <?php echo $currentPage == 'users.php' ? 'active' : ''; ?>"><i class="fa-solid fa-users-gear"></i> المستخدمين</a>
        <?php endif; ?>

        <?php if (hasPagePermission('activity_logs')): ?>
        <a href="activity_logs.php" class="menu-item <?php echo $currentPage == 'activity_logs.php' ? 'active' : ''; ?>"><i class="fa-solid fa-history"></i> سجل العمليات</a>
        <?php endif; ?>

        <?php if (hasPagePermission('settings')): ?>
        <a href="settings.php" class="menu-item <?php echo $currentPage == 'settings.php' ? 'active' : ''; ?>"><i class="fa-solid fa-gears"></i> إعدادات النظام</a>
        <?php endif; ?>
    </nav>
    <div class="sidebar-footer">
        <div class="user-profile">
            <div class="avatar">أ</div>
            <div class="user-info">
                <span class="user-name">المدير العام</span>
                <span class="user-role">مسؤول النظام</span>
            </div>
        </div>
        <button id="btn-logout" class="logout-btn" title="تسجيل الخروج">
            <i class="fa-solid fa-right-from-bracket"></i>
        </button>
    </div>
</aside>

<script>
document.addEventListener("DOMContentLoaded", () => {
    const toggleBtn = document.getElementById("mobile-menu-toggle");
    const closeBtn = document.getElementById("sidebar-close-btn");
    const sidebar = document.querySelector(".sidebar");
    
    if (toggleBtn && sidebar) {
        toggleBtn.addEventListener("click", (e) => {
            e.stopPropagation();
            sidebar.classList.add("open");
        });
    }
    
    if (closeBtn && sidebar) {
        closeBtn.addEventListener("click", (e) => {
            e.stopPropagation();
            sidebar.classList.remove("open");
        });
    }

    // Close sidebar when clicking anywhere else
    document.addEventListener("click", (e) => {
        if (sidebar && sidebar.classList.contains("open") && !sidebar.contains(e.target) && e.target !== toggleBtn) {
            sidebar.classList.remove("open");
        }
    });
});
</script>
