<?php
$r = $role ?? null;
$rp = $rolePerms ?? [];
$ap = $allPermissions ?? [];
?>
<div class="card" style="margin-bottom:20px;">
    <div class="card-body" style="padding:20px;">
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
            <?php if (!$r || !$r->is_system): ?>
            <div class="form-group">
                <label class="form-label">كود الدور <span style="color:#DC2626;">*</span></label>
                <input type="text" name="role_code" value="<?= e($r ? $r->role_code : old('role_code')) ?>" class="form-input" required <?= $r ? 'readonly' : '' ?>>
            </div>
            <?php endif; ?>
            <div class="form-group">
                <label class="form-label">الاسم بالعربي <span style="color:#DC2626;">*</span></label>
                <input type="text" name="name_ar" value="<?= e($r ? $r->name_ar : old('name_ar')) ?>" class="form-input" required>
            </div>
            <div class="form-group">
                <label class="form-label">الاسم بالإنجليزي</label>
                <input type="text" name="name_en" value="<?= e($r ? $r->name_en : old('name_en')) ?>" class="form-input">
            </div>
            <div class="form-group" style="grid-column:1/-1;">
                <label class="form-label">الوصف</label>
                <textarea name="description_ar" class="form-textarea" rows="2"><?= e($r ? $r->description_ar : old('description_ar')) ?></textarea>
            </div>
        </div>
    </div>
</div>
<div class="card">
    <div class="card-body" style="padding:20px;">
        <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;margin-bottom:15px;">
            <h3 style="margin:0;color:#1A1A2E;">الصلاحيات</h3>
            <input type="text" id="role-perm-search" placeholder="بحث في الصلاحيات..." class="form-input" style="width:280px;font-size:13px;">
        </div>
        <?php if (empty($ap)): ?>
            <p style="color:#6B7280;">لا توجد صلاحيات مسجلة بعد. ستظهر تلقائياً عند إضافة الوحدات.</p>
        <?php else: ?>
            <?php foreach ($ap as $group => $perms): ?>
                <?php
                $groupTotal = count($perms);
                $groupChecked = 0;
                foreach ($perms as $key => $_) {
                    if (in_array($key, $rp)) $groupChecked++;
                }
                ?>
                <div class="role-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:10px 15px;background:#F9FAFB;">
                        <div>
                            <strong style="color:#0D7377;font-size:15px;"><?= e($group) ?></strong>
                            <span class="group-count" style="font-size:12px;color:#6B7280;margin-right:8px;">(<?= $groupChecked ?>/<?= $groupTotal ?>)</span>
                        </div>
                        <div style="display:flex;gap:8px;">
                            <button type="button" onclick="toggleGroupAll(this.closest('.role-perm-group'), true)" 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="toggleGroupAll(this.closest('.role-perm-group'), false)" 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;display:grid;grid-template-columns:repeat(auto-fill, minmax(280px, 1fr));gap:8px;">
                        <?php foreach ($perms as $key => $labels): ?>
                            <label class="role-perm-item" data-key="<?= e($key) ?>" data-label="<?= e($labels['ar'] ?? '') ?>" style="display:flex;align-items:center;gap:8px;font-size:14px;cursor:pointer;padding:4px 0;">
                                <input type="checkbox" name="permissions[]" value="<?= e($key) ?>"
                                    <?= in_array($key, $rp) ? 'checked' : '' ?>
                                    onchange="updateGroupCount(this.closest('.role-perm-group'))">
                                <span><?= e($labels['ar'] ?? $key) ?></span>
                                <small style="color:#9CA3AF;">(<?= e($key) ?>)</small>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<script>
function toggleGroupAll(groupEl, check) {
    groupEl.querySelectorAll('input[type="checkbox"]').forEach(function(cb) { cb.checked = check; });
    updateGroupCount(groupEl);
}

function updateGroupCount(groupEl) {
    var total = groupEl.querySelectorAll('input[type="checkbox"]').length;
    var checked = groupEl.querySelectorAll('input[type="checkbox"]:checked').length;
    var span = groupEl.querySelector('.group-count');
    if (span) span.textContent = '(' + checked + '/' + total + ')';
}

document.getElementById('role-perm-search').addEventListener('input', function() {
    var q = this.value.toLowerCase();
    document.querySelectorAll('.role-perm-item').forEach(function(item) {
        var key = (item.getAttribute('data-key') || '').toLowerCase();
        var label = (item.getAttribute('data-label') || '').toLowerCase();
        item.style.display = (!q || key.indexOf(q) >= 0 || label.indexOf(q) >= 0) ? '' : 'none';
    });
    document.querySelectorAll('.role-perm-group').forEach(function(group) {
        var hasVisible = false;
        group.querySelectorAll('.role-perm-item').forEach(function(item) {
            if (item.style.display !== 'none') hasVisible = true;
        });
        group.style.display = hasVisible ? '' : 'none';
    });
});
</script>
