<?php
function cbp_h($v) {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}
function cbp_t($key, $fallback) {
    return function_exists('ec_t') ? ec_t($key, $fallback) : $fallback;
}
function cbp_checked($permissions, $roleId, $menuId, $field) {
    return !empty($permissions[$roleId][$menuId][$field]) ? 'checked' : '';
}
?>

<div class="container-fluid py-3">
    <div class="card border-0 shadow-sm mb-4" style="border-radius:24px;background:linear-gradient(135deg,#0f172a,#2563eb);color:#fff;">
        <div class="card-body p-4 d-flex justify-content-between align-items-center flex-wrap gap-3">
            <div>
                <h3 class="fw-bold mb-1">
                    <i class="fa fa-shield-halved"></i>
                    <?= cbp_h(cbp_t('menu.conference_business_permissions','Conference Business Permissions')) ?>
                </h3>
                <div class="opacity-75">
                    <?= cbp_h($conference['short_name'] ?? '') ?> —
                    Conference #<?= (int)($debugCounts['conference_id'] ?? 0) ?> —
                    Org #<?= (int)($debugCounts['org_id'] ?? 0) ?>
                </div>
            </div>
            <div class="rounded-4 px-4 py-3" style="background:rgba(255,255,255,.14);">
                <div class="small opacity-75">Loaded</div>
                <div class="fs-5 fw-bold">
                    <?= (int)($debugCounts['menu_items'] ?? 0) ?> pages /
                    <?= (int)($debugCounts['roles'] ?? 0) ?> roles
                </div>
            </div>
        </div>
    </div>

    <?php if (!empty($_SESSION['flash_success'])): ?>
        <div class="alert alert-success rounded-4 shadow-sm">
            <?= cbp_h($_SESSION['flash_success']) ?>
        </div>
        <?php unset($_SESSION['flash_success']); ?>
    <?php endif; ?>

    <div class="alert alert-info rounded-4 shadow-sm">
        <strong>Protected:</strong>
        Super Admin is not listed here. Super Admin always has full access.
        <div class="small mt-1">
            Debug:
            roles=<?= (int)($debugCounts['roles'] ?? 0) ?>,
            pages=<?= (int)($debugCounts['menu_items'] ?? 0) ?>,
            permission groups=<?= (int)($debugCounts['permission_role_groups'] ?? 0) ?>
        </div>
    </div>

    <?php if (empty($roles) || empty($menuItems)): ?>
        <div class="alert alert-danger rounded-4 shadow-sm">
            No roles or business menu items loaded. Please check DB seed.
        </div>
    <?php else: ?>
        <div class="card border-0 shadow-sm mb-3" style="border-radius:20px;">
    <div class="card-body">

        <div class="row g-3">

            <div class="col-md-7">
                <input
                    type="search"
                    id="cbpSearch"
                    class="form-control"
                    placeholder="Search page title, URL, role..."
                >
            </div>

            <div class="col-md-2">
                <select
                    id="cbpPageSize"
                    class="form-select">

                    <option value="25">25 Rows</option>
                    <option value="50">50 Rows</option>
                    <option value="100">100 Rows</option>
                    <option value="999999">All</option>

                </select>
            </div>

            <div class="col-md-3 text-end">
                <span
                    id="cbpCounter"
                    class="badge bg-primary fs-6">
                    0 Results
                </span>
            </div>

        </div>

    </div>
</div>

<form method="post" action="/easychair/admin/conference-business-permissions/save">
            <div class="card border-0 shadow-sm" style="border-radius:24px;">
                <div class="card-body p-4">
                    <div class="table-responsive">
                        <table id="cbpTable" class="table table-bordered align-middle">
                            <thead class="table-dark">
                                <tr>
                                    <th style="min-width:260px;">Business Page</th>
                                    <?php foreach ($roles as $r): ?>
                                        <th class="text-center" style="min-width:220px;">
                                            <?= cbp_h(function_exists('ec_role_t') ? ec_role_t($r['code']) : ($r['name'] ?? $r['code'])) ?>
                                            <div class="small opacity-75"><?= cbp_h($r['code']) ?></div>
                                        </th>
                                    <?php endforeach; ?>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($menuItems as $mi): ?>
                                    <tr>
                                        <td>
                                            <div class="fw-bold">
                                                <i class="fa <?= cbp_h($mi['icon'] ?? 'fa-circle') ?>"></i>
                                                <?= cbp_h(function_exists('ec_t') ? ec_t($mi['i18n_key'] ?? '', $mi['label'] ?? '') : ($mi['label'] ?? '')) ?>
                                            </div>
                                            <code class="small"><?= cbp_h($mi['url'] ?? '') ?></code>
                                        </td>

                                        <?php foreach ($roles as $r): ?>
                                            <?php
                                                $roleId = (int)$r['id'];
                                                $menuId = (int)$mi['id'];
                                            ?>
                                            <td>
                                                <div class="d-grid gap-2">
                                                    <label class="form-check">
                                                        <input class="form-check-input" type="checkbox"
                                                            name="perm[<?= $roleId ?>][<?= $menuId ?>][view]"
                                                            value="1" <?= cbp_checked($permissions, $roleId, $menuId, 'can_view') ?>>
                                                        <span class="form-check-label">View</span>
                                                    </label>
                                                    <label class="form-check">
                                                        <input class="form-check-input" type="checkbox"
                                                            name="perm[<?= $roleId ?>][<?= $menuId ?>][create]"
                                                            value="1" <?= cbp_checked($permissions, $roleId, $menuId, 'can_create') ?>>
                                                        <span class="form-check-label">Create</span>
                                                    </label>
                                                    <label class="form-check">
                                                        <input class="form-check-input" type="checkbox"
                                                            name="perm[<?= $roleId ?>][<?= $menuId ?>][update]"
                                                            value="1" <?= cbp_checked($permissions, $roleId, $menuId, 'can_update') ?>>
                                                        <span class="form-check-label">Update</span>
                                                    </label>
                                                    <label class="form-check">
                                                        <input class="form-check-input" type="checkbox"
                                                            name="perm[<?= $roleId ?>][<?= $menuId ?>][delete]"
                                                            value="1" <?= cbp_checked($permissions, $roleId, $menuId, 'can_delete') ?>>
                                                        <span class="form-check-label">Delete</span>
                                                    </label>
                                                </div>
                                            </td>
                                        <?php endforeach; ?>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    
<div
id="cbpPager"
class="d-flex flex-wrap gap-1 justify-content-center mt-3">
</div>
</div>

                    <div class="mt-4 d-flex justify-content-end">
                        <button class="btn btn-primary rounded-pill px-5">
                            <i class="fa fa-save"></i>
                            Save Permissions
                        </button>
                    </div>
                </div>
            </div>
        </form>
    <?php endif; ?>
</div>
<script>
(function(){

const table =
document.getElementById('cbpTable');

if(!table) return;

const rows =
Array.from(
table.querySelectorAll('tbody tr')
);

const search =
document.getElementById('cbpSearch');

const pageSize =
document.getElementById('cbpPageSize');

const pager =
document.getElementById('cbpPager');

const counter =
document.getElementById('cbpCounter');

function render(page=1){

    const q =
    (search.value || '')
    .toLowerCase()
    .trim();

    const filtered =
    rows.filter(row =>
        row.innerText
        .toLowerCase()
        .includes(q)
    );

    counter.innerHTML =
        filtered.length +
        ' Results';

    const size =
    parseInt(
        pageSize.value || 25
    );

    const pages =
    Math.max(
        1,
        Math.ceil(
            filtered.length / size
        )
    );

    page =
    Math.min(page,pages);

    rows.forEach(
        r => r.style.display='none'
    );

    filtered
    .slice(
        (page-1)*size,
        page*size
    )
    .forEach(
        r => r.style.display=''
    );

    pager.innerHTML='';

    for(let p=1;p<=pages;p++){

        const btn =
        document.createElement('button');

        btn.type='button';

        btn.className =
        'btn btn-sm ' +
        (p===page
            ? 'btn-primary'
            : 'btn-outline-primary');

        btn.innerText=p;

        btn.onclick=
        ()=>render(p);

        pager.appendChild(btn);
    }

}

search.addEventListener(
'keyup',
()=>render(1)
);

pageSize.addEventListener(
'change',
()=>render(1)
);

render(1);

})();
</script>
