<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>مصفوفة الصلاحيات<?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/access-matrix/export" class="btn btn-outline">📥 تصدير CSV</a>
<a href="/access-matrix/compare" class="btn btn-outline">🔍 مقارنة أدوار</a>
<a href="/access-matrix/health" class="btn btn-outline">🏥 صحة الصلاحيات</a>
<?php if (can('access_matrix.manage')): ?>
<button onclick="document.getElementById('clone-modal').style.display='flex'" class="btn btn-primary">+ نسخ دور</button>
<?php endif; ?>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<div style="margin-bottom:15px;display:flex;gap:10px;align-items:center;">
    <input type="text" id="matrix-search" placeholder="بحث في الصلاحيات..." class="form-input" style="max-width:300px;" oninput="filterMatrix(this.value)">
    <span style="color:#6B7280;font-size:13px;">
        <?= count($roles) ?> دور |
        <?php $totalPerms = 0; foreach ($matrix as $g) $totalPerms += count($g['permissions']); ?>
        <?= $totalPerms ?> صلاحية
    </span>
    <div style="margin-right:auto;display:flex;gap:8px;font-size:12px;">
        <span style="display:inline-flex;align-items:center;gap:4px;"><span style="width:14px;height:14px;background:#059669;border-radius:3px;display:inline-block;"></span> ممنوحة</span>
        <span style="display:inline-flex;align-items:center;gap:4px;"><span style="width:14px;height:14px;background:#E5E7EB;border-radius:3px;display:inline-block;"></span> غير ممنوحة</span>
    </div>
</div>

<div class="card" style="overflow:auto;max-height:75vh;">
    <table id="matrix-table" style="width:100%;border-collapse:collapse;font-size:12px;">
        <thead style="position:sticky;top:0;z-index:10;">
            <tr style="background:#1A1A2E;">
                <th style="position:sticky;right:0;z-index:11;background:#1A1A2E;color:#fff;padding:10px 12px;text-align:right;min-width:250px;border-left:2px solid #374151;">الصلاحية</th>
                <?php foreach ($roles as $role): ?>
                <th style="color:#fff;padding:8px 6px;text-align:center;min-width:90px;max-width:120px;white-space:normal;font-size:11px;border-left:1px solid #374151;">
                    <div style="font-weight:700;"><?= e($role['name_ar']) ?></div>
                    <div style="opacity:0.6;font-size:10px;direction:ltr;"><?= e($role['role_code']) ?></div>
                    <?php if ($role['has_all_branches']): ?>
                    <span style="background:#F59E0B;color:#000;font-size:9px;padding:1px 4px;border-radius:8px;">كل الفروع</span>
                    <?php endif; ?>
                </th>
                <?php endforeach; ?>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($matrix as $group => $groupData): ?>
            <tr class="matrix-group-header" data-group="<?= e($group) ?>" onclick="toggleGroup('<?= e($group) ?>')" style="cursor:pointer;background:#F3F4F6;">
                <td colspan="<?= count($roles) + 1 ?>" style="padding:10px 12px;font-weight:700;color:#0D7377;font-size:13px;border-top:2px solid #D1D5DB;">
                    <span class="group-arrow" id="arrow-<?= e($group) ?>">▼</span>
                    <?= e($group) ?>
                    <span style="color:#9CA3AF;font-weight:400;font-size:11px;">(<?= count($groupData['permissions']) ?>)</span>
                </td>
            </tr>
            <?php foreach ($groupData['permissions'] as $perm): ?>
            <tr class="matrix-row" data-group="<?= e($group) ?>" data-key="<?= e($perm['key']) ?>">
                <td style="position:sticky;right:0;background:#fff;padding:6px 12px;border-left:2px solid #E5E7EB;border-bottom:1px solid #F3F4F6;z-index:1;">
                    <div style="font-weight:500;"><?= e($perm['label']) ?></div>
                    <div style="font-size:10px;color:#9CA3AF;direction:ltr;"><?= e($perm['key']) ?></div>
                </td>
                <?php foreach ($roles as $role): ?>
                <?php $hasIt = $perm['roles'][(int) $role['id']] ?? false; ?>
                <td style="text-align:center;padding:4px;border-bottom:1px solid #F9FAFB;border-left:1px solid #F3F4F6;">
                    <?php if (can('access_matrix.manage') && $role['role_code'] !== 'super_admin'): ?>
                    <button
                        class="matrix-cell"
                        data-role="<?= (int) $role['id'] ?>"
                        data-perm="<?= e($perm['key']) ?>"
                        onclick="togglePermission(this)"
                        style="width:28px;height:28px;border:none;border-radius:4px;cursor:pointer;background:<?= $hasIt ? '#059669' : '#E5E7EB' ?>;color:<?= $hasIt ? '#fff' : '#9CA3AF' ?>;font-size:14px;font-weight:700;"
                    ><?= $hasIt ? '✓' : '' ?></button>
                    <?php else: ?>
                    <span style="display:inline-block;width:28px;height:28px;border-radius:4px;line-height:28px;background:<?= $hasIt ? '#059669' : '#E5E7EB' ?>;color:<?= $hasIt ? '#fff' : '#9CA3AF' ?>;font-size:14px;font-weight:700;"><?= $hasIt ? '✓' : '' ?></span>
                    <?php endif; ?>
                </td>
                <?php endforeach; ?>
            </tr>
            <?php endforeach; ?>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php if (can('access_matrix.manage')): ?>
<!-- Clone Modal -->
<div id="clone-modal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:1000;align-items:center;justify-content:center;">
    <div style="background:#fff;border-radius:12px;padding:30px;max-width:450px;width:90%;">
        <h3 style="margin:0 0 20px;color:#0D7377;">نسخ دور موجود</h3>
        <form method="POST" action="/access-matrix/clone">
            <?= csrf_field() ?>
            <div class="form-group" style="margin-bottom:15px;">
                <label class="form-label">الدور المصدر</label>
                <select name="source_role_id" class="form-select" required>
                    <option value="">اختر...</option>
                    <?php foreach ($roles as $r): ?>
                    <option value="<?= (int) $r['id'] ?>"><?= e($r['name_ar']) ?> (<?= e($r['role_code']) ?>)</option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group" style="margin-bottom:15px;">
                <label class="form-label">كود الدور الجديد</label>
                <input type="text" name="new_code" class="form-input" placeholder="مثال: custom_cashier" required style="direction:ltr;">
            </div>
            <div class="form-group" style="margin-bottom:20px;">
                <label class="form-label">اسم الدور بالعربي</label>
                <input type="text" name="name_ar" class="form-input" placeholder="مثال: أمين صندوق مخصص" required>
            </div>
            <div style="display:flex;gap:10px;justify-content:end;">
                <button type="button" onclick="document.getElementById('clone-modal').style.display='none'" class="btn btn-outline">إلغاء</button>
                <button type="submit" class="btn btn-primary">نسخ</button>
            </div>
        </form>
    </div>
</div>
<?php endif; ?>

<script>
function toggleGroup(group) {
    var rows = document.querySelectorAll('.matrix-row[data-group="' + group + '"]');
    var arrow = document.getElementById('arrow-' + group);
    var hidden = rows[0] && rows[0].style.display === 'none';
    rows.forEach(function(r) { r.style.display = hidden ? '' : 'none'; });
    arrow.textContent = hidden ? '▼' : '►';
}

function filterMatrix(q) {
    q = q.toLowerCase();
    var rows = document.querySelectorAll('.matrix-row');
    var headers = document.querySelectorAll('.matrix-group-header');
    var groupVisible = {};

    rows.forEach(function(r) {
        var key = r.dataset.key || '';
        var visible = !q || key.toLowerCase().indexOf(q) !== -1 || r.querySelector('td').textContent.toLowerCase().indexOf(q) !== -1;
        r.style.display = visible ? '' : 'none';
        if (visible) groupVisible[r.dataset.group] = true;
    });

    headers.forEach(function(h) {
        h.style.display = groupVisible[h.dataset.group] ? '' : 'none';
    });
}

function togglePermission(btn) {
    var roleId = btn.dataset.role;
    var perm = btn.dataset.perm;

    fetch('/access-matrix/toggle', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
        body: '_token=' + encodeURIComponent(document.querySelector('meta[name=csrf-token]')?.content || '<?= csrf_token() ?>') + '&role_id=' + roleId + '&permission_key=' + encodeURIComponent(perm)
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.granted) {
            btn.style.background = '#059669';
            btn.style.color = '#fff';
            btn.textContent = '✓';
        } else {
            btn.style.background = '#E5E7EB';
            btn.style.color = '#9CA3AF';
            btn.textContent = '';
        }
    })
    .catch(function(e) { alert('خطأ في الاتصال'); });
}
</script>

<?php $__template->endSection(); ?>
