<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>إدارة صلاحيات: <?= e($employee->full_name_ar) ?><?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>

<?php
$rp = $rolePermMap ?? [];
$dm = $directMap ?? [];
$ri = $currentRoleIds ?? [];
$re = $roleExpirations ?? [];
?>

<div style="margin-bottom:20px;">
    <a href="/users/<?= (int) $employee->id ?>" class="btn btn-outline" style="font-size:13px;">&larr; عودة للملف الشخصي</a>
</div>

<form method="POST" action="/users/<?= (int) $employee->id ?>/permissions">
    <?= csrf_field() ?>

    <!-- Employee Header -->
    <div class="card" style="padding:20px;margin-bottom:20px;">
        <div style="display:flex;align-items:center;gap:20px;flex-wrap:wrap;">
            <div>
                <h2 style="margin:0;"><?= e($employee->full_name_ar) ?></h2>
                <p style="margin:4px 0 0;color:#6B7280;">@<?= e($employee->username) ?> — <?= e($employee->getBranchName()) ?></p>
            </div>
            <?php
            $totalEffective = count($employee->getAllPermissions());
            $hasStar = in_array('*', $employee->getAllPermissions(), true);
            ?>
            <div style="margin-right:auto;text-align:center;padding:10px 20px;background:#F0FDF4;border-radius:8px;">
                <div style="font-size:24px;font-weight:700;color:#059669;"><?= $hasStar ? '∞' : $totalEffective ?></div>
                <div style="font-size:12px;color:#6B7280;">صلاحية فعّالة</div>
            </div>
        </div>
    </div>

    <!-- Role Assignments with Expiration -->
    <div class="card" style="padding:20px;margin-bottom:20px;">
        <h3 style="margin:0 0 15px;">الأدوار</h3>
        <div style="display:grid;grid-template-columns:repeat(auto-fill, minmax(320px, 1fr));gap:12px;">
            <?php foreach ($allRoles as $role): ?>
                <?php $checked = in_array($role['id'], $ri); ?>
                <div style="display:flex;align-items:center;gap:10px;padding:8px 12px;border:1px solid <?= $checked ? '#059669' : '#E5E7EB' ?>;border-radius:8px;background:<?= $checked ? '#F0FDF4' : '#fff' ?>;">
                    <input type="checkbox" name="roles[]" value="<?= (int) $role['id'] ?>"
                        <?= $checked ? 'checked' : '' ?>
                        id="role_<?= (int) $role['id'] ?>"
                        onchange="this.closest('div').style.background=this.checked?'#F0FDF4':'#fff';this.closest('div').style.borderColor=this.checked?'#059669':'#E5E7EB';">
                    <label for="role_<?= (int) $role['id'] ?>" style="cursor:pointer;flex:1;font-size:14px;">
                        <?= e($role['name_ar']) ?>
                        <small style="color:#9CA3AF;display:block;"><?= e($role['role_code']) ?></small>
                    </label>
                    <input type="date" name="role_expires[<?= (int) $role['id'] ?>]"
                        value="<?= e(isset($re[(int) $role['id']]) && $re[(int) $role['id']] ? substr($re[(int) $role['id']], 0, 10) : '') ?>"
                        style="width:140px;font-size:12px;padding:4px 6px;border:1px solid #D1D5DB;border-radius:4px;"
                        title="تاريخ انتهاء الدور (اختياري)">
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Permission Matrix -->
    <div class="card" style="padding:20px;margin-bottom:20px;">
        <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-bottom:15px;">
            <h3 style="margin:0;">الصلاحيات التفصيلية</h3>
            <input type="text" id="perm-search" placeholder="بحث في الصلاحيات..." class="form-input" style="width:300px;font-size:13px;">
        </div>

        <div style="margin-bottom:15px;padding:10px;background:#F9FAFB;border-radius:6px;font-size:13px;color:#6B7280;">
            <span style="display:inline-block;width:14px;height:14px;background:#E5E7EB;border-radius:3px;vertical-align:middle;margin-left:4px;"></span> وراثة من الدور
            <span style="display:inline-block;width:14px;height:14px;background:#059669;border-radius:3px;vertical-align:middle;margin-right:12px;margin-left:4px;"></span> منح مباشر
            <span style="display:inline-block;width:14px;height:14px;background:#DC2626;border-radius:3px;vertical-align:middle;margin-right:12px;margin-left:4px;"></span> حظر مباشر
        </div>

        <?php if (empty($allPermissions)): ?>
            <p style="color:#6B7280;">لا توجد صلاحيات مسجلة.</p>
        <?php else: ?>
            <?php foreach ($allPermissions as $group => $perms): ?>
                <?php
                $groupTotal = count($perms);
                $groupActive = 0;
                foreach ($perms as $key => $_) {
                    if (isset($rp[$key]) || (isset($dm[$key]) && $dm[$key] === 'grant')) {
                        $groupActive++;
                    }
                }
                ?>
                <div class="perm-group" style="margin-bottom:15px;border:1px solid #E5E7EB;border-radius:8px;overflow:hidden;">
                    <div style="display:flex;align-items:center;justify-content:space-between;padding:12px 15px;background:#F9FAFB;cursor:pointer;" onclick="this.nextElementSibling.style.display=this.nextElementSibling.style.display==='none'?'block':'none'">
                        <div>
                            <strong style="color:#0D7377;font-size:15px;"><?= e($group) ?></strong>
                            <span style="font-size:12px;color:#6B7280;margin-right:8px;">(<?= $groupActive ?>/<?= $groupTotal ?>)</span>
                        </div>
                        <div style="display:flex;gap:8px;">
                            <button type="button" class="btn-grant-all" onclick="event.stopPropagation();setGroupState(this.closest('.perm-group'),'grant')" style="font-size:11px;padding:2px 8px;border:1px solid #059669;color:#059669;background:#fff;border-radius:4px;cursor:pointer;">منح الكل</button>
                            <button type="button" onclick="event.stopPropagation();setGroupState(this.closest('.perm-group'),'inherit')" style="font-size:11px;padding:2px 8px;border:1px solid #9CA3AF;color:#6B7280;background:#fff;border-radius:4px;cursor:pointer;">إعادة تعيين</button>
                        </div>
                    </div>
                    <div style="padding:10px 15px;">
                        <?php foreach ($perms as $key => $labels): ?>
                            <?php
                            $fromRoles = $rp[$key] ?? [];
                            $directState = $dm[$key] ?? null;
                            $state = 'inherit';
                            if ($directState === 'grant') $state = 'grant';
                            elseif ($directState === 'deny') $state = 'deny';
                            ?>
                            <div class="perm-row" data-key="<?= e($key) ?>" data-label="<?= e($labels['ar'] ?? '') ?>" style="display:flex;align-items:center;gap:10px;padding:6px 0;border-bottom:1px solid #F3F4F6;">
                                <input type="hidden" name="perm_state[<?= e($key) ?>]" value="<?= e($state) ?>" class="perm-state-input">

                                <button type="button" class="perm-toggle" onclick="cyclePerm(this)"
                                    style="width:28px;height:28px;border-radius:6px;border:2px solid <?= $state === 'grant' ? '#059669' : ($state === 'deny' ? '#DC2626' : '#D1D5DB') ?>;background:<?= $state === 'grant' ? '#059669' : ($state === 'deny' ? '#DC2626' : '#E5E7EB') ?>;color:#fff;font-size:14px;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;"
                                    data-state="<?= e($state) ?>">
                                    <?= $state === 'grant' ? '&#10003;' : ($state === 'deny' ? '&#10007;' : '—') ?>
                                </button>

                                <div style="flex:1;min-width:0;">
                                    <span style="font-size:14px;"><?= e($labels['ar'] ?? $key) ?></span>
                                    <small style="color:#9CA3AF;margin-right:6px;">(<?= e($key) ?>)</small>
                                </div>

                                <?php if (!empty($fromRoles)): ?>
                                    <div style="display:flex;gap:4px;flex-wrap:wrap;flex-shrink:0;">
                                        <?php foreach (array_unique($fromRoles) as $roleName): ?>
                                            <span style="font-size:11px;padding:2px 6px;background:#EEF2FF;color:#4338CA;border-radius:4px;"><?= e($roleName) ?></span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <div style="display:flex;gap:10px;">
        <button type="submit" class="btn btn-primary">حفظ الصلاحيات</button>
        <a href="/users/<?= (int) $employee->id ?>" class="btn btn-outline">إلغاء</a>
    </div>
</form>

<script>
function cyclePerm(btn) {
    var states = ['inherit', 'grant', 'deny'];
    var colors = {inherit: {bg:'#E5E7EB', border:'#D1D5DB', icon:'—'}, grant: {bg:'#059669', border:'#059669', icon:'✓'}, deny: {bg:'#DC2626', border:'#DC2626', icon:'✗'}};
    var current = btn.getAttribute('data-state');
    var next = states[(states.indexOf(current) + 1) % states.length];
    btn.setAttribute('data-state', next);
    btn.style.background = colors[next].bg;
    btn.style.borderColor = colors[next].border;
    btn.innerHTML = colors[next].icon;
    btn.closest('.perm-row').querySelector('.perm-state-input').value = next;
}

function setGroupState(groupEl, state) {
    var btns = groupEl.querySelectorAll('.perm-toggle');
    var colors = {inherit: {bg:'#E5E7EB', border:'#D1D5DB', icon:'—'}, grant: {bg:'#059669', border:'#059669', icon:'✓'}, deny: {bg:'#DC2626', border:'#DC2626', icon:'✗'}};
    btns.forEach(function(btn) {
        btn.setAttribute('data-state', state);
        btn.style.background = colors[state].bg;
        btn.style.borderColor = colors[state].border;
        btn.innerHTML = colors[state].icon;
        btn.closest('.perm-row').querySelector('.perm-state-input').value = state;
    });
}

document.getElementById('perm-search').addEventListener('input', function() {
    var q = this.value.toLowerCase();
    document.querySelectorAll('.perm-row').forEach(function(row) {
        var key = (row.getAttribute('data-key') || '').toLowerCase();
        var label = (row.getAttribute('data-label') || '').toLowerCase();
        row.style.display = (!q || key.indexOf(q) >= 0 || label.indexOf(q) >= 0) ? '' : 'none';
    });
    document.querySelectorAll('.perm-group').forEach(function(group) {
        var visible = group.querySelectorAll('.perm-row[style=""], .perm-row:not([style])');
        var allRows = group.querySelectorAll('.perm-row');
        var hasVisible = false;
        allRows.forEach(function(r) { if (r.style.display !== 'none') hasVisible = true; });
        group.style.display = hasVisible ? '' : 'none';
    });
});
</script>
<?php $__template->endSection(); ?>
