<?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;">
        <h3 style="margin-bottom:15px;color:#1A1A2E;">الصلاحيات</h3>
        <?php if (empty($ap)): ?>
            <p style="color:#6B7280;">لا توجد صلاحيات مسجلة بعد. ستظهر تلقائياً عند إضافة الوحدات.</p>
        <?php else: ?>
            <?php foreach ($ap as $group => $perms): ?>
                <div style="margin-bottom:20px;border:1px solid #E5E7EB;border-radius:8px;padding:15px;">
                    <h4 style="margin-bottom:10px;color:#0D7377;font-size:16px;"><?= e($group) ?></h4>
                    <div style="display:grid;grid-template-columns:repeat(auto-fill, minmax(250px, 1fr));gap:8px;">
                        <?php foreach ($perms as $key => $labels): ?>
                            <label style="display:flex;align-items:center;gap:8px;font-size:14px;cursor:pointer;">
                                <input type="checkbox" name="permissions[]" value="<?= e($key) ?>"
                                    <?= in_array($key, $rp) ? 'checked' : '' ?>>
                                <span><?= e($labels['ar'] ?? $key) ?></span>
                                <small style="color:#9CA3AF;">(<?= e($key) ?>)</small>
                            </label>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>