<?php
if (!function_exists('ec_role_layout_t')) {
    function ec_role_layout_t(string $key, string $fallback): string {
        if (function_exists('ec_t')) return ec_t($key, $fallback);
        if (function_exists('t')) return t($key, $fallback);
        return $fallback;
    }
}

if (!function_exists('ec_role_layout_role_label')) {
    function ec_role_layout_role_label(string $role): string {
        $role = trim($role);
        $key = 'role.' . $role;
        $fallback = ucwords(str_replace('_', ' ', $role));
        return ec_role_layout_t($key, $fallback);
    }
}


if (!function_exists('ec_role_layout_db_can_view')) {
    function ec_role_layout_db_can_view(string $url, string $roleCode): bool
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if ($roleCode === 'super_admin') {
            return true;
        }

        if ($url === '/easychair/admin/rbac-matrix') {
            return false;
        }

        try {
            if (!class_exists('\App\Core\Database')) {
                return true;
            }

            $db = \App\Core\Database::getInstance();

            $confId = (int)($_SESSION['conference_id'] ?? 0);
            $orgId  = (int)($_SESSION['org_id'] ?? 0);

            $stmt = $db->prepare("
                SELECT
                    rp.id,
                    rp.is_allowed,
                    rp.can_view,
                    rp.conference_id,
                    rp.org_id
                FROM rbac_menu_items mi
                JOIN rbac_role_menu_permissions rp ON rp.menu_item_id = mi.id
                JOIN roles r ON r.id = rp.role_id
                WHERE mi.url = ?
                  AND r.code = ?
                  AND (rp.conference_id = ? OR rp.conference_id IS NULL)
                  AND (rp.org_id = ? OR rp.org_id IS NULL)
                ORDER BY
                    CASE WHEN rp.conference_id = ? THEN 0 ELSE 1 END,
                    CASE WHEN rp.org_id = ? THEN 0 ELSE 1 END,
                    rp.id DESC
                LIMIT 1
            ");

            $stmt->execute([
                $url,
                $roleCode,
                $confId,
                $orgId,
                $confId,
                $orgId,
            ]);

            $row = $stmt->fetch(\PDO::FETCH_ASSOC);

            /*
             * No DB row means fallback to static role rules.
             * Existing DB row is authoritative:
             * - can_view=0 hides even if is_allowed=1.
             * - is_allowed=0 hides.
             */
            if (!$row) {
                return true;
            }

            return ((int)($row['is_allowed'] ?? 0) === 1)
                && ((int)($row['can_view'] ?? 0) === 1);
        } catch (\Throwable $e) {
            return $url !== '/easychair/admin/rbac-matrix';
        }
    }
}


if (!function_exists('ec_role_layout_all_links')) {
    function ec_role_layout_all_links(): array {
        return [
            [
                'group' => 'menu.group.core',
                'group_fallback' => 'Core',
                'items' => [
                    ['url'=>'/easychair/admin/dashboard', 'icon'=>'fa-gauge-high', 'label_key'=>'menu.dashboard', 'label'=>'Dashboard', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair','track_chair','section_editor']],
                    ['url'=>'/easychair/admin/conferences', 'icon'=>'fa-folder-open', 'label_key'=>'menu.conferences', 'label'=>'Conferences', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair']],
                    ['url'=>'/easychair/admin/organizations', 'icon'=>'fa-building', 'label_key'=>'menu.organizations', 'label'=>'Organizations', 'roles'=>['super_admin']],
                ],
            ],

            [
                'group' => 'menu.group.conference_setup',
                'group_fallback' => 'Conference Setup',
                'items' => [
                    ['url'=>'/easychair/admin/conference-home', 'icon'=>'fa-palette', 'label_key'=>'menu.smart_homepage', 'label'=>'Smart Homepage', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair']],
                    ['url'=>'/easychair/admin/branding', 'icon'=>'fa-image', 'label_key'=>'menu.branding', 'label'=>'Branding & Logos', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair']],
                    ['url'=>'/easychair/admin/committee-images', 'icon'=>'fa-images', 'label_key'=>'menu.committee_images', 'label'=>'Committee & Participant Images', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair']],
                    ['url'=>'/easychair/admin/conference-business', 'icon'=>'fa-calendar-days', 'label_key'=>'menu.business_sessions_issues', 'label'=>'Business, Sessions & Issues', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair','track_chair']],
                ],
            ],

            [
                'group' => 'menu.group.submission_review',
                'group_fallback' => 'Submissions & Reviews',
                'items' => [
                    ['url'=>'/easychair/admin/submission-search', 'icon'=>'fa-search', 'label_key'=>'menu.submission_search', 'label'=>'Submission Search', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair','track_chair','section_editor']],
                    ['url'=>'/easychair/admin/submissions', 'icon'=>'fa-inbox', 'label_key'=>'menu.submissions', 'label'=>'Submissions', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair','track_chair','section_editor']],
                    ['url'=>'/easychair/admin/reviewer-assignments', 'icon'=>'fa-user-plus', 'label_key'=>'menu.reviewer_assignment', 'label'=>'Reviewer Assignment', 'roles'=>['super_admin','org_admin','admin','conference_chair','track_chair','section_editor']],
                    ['url'=>'/easychair/admin/reviewers', 'icon'=>'fa-user-check', 'label_key'=>'menu.reviewers', 'label'=>'Reviewers', 'roles'=>['super_admin','org_admin','admin','conference_chair','track_chair']],
                    ['url'=>'/easychair/admin/reviewer-expertise', 'icon'=>'fa-brain', 'label_key'=>'menu.reviewer_expertise', 'label'=>'Reviewer Expertise', 'roles'=>['super_admin','org_admin','admin','conference_chair','track_chair']],
                    ['url'=>'/easychair/admin/review-form', 'icon'=>'fa-clipboard-list', 'label_key'=>'menu.review_form', 'label'=>'Review Form', 'roles'=>['super_admin','org_admin','admin','conference_chair']],
                    ['url'=>'/easychair/admin/review-monitor', 'icon'=>'fa-chart-line', 'label_key'=>'menu.review_monitor', 'label'=>'Review Monitor', 'roles'=>['super_admin','org_admin','admin','conference_chair','track_chair']],
                    ['url'=>'/easychair/admin/decisions', 'icon'=>'fa-gavel', 'label_key'=>'menu.decisions', 'label'=>'Decisions', 'roles'=>['super_admin','org_admin','admin','conference_chair']],
                    ['url'=>'/easychair/admin/workflow', 'icon'=>'fa-diagram-project', 'label_key'=>'menu.workflow', 'label'=>'Workflow', 'roles'=>['super_admin','org_admin','admin','conference_chair']],
                    ['url'=>'/easychair/admin/workflow-notifications', 'icon'=>'fa-bell', 'label_key'=>'menu.workflow_notifications', 'label'=>'Workflow Notifications', 'roles'=>['super_admin','org_admin','admin','conference_chair']],
                    ['url'=>'/easychair/admin/submission-stage-rules', 'icon'=>'fa-list-ol', 'label_key'=>'menu.submission_stage_rules', 'label'=>'Submission Stage Rules', 'roles'=>['super_admin','org_admin','admin','conference_chair']],
                ],
            ],

            [
                'group' => 'menu.group.production_publish',
                'group_fallback' => 'Production & Publishing',
                'items' => [
                    ['url'=>'/easychair/admin/production', 'icon'=>'fa-industry', 'label_key'=>'menu.production', 'label'=>'Production / Camera-ready', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair']],
                    ['url'=>'/easychair/admin/issues', 'icon'=>'fa-book', 'label_key'=>'menu.issues', 'label'=>'Issues / Proceedings', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair']],
                    ['url'=>'/easychair/admin/certificates', 'icon'=>'fa-certificate', 'label_key'=>'menu.certificates', 'label'=>'Certificates', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair']],
                ],
            ],

            [
                'group' => 'menu.group.communication',
                'group_fallback' => 'Communication',
                'items' => [
                    ['url'=>'/easychair/admin/email-templates', 'icon'=>'fa-envelope-open-text', 'label_key'=>'menu.email_templates', 'label'=>'Email Templates', 'roles'=>['super_admin','org_admin','admin','conference_chair']],
                    ['url'=>'/easychair/admin/conference-mail', 'icon'=>'fa-envelope-circle-check', 'label_key'=>'menu.conference_mail', 'label'=>'Conference Mail', 'roles'=>['super_admin','org_admin','admin','conference_chair']],
                    ['url'=>'/easychair/admin/org-smtp', 'icon'=>'fa-server', 'label_key'=>'menu.org_smtp', 'label'=>'Organization SMTP', 'roles'=>['super_admin','org_admin','admin']],
                    ['url'=>'/easychair/admin/test-email', 'icon'=>'fa-paper-plane', 'label_key'=>'menu.test_email', 'label'=>'Test Email', 'roles'=>['super_admin','org_admin','admin']],
                    ['url'=>'/easychair/admin/notification-broadcast', 'icon'=>'fa-bullhorn', 'label_key'=>'menu.notification_broadcast', 'label'=>'Notification Broadcast', 'roles'=>['super_admin','org_admin','admin','conference_chair']],
                    ['url'=>'/easychair/admin/notification-digest', 'icon'=>'fa-newspaper', 'label_key'=>'menu.notification_digest', 'label'=>'Notification Digest', 'roles'=>['super_admin','org_admin','admin']],
                    ['url'=>'/easychair/admin/notification-audit', 'icon'=>'fa-bell-circle-check', 'label_key'=>'menu.notification_audit', 'label'=>'Notification Audit', 'roles'=>['super_admin','org_admin','admin']],
                ],
            ],

            [
                'group' => 'menu.group.people_permissions',
                'group_fallback' => 'People & Permissions',
                'items' => [
                    ['url'=>'/easychair/admin/users', 'icon'=>'fa-users', 'label_key'=>'menu.users_management', 'label'=>'Users Management', 'roles'=>['super_admin','org_admin','admin']],
                    ['url'=>'/easychair/admin/roles', 'icon'=>'fa-user-shield', 'label_key'=>'menu.roles', 'label'=>'Roles', 'roles'=>['super_admin','org_admin','admin']],
                    ['url'=>'/easychair/admin/rbac-matrix', 'icon'=>'fa-sliders', 'label_key'=>'menu.rbac_matrix', 'label'=>'RBAC Matrix', 'roles'=>['super_admin']],
                    ['url'=>'/easychair/admin/access-audit', 'icon'=>'fa-shield-halved', 'label_key'=>'menu.access_audit', 'label'=>'Access Audit', 'roles'=>['super_admin']],
                    ['url'=>'/easychair/admin/rbac-scope', 'icon'=>'fa-copy', 'label_key'=>'menu.rbac_scope', 'label'=>'RBAC Scope Manager', 'roles'=>['super_admin','org_admin','admin']],
                    ['url'=>'/easychair/admin/conference-role-permissions', 'icon'=>'fa-user-lock', 'label_key'=>'menu.conference_role_permissions', 'label'=>'Conference Role Permissions', 'roles'=>['super_admin','org_admin']],
                    ['url'=>'/easychair/admin/conference-business-permissions', 'icon'=>'fa-shield-halved', 'label_key'=>'menu.conference_business_permissions', 'label'=>'Conference Business Permissions', 'roles'=>['super_admin','org_admin']],
                    ['url'=>'/easychair/admin/custom-rights', 'icon'=>'fa-key', 'label_key'=>'menu.custom_rights', 'label'=>'Custom Rights', 'roles'=>['super_admin']],
                    ['url'=>'/easychair/admin/profile-completion', 'icon'=>'fa-chart-pie', 'label_key'=>'menu.profile_completion', 'label'=>'Profile Completion', 'roles'=>['super_admin','org_admin','admin','conference_chair']],
                    ['url'=>'/easychair/admin/profile-fields', 'icon'=>'fa-list-check', 'label_key'=>'menu.profile_fields', 'label'=>'Profile Fields', 'roles'=>['super_admin','org_admin','admin']],
                ],
            ],

            [
                'group' => 'menu.group.system_tools',
                'group_fallback' => 'System Tools',
                'items' => [
                    ['url'=>'/easychair/admin/dictionary', 'icon'=>'fa-language', 'label_key'=>'menu.dictionary', 'label'=>'Dictionary', 'roles'=>['super_admin']],
                    ['url'=>'/easychair/admin/dictionary-scan', 'icon'=>'fa-magnifying-glass', 'label_key'=>'menu.dictionary_scan', 'label'=>'Dictionary Scanner', 'roles'=>['super_admin']],
                    ['url'=>'/easychair/admin/dictionary-replace', 'icon'=>'fa-wand-magic-sparkles', 'label_key'=>'menu.dictionary_replace', 'label'=>'Dictionary Replace', 'roles'=>['super_admin']],
                ],
            ],

            [
                'group' => 'menu.group.personal',
                'group_fallback' => 'Personal',
                'items' => [
                    ['url'=>'/easychair/profile', 'icon'=>'fa-user-graduate', 'label_key'=>'menu.my_academic_profile', 'label'=>'My Academic Profile', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair','track_chair','section_editor']],
                    ['url'=>'/easychair/notifications', 'icon'=>'fa-bell', 'label_key'=>'menu.my_notifications', 'label'=>'My Notifications', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair','track_chair','section_editor']],
                    ['url'=>'/easychair/select-conference', 'icon'=>'fa-building-columns', 'label_key'=>'menu.change_conference', 'label'=>'Change Conference', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair','track_chair','section_editor']],
                    ['url'=>'/easychair/logout', 'icon'=>'fa-right-from-bracket', 'label_key'=>'menu.logout', 'label'=>'Logout', 'roles'=>['super_admin','org_admin','admin','organizer','conference_chair','track_chair','section_editor']],
                ],
            ],
        ];
    }
}

if (!function_exists('ec_role_layout_filtered_groups')) {
    function ec_role_layout_filtered_groups(string $roleCode): array {
        $groups = ec_role_layout_all_links();

        $rbac = null;
        if (class_exists('\App\Core\RbacService')) {
            try {
                $rbac = new \App\Core\RbacService();
            } catch (Throwable $e) {
                $rbac = null;
            }
        }

        $out = [];
        foreach ($groups as $group) {
            $items = [];

            foreach ($group['items'] as $item) {
                if (($item['url'] ?? '') === '/easychair/admin/rbac-matrix' && $roleCode !== 'super_admin') {
                    continue;
                }
                $allowedRoles = $item['roles'] ?? [];
                if ($roleCode !== 'super_admin' && $allowedRoles && !in_array($roleCode, $allowedRoles, true)) {
                    continue;
                }

                if (!ec_role_layout_db_can_view((string)($item['url'] ?? ''), $roleCode)) {
                    continue;
                }

                $item['label'] = ec_role_layout_t($item['label_key'] ?? '', $item['label'] ?? '');
                $items[] = $item;
            }

            if ($items) {
                $group['label'] = ec_role_layout_t($group['group'], $group['group_fallback']);
                $group['items'] = $items;
                $out[] = $group;
            }
        }

        return $out;
    }
}
