<?php
$isEdit = isset($role) && !empty($role);
$pageTitle = $isEdit ? 'Edit Role' : 'Create Role';
$breadcrumb = [
    ['label' => 'Users', 'url' => APP_URL . '/users'],
    ['label' => 'Roles', 'url' => APP_URL . '/users/roles'],
    ['label' => $pageTitle, 'url' => null]
];
ob_start();

$modules = ['auth', 'dashboard', 'projects', 'clients', 'contractors', 'suppliers', 'finance', 'reports', 'users', 'settings', 'billing'];
$actions = ['view', 'create', 'edit', 'delete', 'approve'];
$rolePermissions = $rolePermissions ?? []; 
?>
<div class="max-w-6xl mx-auto">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800"><?= $pageTitle ?></h1>
        <a href="<?= APP_URL ?>/users/roles" class="text-gray-600 hover:text-gray-900">Back to Roles</a>
    </div>

    <form action="<?= APP_URL ?>/users/roles<?= $isEdit ? '/' . $role['id'] . '/edit' : '/create' ?>" method="POST" class="space-y-6">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION[CSRF_TOKEN_NAME] ?? '') ?>">

        <!-- Role Info -->
        <div class="bg-white rounded-lg shadow p-6">
            <h3 class="text-lg font-medium text-gray-900 mb-4 border-b pb-2">Role Information</h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Role Name *</label>
                    <input type="text" name="name" required value="<?= htmlspecialchars($role['name'] ?? '') ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-[#0A3A6B] focus:ring-[#0A3A6B] sm:text-sm border p-2">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700">Description</label>
                    <textarea name="description" rows="2" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-[#0A3A6B] focus:ring-[#0A3A6B] sm:text-sm border p-2"><?= htmlspecialchars($role['description'] ?? '') ?></textarea>
                </div>
            </div>
        </div>

        <!-- Permissions Matrix -->
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="bg-gray-50 px-6 py-4 border-b border-gray-200 flex justify-between items-center">
                <h3 class="text-lg font-medium text-gray-900">Permissions Matrix</h3>
                <button type="button" id="select_all_btn" class="text-sm text-[#0A3A6B] hover:underline font-medium">Select All Permissions</button>
            </div>
            
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 text-sm">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left font-medium text-gray-500 uppercase tracking-wider">Module</th>
                            <?php foreach ($actions as $act): ?>
                            <th scope="col" class="px-6 py-3 text-center font-medium text-gray-500 uppercase tracking-wider">
                                <label class="flex flex-col items-center cursor-pointer">
                                    <span class="mb-1"><?= ucfirst($act) ?></span>
                                    <input type="checkbox" class="col-selector focus:ring-[#0A3A6B] h-4 w-4 text-[#0A3A6B] border-gray-300 rounded" data-col="<?= $act ?>">
                                </label>
                            </th>
                            <?php endforeach; ?>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($modules as $mod): ?>
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <label class="flex items-center cursor-pointer font-medium text-gray-900 capitalize">
                                    <input type="checkbox" class="row-selector mr-2 focus:ring-[#0A3A6B] h-4 w-4 text-[#0A3A6B] border-gray-300 rounded" data-row="<?= $mod ?>">
                                    <?= $mod ?>
                                </label>
                            </td>
                            <?php foreach ($actions as $act): ?>
                                <?php 
                                $permString = $mod . '.' . $act;
                                $isChecked = in_array($permString, $rolePermissions);
                                ?>
                                <td class="px-6 py-4 whitespace-nowrap text-center">
                                    <input type="checkbox" name="permissions[]" value="<?= $permString ?>" <?= $isChecked ? 'checked' : '' ?> class="perm-checkbox row-<?= $mod ?> col-<?= $act ?> focus:ring-[#0A3A6B] h-5 w-5 text-[#0A3A6B] border-gray-300 rounded cursor-pointer transition duration-150 ease-in-out">
                                </td>
                            <?php endforeach; ?>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="flex justify-end pt-4">
            <button type="submit" class="bg-[#0A3A6B] hover:bg-blue-700 text-white font-bold py-3 px-8 rounded shadow text-lg">
                <?= $isEdit ? 'Update Role' : 'Create Role' ?>
            </button>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const permCheckboxes = document.querySelectorAll('.perm-checkbox');
    const rowSelectors = document.querySelectorAll('.row-selector');
    const colSelectors = document.querySelectorAll('.col-selector');
    const selectAllBtn = document.getElementById('select_all_btn');
    
    // Row selection (Module)
    rowSelectors.forEach(selector => {
        selector.addEventListener('change', function() {
            const rowClass = 'row-' + this.dataset.row;
            const boxes = document.querySelectorAll('.' + rowClass);
            boxes.forEach(box => {
                box.checked = this.checked;
            });
        });
    });
    
    // Column selection (Action)
    colSelectors.forEach(selector => {
        selector.addEventListener('change', function() {
            const colClass = 'col-' + this.dataset.col;
            const boxes = document.querySelectorAll('.' + colClass);
            boxes.forEach(box => {
                box.checked = this.checked;
            });
        });
    });
    
    // Select all button
    let allSelected = false;
    selectAllBtn.addEventListener('click', function() {
        allSelected = !allSelected;
        permCheckboxes.forEach(box => {
            box.checked = allSelected;
        });
        rowSelectors.forEach(box => box.checked = allSelected);
        colSelectors.forEach(box => box.checked = allSelected);
        
        this.textContent = allSelected ? 'Deselect All Permissions' : 'Select All Permissions';
    });
});
</script>
<?php
$content = ob_get_clean();
require ROOT_PATH . '/modules/shared/views/layouts/main.php';
?>