<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('role_management');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_permissions'])) {
        $role_id = (int)$_POST['role_id'];
        $perms = $_POST['permissions'] ?? [];
        $pdo->prepare("DELETE FROM role_permissions WHERE role_id=?")->execute([$role_id]);
        $stmt = $pdo->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?,?)");
        foreach ($perms as $pid) {
            $stmt->execute([$role_id, (int)$pid]);
        }
        logActivity('Updated Permissions', 'Roles', $role_id);
        $_SESSION['success'] = 'Permissions updated successfully.';
        header('Location: roles.php');
        exit;
    }

    if (isset($_POST['action']) && $_POST['action'] === 'add_role') {
        $name = trim($_POST['name']);
        $desc = trim($_POST['description']);
        if ($name) {
            $stmt = $pdo->prepare("INSERT INTO roles (role_name, description) VALUES (?,?)");
            $stmt->execute([$name, $desc]);
            $_SESSION['success'] = 'Role created successfully.';
            header('Location: roles.php');
            exit;
        }
    }
}

$roles = $pdo->query("SELECT * FROM roles ORDER BY id")->fetchAll();
$permissions = $pdo->query("SELECT * FROM permissions ORDER BY module_name, permission_name")->fetchAll();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-shield-alt me-2"></i>Roles & Permissions</h4>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addRoleModal"><i class="fas fa-plus me-1"></i>Add Role</button>
        </div>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <?php foreach ($roles as $role): ?>
        <div class="card mb-3">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><strong><?= htmlspecialchars($role['role_name']) ?></strong> - <small class="text-muted"><?= htmlspecialchars($role['description']) ?></small></span>
            </div>
            <div class="card-body">
                <?php if ($role['id'] == 1): ?>
                    <p class="text-muted mb-0"><i class="fas fa-info-circle me-1"></i>Super Admin has all permissions by default.</p>
                <?php else: ?>
                <form method="POST">
                    <input type="hidden" name="role_id" value="<?= $role['id'] ?>">
                    <div class="row">
                        <?php
                        $stmt = $pdo->prepare("SELECT permission_id FROM role_permissions WHERE role_id=?");
                        $stmt->execute([$role['id']]);
                        $rp = $stmt->fetchAll(PDO::FETCH_COLUMN);
                        $last_module = '';
                        foreach ($permissions as $p):
                            if ($p['module_name'] != $last_module):
                                $last_module = $p['module_name'];
                        ?>
                        <div class="col-md-3 mb-2"><strong><?= $p['module_name'] ?></strong></div>
                        <?php endif; ?>
                        <div class="col-md-3 mb-1">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="permissions[]" value="<?= $p['id'] ?>" id="perm_<?= $role['id'] ?>_<?= $p['id'] ?>" <?= in_array($p['id'], $rp) ? 'checked' : '' ?>>
                                <label class="form-check-label" for="perm_<?= $role['id'] ?>_<?= $p['id'] ?>"><?= htmlspecialchars($p['permission_name']) ?></label>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <button type="submit" name="update_permissions" class="btn btn-primary mt-2"><i class="fas fa-save me-1"></i>Update Permissions</button>
                </form>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Add Role Modal -->
<div class="modal fade" id="addRoleModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header"><h5 class="modal-title">Add Role</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_role">
                    <div class="mb-3">
                        <label class="form-label">Role Name *</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
