<?php
/**
 * Roles & Permissions Management
 * Kenyan Pension & Life Insurance Management System
 */

require_once 'layouts/main.php';
require_once 'includes/auth.php';

requireLogin();
requirePermission('manage_roles');

$action = $_GET['action'] ?? 'list';
$role_id = $_GET['id'] ?? null;
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'create') {
        $sql = "INSERT INTO roles (role_name, role_code, description, is_active)
                VALUES (?, ?, ?, 1)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sss",
            $_POST['role_name'],
            $_POST['role_code'],
            $_POST['description'] ?? null
        );
        if ($stmt->execute()) {
            $message = 'Role created successfully';
            $messageType = 'success';
            $action = 'list';
        } else {
            $message = 'Failed to create role';
            $messageType = 'danger';
        }
    } elseif ($action === 'assign_permissions' && $role_id) {
        // Remove existing permissions
        $conn->query("DELETE FROM role_permissions WHERE role_id = $role_id");
        
        // Add new permissions
        if (isset($_POST['permissions']) && is_array($_POST['permissions'])) {
            $insertSql = "INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)";
            $insertStmt = $conn->prepare($insertSql);
            foreach ($_POST['permissions'] as $permission_id) {
                $insertStmt->bind_param("ii", $role_id, $permission_id);
                $insertStmt->execute();
            }
            $message = 'Permissions updated successfully';
            $messageType = 'success';
        }
    }
}

// Get roles
$roles = $conn->query("SELECT * FROM roles WHERE is_active = 1 ORDER BY role_name")->fetch_all(MYSQLI_ASSOC);

// Get permissions
$permissions = $conn->query("SELECT * FROM permissions ORDER BY permission_name")->fetch_all(MYSQLI_ASSOC);

// Get role permissions if editing
$role_permissions = [];
if ($role_id && $action === 'assign_permissions') {
    $rpResult = $conn->query("SELECT permission_id FROM role_permissions WHERE role_id = $role_id");
    while ($row = $rpResult->fetch_assoc()) {
        $role_permissions[] = $row['permission_id'];
    }
}

$pageTitle = 'Roles & Permissions';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Roles & Permissions')); ?>
    <link rel="stylesheet" href="assets/css/pension-dashboard.css">
    <?php include 'layouts/head-css.php'; ?>
</head>

<body data-sidebar="dark">
    <div id="layout-wrapper">
        <?php include 'layouts/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="welcome-header" style="background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Roles & Permissions</h2>
                                <p>Manage user roles and their permissions</p>
                            </div>
                        </div>
                    </div>

                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <?php if ($action === 'create'): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Add New Role</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <form method="POST">
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Role Name <span class="text-danger">*</span></label>
                                                    <input type="text" name="role_name" class="form-control" required>
                                                </div>
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Role Code <span class="text-danger">*</span></label>
                                                    <input type="text" name="role_code" class="form-control" required>
                                                    <small class="text-muted">Unique identifier (e.g., ADMIN, MEMBER)</small>
                                                </div>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Description</label>
                                                <textarea name="description" class="form-control" rows="3"></textarea>
                                            </div>
                                            <button type="submit" class="btn btn-primary">Save Role</button>
                                            <a href="roles.php" class="btn btn-secondary">Cancel</a>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php elseif ($action === 'assign_permissions' && $role_id): ?>
                        <?php 
                        $role = $conn->query("SELECT * FROM roles WHERE role_id = $role_id")->fetch_assoc();
                        if (!$role) {
                            header('Location: roles.php');
                            exit();
                        }
                        ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Assign Permissions - <?php echo htmlspecialchars($role['role_name']); ?></h4>
                                    </div>
                                    <div class="page-card-body">
                                        <form method="POST">
                                            <div class="row">
                                                <?php 
                                                $grouped_permissions = [];
                                                foreach ($permissions as $perm) {
                                                    $category = $perm['permission_category'] ?? 'GENERAL';
                                                    if (!isset($grouped_permissions[$category])) {
                                                        $grouped_permissions[$category] = [];
                                                    }
                                                    $grouped_permissions[$category][] = $perm;
                                                }
                                                
                                                foreach ($grouped_permissions as $category => $perms): 
                                                ?>
                                                    <div class="col-md-6 mb-4">
                                                        <h6 class="mb-3"><?php echo htmlspecialchars($category); ?></h6>
                                                        <?php foreach ($perms as $perm): ?>
                                                            <div class="form-check mb-2">
                                                                <input class="form-check-input" type="checkbox" 
                                                                       name="permissions[]" 
                                                                       value="<?php echo $perm['permission_id']; ?>"
                                                                       id="perm_<?php echo $perm['permission_id']; ?>"
                                                                       <?php echo in_array($perm['permission_id'], $role_permissions) ? 'checked' : ''; ?>>
                                                                <label class="form-check-label" for="perm_<?php echo $perm['permission_id']; ?>">
                                                                    <?php echo htmlspecialchars($perm['permission_name']); ?>
                                                                </label>
                                                            </div>
                                                        <?php endforeach; ?>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line me-2"></i>Save Permissions
                                            </button>
                                            <a href="roles.php" class="btn btn-secondary">Cancel</a>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="row mb-3">
                            <div class="col-12">
                                <a href="roles.php?action=create" class="btn btn-primary">
                                    <i class="ri-user-add-line me-2"></i>Add Role
                                </a>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Roles List</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <div class="table-responsive">
                                            <table class="data-table">
                                                <thead>
                                                    <tr>
                                                        <th>Role Name</th>
                                                        <th>Role Code</th>
                                                        <th>Description</th>
                                                        <th>Users Count</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php if (empty($roles)): ?>
                                                        <tr><td colspan="5" class="text-center">No roles found</td></tr>
                                                    <?php else: ?>
                                                        <?php foreach ($roles as $role): 
                                                            $userCount = $conn->query("SELECT COUNT(*) as count FROM users WHERE role_id = {$role['role_id']} AND deleted_at IS NULL")->fetch_assoc()['count'];
                                                        ?>
                                                            <tr>
                                                                <td><strong><?php echo htmlspecialchars($role['role_name']); ?></strong></td>
                                                                <td><span class="badge bg-info"><?php echo htmlspecialchars($role['role_code']); ?></span></td>
                                                                <td><?php echo htmlspecialchars($role['description'] ?? 'N/A'); ?></td>
                                                                <td><?php echo $userCount; ?> users</td>
                                                                <td>
                                                                    <a href="roles.php?action=assign_permissions&id=<?php echo $role['role_id']; ?>" class="btn btn-sm btn-success">
                                                                        <i class="ri-shield-check-line me-1"></i>Permissions
                                                                    </a>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
