<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
include_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$response = ["success" => false, "message" => "Invalid request"];

if ($method === 'POST') { // Create new role
    $data = json_decode(file_get_contents("php://input"));
    if (isset($data->name) && isset($data->description) && isset($data->access_type) && isset($data->permissions)) {
        $stmt = $conn->prepare("INSERT INTO roles (name, description, access_type) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $data->name, $data->description, $data->access_type);
        if ($stmt->execute()) {
            $role_id = $conn->insert_id;
            // Assign permissions
            foreach ($data->permissions as $perm_id) {
                $stmt_perm = $conn->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
                $stmt_perm->bind_param("ii", $role_id, $perm_id);
                $stmt_perm->execute();
            }
            $response = ["success" => true, "message" => "Role created", "role_id" => $role_id];
        } else {
            $response["message"] = "Failed to create role";
        }
    }
} elseif ($method === 'GET') { // List all roles
    $result = $conn->query("SELECT * FROM roles");
    $roles = [];
    while ($row = $result->fetch_assoc()) {
        // Fetch permissions for each role
        $perm_res = $conn->query("SELECT p.name FROM permissions p JOIN role_permissions rp ON p.id = rp.permission_id WHERE rp.role_id = " . $row['id']);
        $perms = [];
        while ($perm_row = $perm_res->fetch_assoc()) $perms[] = $perm_row['name'];
        $row['permissions'] = $perms;
        $roles[] = $row;
    }
    $response = ["success" => true, "roles" => $roles];
} elseif ($method === 'PUT') { // Update role (e.g., change access_type or permissions)
    $data = json_decode(file_get_contents("php://input"));
    if (isset($data->id) && isset($data->access_type) && isset($data->permissions)) {
        // Update role
        $stmt = $conn->prepare("UPDATE roles SET access_type = ? WHERE id = ?");
        $stmt->bind_param("si", $data->access_type, $data->id);
        $stmt->execute();
        // Clear old permissions
        $conn->query("DELETE FROM role_permissions WHERE role_id = " . $data->id);
        // Add new
        foreach ($data->permissions as $perm_id) {
            $stmt_perm = $conn->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
            $stmt_perm->bind_param("ii", $data->id, $perm_id);
            $stmt_perm->execute();
        }
        $response = ["success" => true, "message" => "Role updated"];
    }
} // Add DELETE if needed.

echo json_encode($response);
?>