<?php
// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'update_permissions') {
        try {
            $role_id = $_POST['role_id'];
            $perms = isset($_POST['permissions']) ? $_POST['permissions'] : [];
            
            // Encode as JSON
            $perms_json = json_encode($perms);
            
            $stmt = $db->prepare("UPDATE roles SET permissions = ? WHERE id = ?");
            $stmt->execute([$perms_json, $role_id]);
            
            $_SESSION['flash_message'] = __('permissions_updated');
        } catch (Exception $e) {
            $_SESSION['flash_message'] = "Error: " . $e->getMessage();
        }
        header("Location: roles.php");
        exit;
    }

    if (isset($_POST['action']) && $_POST['action'] === 'add_role') {
        try {
            $name = trim($_POST['name']);
            $perms = isset($_POST['permissions']) ? $_POST['permissions'] : [];
            
            if (empty($name)) {
                throw new Exception("Role name is required");
            }

            // Generate slug
            $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
            
            // Check if slug exists
            $stmt = $db->prepare("SELECT COUNT(*) FROM roles WHERE slug = ?");
            $stmt->execute([$slug]);
            if ($stmt->fetchColumn() > 0) {
                throw new Exception("Role with this name already exists");
            }

            // Encode permissions
            $perms_json = json_encode($perms);
            
            $stmt = $db->prepare("INSERT INTO roles (name, slug, permissions) VALUES (?, ?, ?)");
            $stmt->execute([$name, $slug, $perms_json]);
            
            $_SESSION['flash_message'] = "Role added successfully";
        } catch (Exception $e) {
            $_SESSION['flash_message'] = "Error: " . $e->getMessage();
        }
        header("Location: roles.php");
        exit;
    }
}

// Fetch Roles
$stmt = $db->query("SELECT * FROM roles ORDER BY name ASC");
$roles = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Define Available Permissions
$available_permissions = [
    'dashboard',
    'patients',
    'visits',
    'appointments',
    'home_visits',
    'queue',
    'laboratory',
    'xray',
    'pharmacy',
    'inventory',
    'billing',
    'insurance',
    'hr',
    'reports',
    'settings',
    'users'
];

?>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold text-dark mb-0"><?php echo __('roles_permissions'); ?></h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRoleModal">
            <i class="bi bi-plus-lg"></i> <?php echo __('add_role'); ?>
        </button>
    </div>

    <div class="card shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>ID</th>
                            <th><?php echo __('role'); ?></th>
                            <th><?php echo __('permissions'); ?></th>
                            <th><?php echo __('actions'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($roles as $role): ?>
                        <tr>
                            <td><?php echo $role['id']; ?></td>
                            <td><span class="badge bg-primary fs-6"><?php echo htmlspecialchars($role['name']); ?></span></td>
                            <td>
                                <?php 
                                $role_perms = json_decode($role['permissions'], true) ?? [];
                                if (in_array('*', $role_perms)) {
                                    echo '<span class="badge bg-success">All Access</span>';
                                } else {
                                    $count = count($role_perms);
                                    echo $count > 0 ? $count . ' modules' : 'None';
                                }
                                ?>
                            </td>
                            <td>
                                <?php if ($role['slug'] !== 'admin'): ?>
                                <button class="btn btn-sm btn-outline-primary" 
                                        data-id="<?php echo $role['id']; ?>"
                                        data-name="<?php echo htmlspecialchars($role['name']); ?>"
                                        data-permissions='<?php echo htmlspecialchars($role['permissions'], ENT_QUOTES, 'UTF-8'); ?>'
                                        onclick="editPermissions(this)">
                                    <i class="bi bi-shield-lock"></i> <?php echo __('permissions'); ?>
                                </button>
                                <?php else: ?>
                                <span class="text-muted"><i class="bi bi-lock-fill"></i> Full Access</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Role Modal -->
<div class="modal fade" id="addRoleModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form method="POST" class="modal-content">
            <input type="hidden" name="action" value="add_role">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo __('add_role'); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="roleName" class="form-label"><?php echo __('role_name'); ?></label>
                    <input type="text" class="form-control" id="roleName" name="name" required placeholder="e.g. Senior Nurse">
                </div>
                
                <h6 class="mt-4 mb-3"><?php echo __('permissions'); ?></h6>
                <div class="row">
                    <div class="col-12 mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="selectAllAdd">
                            <label class="form-check-label fw-bold" for="selectAllAdd"><?php echo __('select_all'); ?></label>
                        </div>
                        <hr>
                    </div>
                    <?php foreach ($available_permissions as $perm): ?>
                    <div class="col-md-4 mb-2">
                        <div class="form-check">
                            <input class="form-check-input perm-check-add" type="checkbox" name="permissions[]" value="<?php echo $perm; ?>" id="add_perm_<?php echo $perm; ?>">
                            <label class="form-check-label" for="add_perm_<?php echo $perm; ?>">
                                <?php echo __('permission_' . $perm); ?>
                            </label>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                <button type="submit" class="btn btn-primary"><?php echo __('save'); ?></button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Permissions Modal -->
<div class="modal fade" id="permissionsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <form method="POST" class="modal-content">
            <input type="hidden" name="action" value="update_permissions">
            <input type="hidden" name="role_id" id="permRoleId">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo __('edit_user'); ?>: <span id="permRoleName"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-12 mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="selectAll">
                            <label class="form-check-label fw-bold" for="selectAll"><?php echo __('select_all'); ?></label>
                        </div>
                        <hr>
                    </div>
                    <?php foreach ($available_permissions as $perm): ?>
                    <div class="col-md-4 mb-2">
                        <div class="form-check">
                            <input class="form-check-input perm-check" type="checkbox" name="permissions[]" value="<?php echo $perm; ?>" id="perm_<?php echo $perm; ?>">
                            <label class="form-check-label" for="perm_<?php echo $perm; ?>">
                                <?php echo __('permission_' . $perm); ?>
                            </label>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?php echo __('cancel'); ?></button>
                <button type="submit" class="btn btn-primary"><?php echo __('save_permissions'); ?></button>
            </div>
        </form>
    </div>
</div>

<script>
function editPermissions(btn) {
    document.getElementById('permRoleId').value = btn.dataset.id;
    document.getElementById('permRoleName').innerText = btn.dataset.name;
    
    // Reset all checkboxes
    document.querySelectorAll('.perm-check').forEach(c => c.checked = false);
    
    // Check active permissions
    let perms = [];
    try {
        perms = JSON.parse(btn.dataset.permissions);
    } catch(e) {
        perms = [];
    }
    
    if (perms && Array.isArray(perms)) {
        perms.forEach(p => {
            let checkbox = document.getElementById('perm_' + p);
            if (checkbox) checkbox.checked = true;
        });
    } else if (perms === '*') {
        // Handle wildcard if needed, though mostly admin specific
    }
    
    new bootstrap.Modal(document.getElementById('permissionsModal')).show();
}

document.getElementById('selectAll').addEventListener('change', function() {
    let checked = this.checked;
    document.querySelectorAll('.perm-check').forEach(c => c.checked = checked);
});

document.getElementById('selectAllAdd').addEventListener('change', function() {
    let checked = this.checked;
    document.querySelectorAll('.perm-check-add').forEach(c => c.checked = checked);
});
</script>
