<?php
require_once 'auth.php';
require_once 'db/config.php';

if (!is_logged_in()) {
    header('Location: login.php');
    exit;
}

if (!hasPermission('manage_roles')) {
    header('Location: app.php');
    exit;
}

if (!isset($_GET['role_id'])) {
    header('Location: roles.php');
    exit;
}

$role_id = $_GET['role_id'];
$pdo = db();

// Fetch role details
$stmt = $pdo->prepare("SELECT * FROM roles WHERE id = ?");
$stmt->execute([$role_id]);
$role = $stmt->fetch();

if (!$role) {
    header('Location: roles.php');
    exit;
}

// Define all available permissions
$available_permissions = [
    'manage_candidates',
    'view_candidates',
    'manage_tasks',
    'view_tasks',
    'manage_workflows',
    'view_workflows',
    'manage_roles',
    'view_roles',
    'manage_users',
    'view_users'
];

// Fetch current permissions for the role
$stmt = $pdo->prepare("SELECT permission_name FROM role_permissions WHERE role_id = ?");
$stmt->execute([$role_id]);
$current_permissions = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_permissions'])) {
    $selected_permissions = $_POST['permissions'] ?? [];

    try {
        // Start a transaction
        $pdo->beginTransaction();

        // Delete existing permissions for the role
        $delete_stmt = $pdo->prepare("DELETE FROM role_permissions WHERE role_id = ?");
        $delete_stmt->execute([$role_id]);

        // Insert new permissions
        $insert_stmt = $pdo->prepare("INSERT INTO role_permissions (role_id, permission_name) VALUES (?, ?)");
        foreach ($selected_permissions as $permission) {
            if (in_array($permission, $available_permissions)) {
                $insert_stmt->execute([$role_id, $permission]);
            }
        }

        // Commit the transaction
        $pdo->commit();

        header("Location: roles.php");
        exit;
    } catch (PDOException $e) {
        $pdo->rollBack();
        error_log("Error updating permissions: " . $e->getMessage());
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Role</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/custom.css">
</head>
<body>
    <header class="header d-flex justify-content-between align-items-center">
        <div class="logo">
            <a href="app.php">
                <img src="assets/pasted-20251120-051320-b2b0cdfa.png" alt="FinMox Logo" style="height: 32px;">
            </a>
        </div>
        <nav class="d-flex align-items-center">
            <a href="app.php" class="btn btn-outline-primary me-2">Home</a>
            <a href="dashboard.php" class="btn btn-outline-primary me-2">Dashboard</a>
            <a href="workflows.php" class="btn btn-outline-primary me-2">Workflows</a>
            <a href="settings.php" class="btn btn-outline-primary me-3">Settings</a>
            <div class="dropdown">
                <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="userDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                    <?php echo htmlspecialchars($_SESSION['username']); ?>
                </button>
                <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                    <?php if (hasPermission('manage_roles')): ?>
                        <li><a class="dropdown-item" href="roles.php">Manage Roles</a></li>
                        <li><hr class="dropdown-divider"></li>
                    <?php endif; ?>
                    <li><a class="dropdown-item" href="logout.php">Logout</a></li>
                </ul>
            </div>
        </nav>
    </header>

    <main class="container-fluid">
        <h2 class="mb-4">Edit Role: <?php echo htmlspecialchars($role['name']); ?></h2>

        <div class="card">
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="save_permissions" value="1">
                    <div class="mb-3">
                        <label class="form-label">Permissions</label>
                        <?php foreach ($available_permissions as $permission): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="permissions[]" value="<?php echo $permission; ?>" id="perm_<?php echo $permission; ?>" <?php echo in_array($permission, $current_permissions) ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="perm_<?php echo $permission; ?>">
                                    <?php echo ucfirst(str_replace('_', ' ', $permission)); ?>
                                </label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <button type="submit" class="btn btn-primary">Save Permissions</button>
                    <a href="roles.php" class="btn btn-secondary">Cancel</a>
                </form>
            </div>
        </div>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>