<?php

use App\Core\Csrf;

$isAr = current_lang() === 'ar';
$tr = static function (string $en, string $ar) use ($isAr): string {
    return $isAr ? $ar : $en;
};

$businessCategories = (array)config(
    'access_control.business_categories',
    ['business', 'reporting', 'workflow']
);

$rolesByCode = [];
$activeRoles = [];

foreach ((array)$roles as $role) {
    $roleCode = strtoupper(trim((string)($role['role_code'] ?? '')));

    if ($roleCode === '') {
        continue;
    }

    $rolesByCode[$roleCode] = $role;

    if ((int)($role['is_active'] ?? 1) === 1) {
        $activeRoles[$roleCode] = $role;
    }
}

$assignmentMap = [];

foreach ((array)$assignments as $assignment) {
    $username = strtoupper(trim((string)($assignment['username'] ?? '')));

    if ($username === '') {
        continue;
    }

    $branches = array_values(array_filter(array_map(
        'strtolower',
        array_map(
            'trim',
            explode(',', (string)($assignment['branches'] ?? ''))
        )
    )));

    $assignmentMap[$username] = [
        'role_code' => strtoupper(trim((string)($assignment['role_code'] ?? ''))),
        'branches' => array_values(array_unique($branches)),
    ];
}

$userDirectory = [];

foreach ((array)$users as $userRow) {
    $username = trim((string)($userRow['username'] ?? ''));

    if ($username === '') {
        continue;
    }

    $key = strtoupper($username);
    $assignment = (array)($assignmentMap[$key] ?? []);
    $roleCode = (string)($assignment['role_code'] ?? '');
    $role = (array)($rolesByCode[$roleCode] ?? []);

    $userDirectory[] = [
        'username' => $username,
        'role_code' => $roleCode,
        'role_name' => $roleCode === ''
            ? $tr('Existing access', 'الصلاحيات الحالية')
            : (string)($role[
                $isAr ? 'role_name_ar' : 'role_name_en'
            ] ?? $roleCode),
    ];
}

$permissionGroups = [
    'business' => [
        'title' => $tr(
            'Business pages and reports',
            'صفحات وتقارير العمل'
        ),
        'permissions' => [],
    ],
    'administration' => [
        'title' => $tr(
            'Settings and administration',
            'الإعدادات والإدارة'
        ),
        'permissions' => [],
    ],
];

foreach ((array)$permissions as $code => $permission) {
    $category = (string)($permission['category'] ?? 'business');
    $group = in_array($category, $businessCategories, true)
        ? 'business'
        : 'administration';

    $permissionGroups[$group]['permissions'][] = [
        'code' => (string)$code,
        'name' => (string)($permission[
            $isAr ? 'name_ar' : 'name_en'
        ] ?? $code),
        'category' => $category,
    ];
}

$roleJson = [];

foreach ($rolesByCode as $roleCode => $role) {
    $roleJson[$roleCode] = [
        'role_code' => $roleCode,
        'name_en' => (string)($role['role_name_en'] ?? ''),
        'name_ar' => (string)($role['role_name_ar'] ?? ''),
        'description_en' => (string)($role['role_description_en'] ?? ''),
        'description_ar' => (string)($role['role_description_ar'] ?? ''),
        'policy_mode' => (string)($role['policy_mode'] ?? 'EXPLICIT'),
        'all_branches' => (int)($role['all_branches'] ?? 0),
        'is_system_role' => (int)($role['is_system_role'] ?? 0),
        'is_protected' => (int)($role['is_protected'] ?? 0),
        'is_active' => (int)($role['is_active'] ?? 1),
        'user_count' => (int)($role['user_count'] ?? 0),
        'override_count' => (int)($role['override_count'] ?? 0),
        'overrides' => (array)($roleOverrides[$roleCode] ?? []),
    ];
}

$permissionJson = [];

foreach ((array)$permissions as $code => $permission) {
    $permissionJson[$code] = [
        'category' => (string)($permission['category'] ?? 'business'),
        'name' => (string)($permission[
            $isAr ? 'name_ar' : 'name_en'
        ] ?? $code),
    ];
}

$actionLabels = [
    'SECURITY_SCHEMA_INSTALLED' => $tr(
        'Security system installed',
        'تم تثبيت نظام الصلاحيات'
    ),
    'USER_ROLE_ASSIGNED' => $tr(
        'User role assigned',
        'تم تعيين دور للمستخدم'
    ),
    'USER_ROLE_CLEARED' => $tr(
        'User returned to existing access',
        'تمت إعادة المستخدم للصلاحيات الحالية'
    ),
    'ROLE_CREATED' => $tr(
        'New role created',
        'تم إنشاء دور جديد'
    ),
    'ROLE_UPDATED' => $tr(
        'Role updated',
        'تم تحديث الدور'
    ),
    'ROLE_OVERRIDES_REPLACED' => $tr(
        'Role permissions updated',
        'تم تحديث صلاحيات الدور'
    ),
];

$requestedRole = strtoupper(trim((string)(
    $_GET['role'] ?? 'GENERAL_MANAGER'
)));

if (!isset($rolesByCode[$requestedRole])) {
    $requestedRole = isset($rolesByCode['GENERAL_MANAGER'])
        ? 'GENERAL_MANAGER'
        : (string)(array_key_first($rolesByCode) ?? '');
}

$activeRoleCount = (int)($accessCounts['active_roles'] ?? 0);
$configuredUserCount = (int)($accessCounts['configured_users'] ?? 0);
$siteAdminCount = (int)($accessCounts['site_admins'] ?? 0);
?>

<section
    class="acl142-page"
    data-acl142-page
    data-current-user="<?= e((string)$currentUsername) ?>"
    data-requested-role="<?= e($requestedRole) ?>"
>
    <header class="acl142-header">
        <div>
            <span class="acl142-eyebrow">
                <?= e($tr('ACCESS MANAGEMENT', 'إدارة الصلاحيات')) ?>
            </span>
            <h2>
                <?= e($tr(
                    'Users, Roles and Access',
                    'المستخدمون والأدوار والصلاحيات'
                )) ?>
            </h2>
            <p>
                <?= e($tr(
                    'Assign roles, create new roles and control page access from one workspace.',
                    'عيّن الأدوار وأنشئ أدوارًا جديدة وتحكم في الوصول من شاشة واحدة.'
                )) ?>
            </p>
        </div>

        <div class="acl142-summary">
            <article>
                <strong><?= e(number_format($configuredUserCount)) ?></strong>
                <span><?= e($tr('Assigned users', 'مستخدمون معيّنون')) ?></span>
            </article>
            <article>
                <strong><?= e(number_format($activeRoleCount)) ?></strong>
                <span><?= e($tr('Active roles', 'أدوار فعالة')) ?></span>
            </article>
            <article>
                <strong><?= e(number_format($siteAdminCount)) ?></strong>
                <span><?= e($tr('Site admins', 'مديرو الموقع')) ?></span>
            </article>
            <span class="<?= $schemaReady ? 'is-ready' : 'is-pending' ?>">
                <?= e($schemaReady
                    ? $tr('Security active', 'النظام نشط')
                    : $tr('Installation required', 'يلزم التثبيت')
                ) ?>
            </span>
        </div>
    </header>

    <?php if ($successMessage): ?>
        <div class="acl142-message is-success"><?= e($successMessage) ?></div>
    <?php endif; ?>

    <?php if ($errorMessage): ?>
        <div class="acl142-message is-error"><?= e($errorMessage) ?></div>
    <?php endif; ?>

    <?php if ($schemaReady && !$roleManagementReady): ?>
        <div class="acl142-message is-warning">
            <?= e($tr(
                'Run the Role Management schema upgrade before creating or editing roles.',
                'شغّل ترقية مخطط إدارة الأدوار قبل إنشاء الأدوار أو تعديلها.'
            )) ?>
        </div>
    <?php endif; ?>

    <nav class="acl142-tabs">
        <button type="button" class="is-active" data-acl142-tab="users">
            <?= e($tr('Users', 'المستخدمون')) ?>
        </button>
        <button type="button" data-acl142-tab="roles">
            <?= e($tr('Roles', 'الأدوار')) ?>
        </button>
        <button type="button" data-acl142-tab="audit">
            <?= e($tr('Change History', 'سجل التغييرات')) ?>
        </button>
    </nav>

    <?php if ($schemaReady): ?>
        <section class="acl142-section is-active" data-acl142-section="users">
            <div class="acl142-users-layout">
                <aside class="acl142-user-directory">
                    <header>
                        <div>
                            <span><?= e($tr('DASHBOARD USERS', 'مستخدمو لوحة المعلومات')) ?></span>
                            <strong><?= e(number_format(count($userDirectory))) ?></strong>
                        </div>
                        <input
                            type="search"
                            data-acl142-user-search
                            placeholder="<?= e($tr('Search users', 'البحث عن مستخدم')) ?>"
                            autocomplete="off"
                        >
                    </header>

                    <div class="acl142-user-list" data-acl142-user-list>
                        <?php foreach ($userDirectory as $userEntry): ?>
                            <button
                                type="button"
                                data-acl142-user
                                data-username="<?= e((string)$userEntry['username']) ?>"
                                data-search="<?= e(strtolower((string)$userEntry['username'])) ?>"
                            >
                                <span class="acl142-avatar">
                                    <?= e(strtoupper(substr((string)$userEntry['username'], 0, 1))) ?>
                                </span>
                                <span>
                                    <strong><?= e((string)$userEntry['username']) ?></strong>
                                    <small><?= e((string)$userEntry['role_name']) ?></small>
                                </span>
                                <em class="<?= $userEntry['role_code'] === ''
                                    ? 'is-legacy'
                                    : 'is-assigned'
                                ?>"></em>
                            </button>
                        <?php endforeach; ?>
                    </div>

                    <p class="acl142-empty-list" data-acl142-no-users hidden>
                        <?= e($tr(
                            'No users match the search.',
                            'لا يوجد مستخدم مطابق للبحث.'
                        )) ?>
                    </p>
                </aside>

                <form
                    method="post"
                    action="<?= e(url_to('access-control')) ?>"
                    class="acl142-user-editor"
                    data-acl142-user-form
                >
                    <?= Csrf::field() ?>
                    <input type="hidden" name="acl_action" value="save_user_access">
                    <input type="hidden" name="username" value="" data-acl142-username>

                    <div class="acl142-empty-editor" data-acl142-empty-editor>
                        <span>←</span>
                        <h3><?= e($tr('Select a user', 'اختر مستخدمًا')) ?></h3>
                        <p>
                            <?= e($tr(
                                'Choose a user to review or change the assigned role.',
                                'اختر مستخدمًا لمراجعة دوره أو تعديله.'
                            )) ?>
                        </p>
                    </div>

                    <div class="acl142-editor-content" data-acl142-editor-content hidden>
                        <header class="acl142-editor-header">
                            <div>
                                <span><?= e($tr('SELECTED USER', 'المستخدم المحدد')) ?></span>
                                <h3 data-acl142-selected-username>—</h3>
                            </div>
                            <span class="acl142-current-role" data-acl142-current-role>—</span>
                        </header>

                        <div class="acl142-form-grid">
                            <label class="acl142-field">
                                <span><?= e($tr('Role', 'الدور')) ?></span>
                                <select name="role_code" data-acl142-user-role>
                                    <option value="">
                                        <?= e($tr('Existing access', 'الصلاحيات الحالية')) ?>
                                    </option>
                                    <?php foreach ($activeRoles as $roleCode => $role): ?>
                                        <option value="<?= e($roleCode) ?>">
                                            <?= e((string)($role[
                                                $isAr ? 'role_name_ar' : 'role_name_en'
                                            ] ?? $roleCode)) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <small data-acl142-user-role-description></small>
                            </label>

                            <div class="acl142-branch-block" data-acl142-branch-block>
                                <span><?= e($tr('Branch access', 'نطاق الفروع')) ?></span>

                                <div class="acl142-branch-mode">
                                    <label>
                                        <input
                                            type="radio"
                                            name="branch_mode"
                                            value="ALL"
                                            checked
                                            data-acl142-branch-mode
                                        >
                                        <span><?= e($tr('All active branches', 'جميع الفروع النشطة')) ?></span>
                                    </label>
                                    <label>
                                        <input
                                            type="radio"
                                            name="branch_mode"
                                            value="SELECTED"
                                            data-acl142-branch-mode
                                        >
                                        <span><?= e($tr('Selected branches', 'فروع محددة')) ?></span>
                                    </label>
                                </div>

                                <div class="acl142-branch-checks" data-acl142-branch-checks>
                                    <label>
                                        <input
                                            type="checkbox"
                                            name="branches[]"
                                            value="njch"
                                            data-acl142-branch
                                        >
                                        <span>New Jeddah</span>
                                    </label>
                                    <label>
                                        <input
                                            type="checkbox"
                                            name="branches[]"
                                            value="mnh"
                                            data-acl142-branch
                                        >
                                        <span>Madina</span>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <div class="acl142-access-preview">
                            <div>
                                <span><?= e($tr('ACCESS AFTER SAVING', 'الصلاحيات بعد الحفظ')) ?></span>
                                <strong data-acl142-preview-role>—</strong>
                            </div>
                            <small data-acl142-preview-branches>—</small>
                        </div>

                        <button type="submit" class="acl142-primary">
                            <?= e($tr('Save user access', 'حفظ صلاحيات المستخدم')) ?>
                        </button>
                    </div>
                </form>
            </div>
        </section>

        <section class="acl142-section" data-acl142-section="roles">
            <div class="acl142-roles-layout">
                <aside class="acl142-role-directory">
                    <header>
                        <div>
                            <span><?= e($tr('ROLES', 'الأدوار')) ?></span>
                            <strong><?= e(number_format(count($rolesByCode))) ?></strong>
                        </div>
                        <button
                            type="button"
                            data-acl142-new-role
                            <?= !$roleManagementReady ? 'disabled' : '' ?>
                        >
                            + <?= e($tr('New role', 'دور جديد')) ?>
                        </button>
                    </header>

                    <div class="acl142-role-list">
                        <?php foreach ($rolesByCode as $roleCode => $role): ?>
                            <?php
                            $isActive = (int)($role['is_active'] ?? 1) === 1;
                            ?>
                            <button
                                type="button"
                                data-acl142-role
                                data-role-code="<?= e($roleCode) ?>"
                                class="<?= $roleCode === $requestedRole ? 'is-active' : '' ?>"
                            >
                                <span class="acl142-role-icon">
                                    <?= $roleCode === 'SITE_ADMIN'
                                        ? '★'
                                        : ((int)($role['is_system_role'] ?? 0) === 1 ? '◆' : '●')
                                    ?>
                                </span>
                                <span>
                                    <strong>
                                        <?= e((string)($role[
                                            $isAr ? 'role_name_ar' : 'role_name_en'
                                        ] ?? $roleCode)) ?>
                                    </strong>
                                    <small>
                                        <?= e(number_format((int)($role['user_count'] ?? 0))) ?>
                                        <?= e($tr('users', 'مستخدم')) ?>
                                        ·
                                        <?= e($isActive
                                            ? $tr('Active', 'فعال')
                                            : $tr('Inactive', 'موقوف')
                                        ) ?>
                                    </small>
                                </span>
                                <em class="<?= $isActive ? 'is-active' : 'is-inactive' ?>"></em>
                            </button>
                        <?php endforeach; ?>
                    </div>
                </aside>

                <form
                    method="post"
                    action="<?= e(url_to('access-control')) ?>"
                    class="acl142-role-editor"
                    data-acl142-role-form
                >
                    <?= Csrf::field() ?>
                    <input type="hidden" name="acl_action" value="save_role">
                    <input type="hidden" name="is_new_role" value="0" data-acl142-is-new-role>
                    <input type="hidden" name="policy_mode" value="EXPLICIT" data-acl142-policy-value>
                    <input type="hidden" name="all_branches" value="0" data-acl142-all-branches-value>
                    <input type="hidden" name="is_active" value="1" data-acl142-active-value>

                    <header class="acl142-role-editor-header">
                        <div>
                            <span data-acl142-role-editor-label>
                                <?= e($tr('EDIT ROLE', 'تعديل الدور')) ?>
                            </span>
                            <h3 data-acl142-role-editor-title>—</h3>
                            <small data-acl142-role-editor-meta></small>
                        </div>
                        <span class="acl142-role-protection" data-acl142-role-protection></span>
                    </header>

                    <div class="acl142-role-fields">
                        <label class="acl142-field">
                            <span><?= e($tr('Role code', 'رمز الدور')) ?></span>
                            <input
                                type="text"
                                name="role_code"
                                data-acl142-role-code
                                maxlength="50"
                            >
                            <small>
                                <?= e($tr(
                                    'English letters, numbers and underscores. It cannot change after creation.',
                                    'حروف إنجليزية وأرقام وشرطة سفلية، ولا يتغير بعد الإنشاء.'
                                )) ?>
                            </small>
                        </label>

                        <label class="acl142-field">
                            <span><?= e($tr('English name', 'الاسم بالإنجليزية')) ?></span>
                            <input
                                type="text"
                                name="role_name_en"
                                data-acl142-role-name-en
                                maxlength="120"
                                required
                            >
                        </label>

                        <label class="acl142-field">
                            <span><?= e($tr('Arabic name', 'الاسم بالعربية')) ?></span>
                            <input
                                type="text"
                                name="role_name_ar"
                                data-acl142-role-name-ar
                                maxlength="120"
                            >
                        </label>

                        <label class="acl142-field is-wide">
                            <span><?= e($tr('English description', 'الوصف بالإنجليزية')) ?></span>
                            <textarea
                                name="role_description_en"
                                data-acl142-role-description-en
                                rows="2"
                                maxlength="500"
                            ></textarea>
                        </label>

                        <label class="acl142-field is-wide">
                            <span><?= e($tr('Arabic description', 'الوصف بالعربية')) ?></span>
                            <textarea
                                name="role_description_ar"
                                data-acl142-role-description-ar
                                rows="2"
                                maxlength="500"
                            ></textarea>
                        </label>
                    </div>

                    <div class="acl142-role-settings">
                        <label class="acl142-field">
                            <span><?= e($tr('Starting access', 'نقطة بداية الصلاحيات')) ?></span>
                            <select data-acl142-policy-select>
                                <option value="EXPLICIT">
                                    <?= e($tr('Selected pages only', 'الصفحات المحددة فقط')) ?>
                                </option>
                                <option value="ALL_BUSINESS">
                                    <?= e($tr(
                                        'All business pages automatically',
                                        'جميع صفحات العمل تلقائيًا'
                                    )) ?>
                                </option>
                            </select>
                            <small>
                                <?= e($tr(
                                    'All business automatically includes future business pages.',
                                    'الخيار التلقائي يضيف صفحات العمل الجديدة مستقبلًا.'
                                )) ?>
                            </small>
                        </label>

                        <label class="acl142-toggle-row">
                            <span>
                                <strong><?= e($tr(
                                    'All branches by default',
                                    'جميع الفروع افتراضيًا'
                                )) ?></strong>
                                <small><?= e($tr(
                                    'The user assignment may still restrict branches.',
                                    'يمكن تقييد الفروع عند تعيين الدور للمستخدم.'
                                )) ?></small>
                            </span>
                            <input type="checkbox" data-acl142-all-branches-toggle>
                            <i></i>
                        </label>

                        <label class="acl142-toggle-row">
                            <span>
                                <strong><?= e($tr('Role is active', 'الدور فعال')) ?></strong>
                                <small><?= e($tr(
                                    'A role with assigned users cannot be deactivated.',
                                    'لا يمكن إيقاف دور مرتبط بمستخدمين.'
                                )) ?></small>
                            </span>
                            <input type="checkbox" data-acl142-active-toggle>
                            <i></i>
                        </label>
                    </div>

                    <section class="acl142-role-permissions">
                        <header>
                            <div>
                                <span><?= e($tr('ROLE ACCESS', 'صلاحيات الدور')) ?></span>
                                <h4><?= e($tr('Pages and actions', 'الصفحات والعمليات')) ?></h4>
                            </div>
                            <div>
                                <strong data-acl142-allowed-count>0</strong>
                                <small><?= e($tr('allowed', 'مسموح')) ?></small>
                            </div>
                        </header>

                        <?php foreach ($permissionGroups as $group): ?>
                            <div class="acl142-permission-group">
                                <h5><?= e((string)$group['title']) ?></h5>
                                <div class="acl142-permission-grid">
                                    <?php foreach ((array)$group['permissions'] as $permission): ?>
                                        <label
                                            class="acl142-permission-card"
                                            data-acl142-permission
                                            data-permission-code="<?= e((string)$permission['code']) ?>"
                                            data-permission-category="<?= e((string)$permission['category']) ?>"
                                        >
                                            <span>
                                                <strong><?= e((string)$permission['name']) ?></strong>
                                                <small data-acl142-permission-state>
                                                    <?= e($tr('Blocked', 'ممنوع')) ?>
                                                </small>
                                            </span>
                                            <input
                                                type="checkbox"
                                                name="role_allowed[<?= e((string)$permission['code']) ?>]"
                                                value="1"
                                                data-acl142-permission-switch
                                            >
                                            <i></i>
                                        </label>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </section>

                    <div class="acl142-role-actions">
                        <button
                            type="button"
                            class="acl142-secondary"
                            data-acl142-cancel-new-role
                            hidden
                        >
                            <?= e($tr('Cancel', 'إلغاء')) ?>
                        </button>
                        <button
                            type="submit"
                            class="acl142-primary"
                            data-acl142-save-role
                            <?= !$roleManagementReady ? 'disabled' : '' ?>
                        >
                            <?= e($tr('Save role', 'حفظ الدور')) ?>
                        </button>
                    </div>
                </form>
            </div>
        </section>

        <section class="acl142-section" data-acl142-section="audit">
            <header class="acl142-audit-header">
                <div>
                    <span><?= e($tr('CHANGE HISTORY', 'سجل التغييرات')) ?></span>
                    <h3><?= e($tr('Recent access changes', 'أحدث تغييرات الصلاحيات')) ?></h3>
                </div>
            </header>

            <div class="acl142-audit-list">
                <?php foreach ((array)$audit as $auditRow): ?>
                    <?php
                    $actionCode = (string)($auditRow['action_code'] ?? '');
                    ?>
                    <article>
                        <span class="acl142-audit-icon">✓</span>
                        <div>
                            <strong><?= e($actionLabels[$actionCode] ?? $actionCode) ?></strong>
                            <small><?= e((string)($auditRow['target_key'] ?? '')) ?></small>
                        </div>
                        <div>
                            <span><?= e((string)($auditRow['actor_username'] ?? '')) ?></span>
                            <small><?= e((string)($auditRow['created_at'] ?? '')) ?></small>
                        </div>
                    </article>
                <?php endforeach; ?>

                <?php if (!$audit): ?>
                    <div class="acl142-empty-list">
                        <?= e($tr(
                            'No changes have been recorded yet.',
                            'لم تسجل تغييرات حتى الآن.'
                        )) ?>
                    </div>
                <?php endif; ?>
            </div>
        </section>

        <script type="application/json" id="acl142_assignment_map"><?= json_encode(
            $assignmentMap,
            JSON_UNESCAPED_UNICODE
            | JSON_UNESCAPED_SLASHES
            | JSON_HEX_TAG
            | JSON_HEX_APOS
            | JSON_HEX_QUOT
            | JSON_HEX_AMP
        ) ?></script>

        <script type="application/json" id="acl142_role_map"><?= json_encode(
            $roleJson,
            JSON_UNESCAPED_UNICODE
            | JSON_UNESCAPED_SLASHES
            | JSON_HEX_TAG
            | JSON_HEX_APOS
            | JSON_HEX_QUOT
            | JSON_HEX_AMP
        ) ?></script>

        <script type="application/json" id="acl142_permission_map"><?= json_encode(
            $permissionJson,
            JSON_UNESCAPED_UNICODE
            | JSON_UNESCAPED_SLASHES
            | JSON_HEX_TAG
            | JSON_HEX_APOS
            | JSON_HEX_QUOT
            | JSON_HEX_AMP
        ) ?></script>
    <?php endif; ?>
</section>
