<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

//require_once BASE_PATH . '/app/views/partials/sidebar_translate.php';~
require_once BASE_PATH . '/app/helpers/easychair_translate.php';

$content = $content ?? '';

foreach ([
    '/app/helpers/conference_scope.php',
    '/app/helpers/i18n.php',
    '/app/helpers/easychair_translate.php',
    '/app/helpers/permissions.php',
    '/app/core/RbacService.php',
    '/app/views/partials/unified_role_layout_links.php',
] as $rel) {
    if (defined('BASE_PATH') && file_exists(BASE_PATH . $rel)) {
        require_once BASE_PATH . $rel;
    }
}

/* Superadmin must never be limited by conference role */
$systemRole = (string)($_SESSION['role'] ?? $_SESSION['user_role'] ?? '');
$conferenceRole = (string)($_SESSION['conference_role'] ?? '');
$isSuperAdmin = ($systemRole === 'super_admin');

$roleCode = $isSuperAdmin
    ? 'super_admin'
    : ($conferenceRole ?: ($systemRole ?: 'admin'));

if (!$isSuperAdmin && function_exists('ec_scope_role') && ec_scope_role() !== 'super_admin' && function_exists('ec_scope_auto_select_conference')) {
    ec_scope_auto_select_conference(false);
}

/* Output filter: superadmin bypass */
if (!function_exists('ec_admin_output_rbac_filter')) {
    function ec_admin_output_rbac_filter(string $html): string
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            @session_start();
        }

        if (($_SESSION['role'] ?? '') === 'super_admin') {
            return $html;
        }

        if (defined('BASE_PATH') && file_exists(BASE_PATH . '/app/helpers/permissions.php')) {
            require_once BASE_PATH . '/app/helpers/permissions.php';
        }

        $blocked = [
            '/easychair/admin/email-templates',
            '/easychair/admin/test-email',
            '/easychair/admin/rbac-matrix',
            '/admin/email-templates',
            '/admin/test-email',
            '/admin/rbac-matrix',
        ];

        foreach ($blocked as $url) {
            $full = str_starts_with($url, '/easychair/') ? $url : '/easychair' . $url;
            $allowed = function_exists('ec_can_menu') ? ec_can_menu($full) : false;

            if ($allowed) {
                continue;
            }

            $q = preg_quote($url, '~');
            foreach ([
                '~<li\b[^>]*>\s*<a\b[^>]*href=["\'][^"\']*' . $q . '[^"\']*["\'][\s\S]*?</a>\s*</li>~i',
                '~<a\b[^>]*href=["\'][^"\']*' . $q . '[^"\']*["\'][\s\S]*?</a>~i',
                '~<div\b[^>]*>\s*<a\b[^>]*href=["\'][^"\']*' . $q . '[^"\']*["\'][\s\S]*?</a>\s*</div>~i',
            ] as $pat) {
                $html = preg_replace($pat, '', $html);
            }
        }

        return $html;
    }
}

if (!defined('PACK503I_OUTPUT_FILTER_STARTED')) {
    define('PACK503I_OUTPUT_FILTER_STARTED', true);
    ob_start('ec_admin_output_rbac_filter');
}

if (!function_exists('ec_role_h')) {
    function ec_role_h($v): string {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('ec_role_t')) {
    function ec_role_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;
    }
}

$lang = function_exists('ec_lang') ? ec_lang() : ($_SESSION['lang'] ?? 'ar');
$dir = function_exists('ec_dir') ? ec_dir() : ($lang === 'en' ? 'ltr' : 'rtl');
$isRtl = $dir === 'rtl';

$userName = $_SESSION['user_name'] ?? ($_SESSION['name'] ?? ($_SESSION['email'] ?? 'User'));
$userEmail = $_SESSION['email'] ?? '';
$roleLabel = function_exists('ec_role_layout_role_label')
    ? ec_role_layout_role_label($roleCode)
    : ucwords(str_replace('_',' ', $roleCode));

$conferenceId = $_SESSION['conference_id'] ?? $_SESSION['current_conference_id'] ?? null;
$orgId = $_SESSION['org_id'] ?? null;
$conferenceShort = $_SESSION['conference_short_name'] ?? ($conferenceId ? ('Conference #' . $conferenceId) : '');
$conferenceTitle = '';
$orgName = '';

try {
    if (defined('BASE_PATH') && class_exists('\App\Core\Database')) {
        $db = \App\Core\Database::getInstance();

        if ($conferenceId) {
            $stmt = $db->prepare("
                SELECT c.short_name, c.title_en, c.title_ar, c.org_id, o.name AS org_name
                FROM conferences c
                LEFT JOIN organizations o ON o.id = c.org_id
                WHERE c.id = ?
                LIMIT 1
            ");
            $stmt->execute([(int)$conferenceId]);
            $c = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($c) {
                $conferenceShort = $c['short_name'] ?: $conferenceShort;
                $conferenceTitle = $lang === 'en'
                    ? ($c['title_en'] ?: $c['title_ar'] ?: '')
                    : ($c['title_ar'] ?: $c['title_en'] ?: '');
                $orgName = $c['org_name'] ?? '';
                $orgId = $c['org_id'] ?? $orgId;
            }
        } elseif ($orgId) {
            $stmt = $db->prepare("SELECT name FROM organizations WHERE id = ? LIMIT 1");
            $stmt->execute([(int)$orgId]);
            $orgName = (string)$stmt->fetchColumn();
        }
    }
} catch (Throwable $e) {}

/* Build sidebar groups 
if ($isSuperAdmin && function_exists('ec_role_layout_all_groups')) {
    $groups = ec_role_layout_all_groups();
} elseif (function_exists('ec_role_layout_filtered_groups')) {
    $groups = ec_role_layout_filtered_groups($roleCode);
} else {
    $groups = [];
}
*/


$groups = function_exists('ec_role_layout_filtered_groups')
    ? ec_role_layout_filtered_groups()
    : [];


/* Fallback: if helper returns only author/empty for superadmin, force admin groups */
if ($isSuperAdmin && empty($groups)) {
    $groups = [
        ['group'=>'core','label'=>'Core','items'=>[
            ['url'=>'/easychair/admin/dashboard','icon'=>'fa-gauge-high','label'=>'Dashboard'],
            ['url'=>'/easychair/admin/conferences','icon'=>'fa-folder-open','label'=>'Conferences'],
            ['url'=>'/easychair/admin/organizations','icon'=>'fa-building','label'=>'Organizations'],
        ]],
        ['group'=>'submissions','label'=>'Submissions','items'=>[
            ['url'=>'/easychair/admin/submissions','icon'=>'fa-inbox','label'=>'Submissions'],
            ['url'=>'/easychair/admin/submission-search','icon'=>'fa-magnifying-glass','label'=>'Submission Search'],
            ['url'=>'/easychair/admin/decisions','icon'=>'fa-gavel','label'=>'Decisions'],
        ]],
        ['group'=>'reviewing','label'=>'Reviewing','items'=>[
            ['url'=>'/easychair/admin/reviewer-assignments','icon'=>'fa-user-plus','label'=>'Reviewer Assignment'],
            ['url'=>'/easychair/admin/reviewers','icon'=>'fa-user-check','label'=>'Reviewers'],
            ['url'=>'/easychair/admin/review-form','icon'=>'fa-clipboard-list','label'=>'Review Form'],
            ['url'=>'/easychair/admin/review-monitor','icon'=>'fa-chart-line','label'=>'Review Monitor'],
        ]],
        ['group'=>'settings','label'=>'Settings','items'=>[
            ['url'=>'/easychair/admin/users','icon'=>'fa-users','label'=>'Users'],
            ['url'=>'/easychair/admin/roles','icon'=>'fa-user-shield','label'=>'Roles'],
            ['url'=>'/easychair/admin/rbac-matrix','icon'=>'fa-sliders','label'=>'RBAC Matrix'],
            ['url'=>'/easychair/admin/dictionary','icon'=>'fa-language','label'=>'Dictionary'],
            ['url'=>'/easychair/logout','icon'=>'fa-right-from-bracket','label'=>'Logout'],
        ]],
    ];
}

$currentPath = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: '';
$pageTitle = ec_role_t('layout.admin_workspace', 'Administration Workspace');
?>
<!DOCTYPE html>
<html lang="<?php echo ec_role_h($lang); ?>" dir="<?php echo ec_role_h($dir); ?>">
<head>
    <meta charset="UTF-8">
    <title><?php echo ec_role_h($pageTitle); ?> - EasyChair</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <?php if ($isRtl): ?>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <?php else: ?>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <?php endif; ?>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet">

    <style>
        :root { --ec-sidebar-w:292px; --ec-bg:#f4f7fb; --ec-navy:#0f172a; --ec-blue:#2563eb; }
        *{box-sizing:border-box}
        html,body{min-height:100%;max-width:100%;overflow-x:hidden}
        body{margin:0;font-family:'Cairo',sans-serif;background:var(--ec-bg);color:#111827;direction:<?php echo $isRtl?'rtl':'ltr'; ?>;text-align:<?php echo $isRtl?'right':'left'; ?>}
        .role-sidebar{position:fixed;top:0;bottom:0;<?php echo $isRtl?'right':'left'; ?>:0;width:var(--ec-sidebar-w);z-index:1040;overflow-y:auto;overflow-x:hidden;padding:18px 12px;color:#fff;background:radial-gradient(circle at top,rgba(59,130,246,.35),transparent 34%),linear-gradient(180deg,#0f172a,#1e3a8a);box-shadow:0 20px 45px rgba(15,23,42,.24);scrollbar-width:thin}
        .role-sidebar::-webkit-scrollbar{width:7px}.role-sidebar::-webkit-scrollbar-thumb{background:rgba(255,255,255,.30);border-radius:999px}
        .role-brand{display:flex;align-items:center;gap:10px;padding:8px 8px 14px;margin-bottom:8px;font-weight:900;font-size:19px}.role-brand i{font-size:23px}
        .role-lang-switch{display:flex;gap:8px;margin:0 6px 14px}.role-lang-switch a{flex:1;text-align:center;text-decoration:none;border-radius:999px;padding:7px 10px;font-weight:900;background:#fff;color:#1d4ed8}.role-lang-switch a.active{background:#2563eb;color:#fff;box-shadow:inset 0 0 0 1px rgba(255,255,255,.35)}
        .role-context,.role-user{background:rgba(255,255,255,.08);border:1px solid rgba(255,255,255,.12);border-radius:18px;padding:12px;margin:0 6px 14px}
        .role-context .short,.role-user .name{font-weight:900;overflow-wrap:anywhere}.role-context .title,.role-context .org,.role-user .meta{opacity:.78;font-size:12px;line-height:1.6;margin-top:4px;overflow-wrap:anywhere}
        .role-group{margin:8px 4px 10px;border-radius:16px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.08);overflow:hidden}
        .role-group summary{cursor:pointer;list-style:none;padding:10px 12px;font-weight:900;color:#fff;display:flex;align-items:center;justify-content:space-between;gap:8px}.role-group summary::-webkit-details-marker{display:none}.role-group summary::after{content:"⌄";opacity:.85;font-weight:900}.role-group[open] summary::after{content:"⌃"}
        .role-group-links{padding:4px 6px 8px}.role-link{display:flex;align-items:center;gap:9px;padding:9px 10px;margin-bottom:5px;border-radius:13px;color:rgba(255,255,255,.92);text-decoration:none;font-weight:800;font-size:13px;line-height:1.35;transition:.16s ease}.role-link i{width:20px;text-align:center;opacity:.95}.role-link:hover,.role-link.active{color:#fff;background:rgba(255,255,255,.16);transform:translateY(-1px)}
        .role-main{min-height:100vh;width:calc(100% - var(--ec-sidebar-w));<?php echo $isRtl?'margin-right':'margin-left'; ?>:var(--ec-sidebar-w);<?php echo $isRtl?'margin-left':'margin-right'; ?>:0}
        .role-topbar{min-height:76px;background:#fff;border-bottom:1px solid #e5e7eb;padding:14px 24px;display:flex;justify-content:space-between;align-items:center;gap:14px;box-shadow:0 8px 24px rgba(15,23,42,.04);position:sticky;top:0;z-index:1010}
        .role-topbar-title{font-weight:900;font-size:16px}.role-topbar-subtitle{color:#64748b;font-size:13px}.role-badges{display:flex;flex-wrap:wrap;gap:8px;justify-content:<?php echo $isRtl?'flex-start':'flex-end'; ?>}.role-badge{background:#e0f2fe;color:#075985;border-radius:999px;padding:7px 12px;font-weight:900;font-size:12px;white-space:nowrap}.role-badge.alt{background:#ecfdf5;color:#047857}
        .role-content{padding:24px;max-width:100%}.role-content>*,.container,.container-fluid,.card,[class*="dashboard"],[class*="hero"]{max-width:100%!important}.table-responsive{width:100%;overflow-x:auto;-webkit-overflow-scrolling:touch}table{max-width:100%}th,td{vertical-align:middle}td{overflow-wrap:anywhere}
        .mobile-role-menu-btn{display:none;border:0;border-radius:999px;background:#1d4ed8;color:#fff;font-weight:900;padding:9px 13px;box-shadow:0 12px 30px rgba(15,23,42,.20)}.role-overlay{display:none;position:fixed;inset:0;z-index:1030;background:rgba(15,23,42,.48)}body.role-sidebar-open .role-overlay{display:block}
        .role-link.active{background:rgba(255,255,255,.22)!important;box-shadow:inset 4px 0 0 rgba(255,255,255,.85)}body.rtl .role-link.active{box-shadow:inset -4px 0 0 rgba(255,255,255,.85)}.role-group:has(.role-link.active) summary{background:rgba(255,255,255,.10)}
        @media(max-width:1200px){:root{--ec-sidebar-w:270px}.role-content{padding:18px}}
        @media(max-width:991px){.mobile-role-menu-btn{display:inline-flex;align-items:center;gap:8px}.role-sidebar{width:292px;max-width:88vw;transition:transform .22s ease;<?php echo $isRtl?'transform:translateX(105%);':'transform:translateX(-105%);'; ?>}body.role-sidebar-open .role-sidebar{transform:translateX(0)}.role-main{width:100%;margin-left:0;margin-right:0}.role-topbar{padding:12px 14px}.role-content{padding:14px}}
        @media(max-width:576px){.role-topbar{align-items:flex-start;flex-direction:column}.role-badges{justify-content:flex-start}.role-badge{white-space:normal}h1,.h1{font-size:1.55rem!important}h2,.h2{font-size:1.35rem!important}h3,.h3{font-size:1.18rem!important}table{font-size:13px}}
    </style>
</head>

<body class="<?php echo $isRtl ? 'rtl' : 'ltr'; ?>">
    <!-- layout=conference_role systemRole=<?php echo ec_role_h($systemRole); ?> roleCode=<?php echo ec_role_h($roleCode); ?> -->

    <aside class="role-sidebar">
        <div class="role-brand">
            <i class="fa-solid fa-building-columns"></i>
            <span><?php echo ec_role_h(ec_role_t('layout.admin_workspace', 'Administration Workspace')); ?></span>
        </div>

        <div class="role-lang-switch">
            <a class="<?php echo $lang === 'ar' ? 'active' : ''; ?>" href="/easychair/lang?set=ar">عربي</a>
            <a class="<?php echo $lang === 'en' ? 'active' : ''; ?>" href="/easychair/lang?set=en">EN</a>
        </div>

        <div class="role-context">
            <div class="short"><?php echo ec_role_h($conferenceShort); ?></div>
            <?php if ($conferenceTitle): ?><div class="title"><?php echo ec_role_h($conferenceTitle); ?></div><?php endif; ?>
            <?php if ($orgName): ?><div class="org"><?php echo ec_role_h($orgName); ?></div><?php endif; ?>
        </div>

        <div class="role-user">
            <div class="name"><?php echo ec_role_h($userName); ?></div>
            <div class="meta"><?php echo ec_role_h($roleLabel); ?><?php if ($userEmail): ?> | <?php echo ec_role_h($userEmail); ?><?php endif; ?></div>
        </div>

        <nav>
            <?php foreach ($groups as $idx => $group): ?>
                <?php
                $groupItems = $group['items'] ?? [];
                $groupHasActive = false;
                foreach ($groupItems as $__gi) {
                    $__url = (string)($__gi['url'] ?? '#');
                    if (rtrim($currentPath, '/') === rtrim($__url, '/') || ($__url !== '#' && $__url !== '' && str_starts_with(rtrim($currentPath, '/') . '/', rtrim($__url, '/') . '/'))) {
                        $groupHasActive = true;
                        break;
                    }
                }
                $groupOpen = $groupHasActive || ($idx === 0 && empty($currentPath));
                $groupKey = preg_replace('/[^a-zA-Z0-9_-]+/', '_', (string)($group['group'] ?? ('group_' . $idx)));
                ?>
                <details class="role-group" data-group-key="<?php echo ec_role_h($groupKey); ?>" <?php echo $groupOpen ? 'open' : ''; ?>>
                    <summary><?php echo ec_role_h($group['label'] ?? ''); ?></summary>
                    <div class="role-group-links">
                        <?php foreach ($groupItems as $item): ?>
                            <?php
                            $url = (string)($item['url'] ?? '#');

                            if (!$isSuperAdmin) {
                                if (function_exists('ec_role_layout_db_can_view') && !ec_role_layout_db_can_view($url, (string)$roleCode)) {
                                    continue;
                                }
                                if (function_exists('ec_can_menu') && !ec_can_menu($url)) {
                                    continue;
                                }
                            }

                            $active = rtrim($currentPath, '/') === rtrim($url, '/')
                                || ($url !== '#' && $url !== '' && str_starts_with(rtrim($currentPath, '/') . '/', rtrim($url, '/') . '/'));
                            ?>
                            <a class="role-link <?php echo $active ? 'active' : ''; ?>" href="<?php echo ec_role_h($url); ?>">
                                <i class="fa-solid <?php echo ec_role_h($item['icon'] ?? 'fa-circle'); ?>"></i>
                                <span><?php echo ec_role_h($item['label'] ?? ''); ?></span>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </details>
            <?php endforeach; ?>
        </nav>
    </aside>

    <div class="role-overlay" onclick="document.body.classList.remove('role-sidebar-open')"></div>

    <main class="role-main">
        <div class="role-topbar">
            <button type="button" class="mobile-role-menu-btn" onclick="document.body.classList.toggle('role-sidebar-open')">
                <i class="fa-solid fa-bars"></i>
                <span><?php echo ec_role_h(ec_role_t('action.menu', 'Menu')); ?></span>
            </button>

            <div>
                <div class="role-topbar-title"><?php echo ec_role_h($userName); ?></div>
                <div class="role-topbar-subtitle">
                    <?php echo ec_role_h(ec_role_t('layout.welcome_back', 'Welcome back')); ?>
                    · <?php echo ec_role_h($roleLabel); ?>
                </div>
            </div>

            <div class="role-badges">
                <?php if ($conferenceShort): ?><span class="role-badge"><?php echo ec_role_h($conferenceShort); ?></span><?php endif; ?>
                <?php if ($orgId): ?><span class="role-badge alt">Org <?php echo (int)$orgId; ?></span><?php endif; ?>
            </div>
        </div>

        <div class="role-content">
            <?php echo $content; ?>
        </div>
    </main>

    <script>
    document.addEventListener('DOMContentLoaded', function () {
        document.querySelectorAll('table').forEach(function (table) {
            if (!table.parentElement.classList.contains('table-responsive')) {
                const wrapper = document.createElement('div');
                wrapper.className = 'table-responsive';
                table.parentNode.insertBefore(wrapper, table);
                wrapper.appendChild(table);
            }
        });

        document.querySelectorAll('.role-sidebar a').forEach(function (a) {
            a.addEventListener('click', function () {
                document.body.classList.remove('role-sidebar-open');
            });
        });

        const role = document.body.classList.contains('rtl') ? 'rtl' : 'ltr';
        const path = window.location.pathname;
        const storageKey = 'easychair.sidebar.openGroup.' + path + '.' + role;
        const groups = Array.from(document.querySelectorAll('.role-group[data-group-key]'));
        const activeLink = document.querySelector('.role-link.active');

        if (activeLink) {
            const activeGroup = activeLink.closest('.role-group');
            groups.forEach(function (g) { g.open = (g === activeGroup); });
            if (activeGroup) {
                try { localStorage.setItem(storageKey, activeGroup.dataset.groupKey || ''); } catch (e) {}
            }
            setTimeout(function () { activeLink.scrollIntoView({block:'center', behavior:'smooth'}); }, 120);
        }

        groups.forEach(function (group) {
            group.addEventListener('toggle', function () {
                if (!group.open) return;
                groups.forEach(function (other) { if (other !== group) other.open = false; });
                try { localStorage.setItem(storageKey, group.dataset.groupKey || ''); } catch (e) {}
            });
        });
    });
    </script>

<?php
if (defined('BASE_PATH') && file_exists(BASE_PATH . '/app/views/partials/toast.php')) {
    require BASE_PATH . '/app/views/partials/toast.php';
}
?>
</body>
</html>
