<?php
/**
 * Sidebar component — reads menu items from MenuRegistry.
 * Uses Lucide icons instead of emojis for a professional look.
 */

use App\Core\App;
use App\Core\Registries\MenuRegistry;
use App\Modules\Settings\Services\BrandingService;

$currentPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$employee = App::getInstance()->currentEmployee();

// Icon name → Lucide icon mapping (includes legacy names, short names, and emoji fallbacks)
$iconMap = [
    'dashboard' => 'layout-dashboard', 'tachometer-alt' => 'gauge', 'home' => 'home',
    'users' => 'users', 'user' => 'user', 'user-plus' => 'user-plus', 'user-clock' => 'user-cog',
    'user-tie' => 'briefcase', 'user-shield' => 'shield-check', 'user-friends' => 'users',
    'clipboard' => 'clipboard-list', 'clipboard-list' => 'clipboard-list', 'file-alt' => 'file-text',
    'calendar' => 'calendar', 'calendar-alt' => 'calendar-days', 'calendar-check' => 'calendar-check',
    'money-bill' => 'banknote', 'wallet' => 'wallet', 'cash-register' => 'banknote',
    'credit-card' => 'credit-card', 'receipt' => 'receipt', 'coins' => 'coins',
    'file-invoice-dollar' => 'file-text', 'hand-holding-usd' => 'hand-coins',
    'exchange-alt' => 'arrow-left-right', 'random' => 'shuffle', 'transfer' => 'arrow-left-right',
    'swap' => 'arrow-left-right',
    'gavel' => 'gavel', 'balance-scale' => 'scale', 'exclamation-triangle' => 'alert-triangle',
    'alert' => 'alert-triangle', 'warning' => 'alert-triangle', 'ban' => 'ban',
    'trophy' => 'trophy', 'medal' => 'medal', 'award' => 'award', 'star' => 'star',
    'globe' => 'globe', 'globe-americas' => 'globe-2', 'flag' => 'flag',
    'id-card' => 'id-card', 'address-card' => 'contact', 'qrcode' => 'qr-code',
    'file' => 'file-text', 'folder' => 'folder', 'folder-open' => 'folder-open',
    'sms' => 'smartphone', 'envelope' => 'mail', 'bell' => 'bell', 'comment' => 'message-circle',
    'chart' => 'bar-chart-3', 'chart-bar' => 'bar-chart-3', 'chart-line' => 'trending-up', 'chart-pie' => 'pie-chart',
    'cog' => 'settings', 'cogs' => 'settings-2', 'wrench' => 'wrench', 'tools' => 'wrench',
    'sliders-h' => 'sliders-horizontal', 'settings' => 'settings',
    'shield-alt' => 'shield', 'lock' => 'lock', 'key' => 'key-round',
    'building' => 'building-2', 'city' => 'building', 'store' => 'store',
    'book' => 'book-open', 'history' => 'history', 'archive' => 'archive',
    'sitemap' => 'git-branch', 'project-diagram' => 'workflow', 'workflow' => 'workflow',
    'heart' => 'heart', 'heartbeat' => 'heart-pulse', 'cross' => 'cross',
    'ring' => 'gem', 'baby' => 'baby', 'child' => 'user', 'children' => 'users',
    'repeat' => 'repeat', 'sync' => 'refresh-cw', 'redo' => 'redo',
    'print' => 'printer', 'search' => 'search', 'plus' => 'plus', 'edit' => 'pencil',
    'trash' => 'trash-2', 'times' => 'x', 'check' => 'check',
    'dollar-sign' => 'circle-dollar-sign', 'percentage' => 'percent',
    'swimming-pool' => 'waves', 'running' => 'activity', 'futbol' => 'trophy',
    'sun' => 'sun', 'umbrella-beach' => 'umbrella',
    // Emoji → Lucide fallbacks (some modules still register emojis)
    '📊' => 'layout-dashboard', '🏠' => 'home',
    '👥' => 'users', '👤' => 'user', '⏰' => 'clock',
    '👔' => 'briefcase', '🛡️' => 'shield-check',
    '📋' => 'clipboard-list', '📄' => 'file-text',
    '📅' => 'calendar', '✅' => 'check-circle',
    '💰' => 'banknote', '💳' => 'wallet', '🧾' => 'receipt', '🪙' => 'coins',
    '💲' => 'circle-dollar-sign',
    '🔀' => 'arrow-left-right',
    '⚖️' => 'scale', '⚠️' => 'alert-triangle', '🚫' => 'ban',
    '🏆' => 'trophy', '🏅' => 'medal', '🎖️' => 'award', '⭐' => 'star',
    '🌍' => 'globe', '🌎' => 'globe', '🏳️' => 'flag',
    '🪪' => 'id-card', '📱' => 'smartphone',
    '📁' => 'folder', '📂' => 'folder-open',
    '✉️' => 'mail', '🔔' => 'bell', '💬' => 'message-circle',
    '📈' => 'trending-up',
    '⚙️' => 'settings', '🔧' => 'wrench', '🛠️' => 'wrench',
    '🔐' => 'shield', '🔒' => 'lock', '🔑' => 'key-round',
    '🏢' => 'building-2', '🏙️' => 'building', '🏪' => 'store',
    '📖' => 'book-open', '📜' => 'history', '🗄️' => 'archive',
    '🔄' => 'refresh-cw',
    '❤️' => 'heart', '💓' => 'heart-pulse', '✝️' => 'cross',
    '💍' => 'gem', '👶' => 'baby', '👦' => 'user', '👨‍👩‍👧‍👦' => 'users',
    '🖨️' => 'printer', '🔍' => 'search', '➕' => 'plus', '✏️' => 'pencil',
    '🗑️' => 'trash-2', '❌' => 'x',
    '💹' => 'percent',
    '🏊' => 'waves', '🏃' => 'activity', '⚽' => 'trophy',
    '☀️' => 'sun', '🏖️' => 'umbrella',
    '📌' => 'circle',
];

$getIcon = function(?string $icon) use ($iconMap): string {
    if ($icon === null || $icon === '') return 'circle';
    // Direct lookup (handles both text keys and emoji keys)
    if (isset($iconMap[$icon])) return $iconMap[$icon];
    $lower = strtolower($icon);
    if (isset($iconMap[$lower])) return $iconMap[$lower];
    // Check if it looks like a valid Lucide icon name already
    if (preg_match('/^[a-z][a-z0-9-]+$/', $lower)) return $lower;
    return 'circle';
};

// Get all permissions for current employee
$employeePermissions = [];
if ($employee && method_exists($employee, 'getAllPermissions')) {
    $employeePermissions = $employee->getAllPermissions();
} elseif ($employee) {
    try {
        $db = App::getInstance()->db();
        $empId = $employee->id ?? 0;
        $perms = $db->select(
            "SELECT DISTINCT rp.permission_key
             FROM employee_roles er
             JOIN role_permissions rp ON rp.role_id = er.role_id
             WHERE er.employee_id = ? AND er.is_active = 1",
            [(int) $empId]
        );
        $employeePermissions = array_column($perms, 'permission_key');

        $isSuperAdmin = $db->selectOne(
            "SELECT 1 FROM employee_roles er
             JOIN roles r ON r.id = er.role_id
             WHERE er.employee_id = ? AND r.role_code = 'super_admin' AND er.is_active = 1
             LIMIT 1",
            [(int) $empId]
        );
        if ($isSuperAdmin) {
            $employeePermissions = ['*'];
        }
    } catch (\Throwable $e) {
        $employeePermissions = [];
    }
}

$hasPerm = function(string $perm) use ($employeePermissions): bool {
    if (empty($perm)) return true;
    if (in_array('*', $employeePermissions)) return true;
    return in_array($perm, $employeePermissions);
};

$isActive = function(string $route) use ($currentPath): bool {
    if ($route === '/') return $currentPath === '/';
    return str_starts_with($currentPath, $route);
};

// Get menu items from registry
$menuItems = MenuRegistry::getAll();
usort($menuItems, fn($a, $b) => ($a['order'] ?? 999) <=> ($b['order'] ?? 999));

// Fallback if registry empty
if (empty($menuItems)) {
    $menuItems = [
        ['key' => 'dashboard', 'label_ar' => 'لوحة التحكم', 'icon' => 'dashboard', 'route' => '/dashboard', 'permission' => '', 'order' => 10, 'children' => []],
        ['key' => 'members', 'label_ar' => 'إدارة الأعضاء', 'icon' => 'users', 'route' => '/members', 'permission' => 'member.view', 'order' => 100, 'children' => [
            ['label_ar' => 'كل الأعضاء', 'route' => '/members', 'permission' => 'member.view'],
            ['label_ar' => 'عضو جديد', 'route' => '/members/create', 'permission' => 'member.create'],
        ]],
        ['key' => 'users', 'label_ar' => 'الموظفون', 'icon' => 'user', 'route' => '/users', 'permission' => 'user.view', 'order' => 910, 'children' => []],
        ['key' => 'roles', 'label_ar' => 'الأدوار', 'icon' => 'shield-alt', 'route' => '/roles', 'permission' => 'role.view', 'order' => 920, 'children' => []],
        ['key' => 'branches', 'label_ar' => 'الفروع', 'icon' => 'building', 'route' => '/branches', 'permission' => 'branch.view', 'order' => 930, 'children' => []],
        ['key' => 'settings', 'label_ar' => 'الإعدادات', 'icon' => 'settings', 'route' => '/settings', 'permission' => 'settings.view', 'order' => 960, 'children' => []],
    ];
}
?>

<div class="sidebar-header">
    <?php $brandLogo = BrandingService::logo(); ?>
    <?php if ($brandLogo): ?>
        <img src="<?= e($brandLogo) ?>" alt="<?= e(BrandingService::clubNameEn()) ?>" class="sidebar-logo">
    <?php else: ?>
        <div class="sidebar-brand"><?= e(BrandingService::clubNameEn()) ?></div>
    <?php endif; ?>
</div>

<nav class="sidebar-nav">
    <ul class="sidebar-menu">
        <?php foreach ($menuItems as $item): ?>
            <?php
            if (!empty($item['parent'])) continue;
            if (!empty($item['permission']) && !$hasPerm($item['permission'])) continue;

            if (!empty($item['is_separator'])) {
                echo '<li class="sidebar-section-label">' . e($item['label_ar']) . '</li>';
                continue;
            }

            $children = $item['children'] ?? [];
            $visibleChildren = [];
            foreach ($children as $child) {
                if (empty($child['permission']) || $hasPerm($child['permission'])) {
                    $visibleChildren[] = $child;
                }
            }

            $hasChildren = !empty($visibleChildren);
            $itemRoute = $item['route'] ?? '#';
            $itemActive = $isActive($itemRoute);

            $childActive = false;
            foreach ($visibleChildren as $child) {
                if ($isActive($child['route'] ?? '')) { $childActive = true; break; }
            }

            $isOpen = $itemActive || $childActive;
            $iconName = $getIcon($item['icon'] ?? '');
            ?>
            <li class="sidebar-item<?= $isOpen && $hasChildren ? ' open' : '' ?>">
                <?php if ($hasChildren): ?>
                    <a href="javascript:void(0)" class="sidebar-link<?= $itemActive ? ' active' : '' ?>" onclick="toggleSubmenu(this)">
                        <span class="sidebar-icon"><i data-lucide="<?= e($iconName) ?>"></i></span>
                        <span class="sidebar-text"><?= e($item['label_ar']) ?></span>
                        <span class="sidebar-arrow"><i data-lucide="chevron-down"></i></span>
                    </a>
                    <ul class="sidebar-submenu"<?= $isOpen ? '' : ' style="display:none;"' ?>>
                        <?php foreach ($visibleChildren as $child): ?>
                            <?php $childRoute = $child['route'] ?? '#'; ?>
                            <li>
                                <a href="<?= e($childRoute) ?>" class="sidebar-sublink<?= $isActive($childRoute) ? ' active' : '' ?>">
                                    <?= e($child['label_ar']) ?>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <a href="<?= e($itemRoute) ?>" class="sidebar-link<?= $itemActive ? ' active' : '' ?>">
                        <span class="sidebar-icon"><i data-lucide="<?= e($iconName) ?>"></i></span>
                        <span class="sidebar-text"><?= e($item['label_ar']) ?></span>
                    </a>
                <?php endif; ?>
            </li>
        <?php endforeach; ?>
    </ul>
</nav>
