<?php
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

include_once __DIR__ . "/config.php";

$data = json_decode(file_get_contents("php://input"), true);

if (!$data || !isset($data['name']) || !isset($data['access_type'])) {
    echo json_encode(["success" => false, "message" => "name and access_type are required"]);
    exit;
}

$name         = trim($data['name']);
$description  = $data['description'] ?? "";
$access_type  = $data['access_type']; // full, read-only, custom
$permissions  = $data['permissions'] ?? []; // array of permission IDs (only for custom)

try {
    $conn->begin_transaction();

    // Check if role already exists
    $check = $conn->prepare("SELECT id FROM roles WHERE name = ?");
    $check->bind_param("s", $name);
    $check->execute();
    if ($check->get_result()->num_rows > 0) {
        echo json_encode(["success" => false, "message" => "Role already exists"]);
        exit;
    }

    // Insert Role
    $stmt = $conn->prepare("INSERT INTO roles (name, description, access_type, created_at) VALUES (?, ?, ?, NOW())");
    $stmt->bind_param("sss", $name, $description, $access_type);
    $stmt->execute();
    $role_id = $stmt->insert_id;

    // Assign Permissions Based on access_type
    if ($access_type === "full") {
        $conn->query("INSERT INTO role_permissions (role_id, permission_id) SELECT $role_id, id FROM permissions");
    }
    elseif ($access_type === "read-only") {
        $conn->query("INSERT INTO role_permissions (role_id, permission_id) SELECT $role_id, id FROM permissions WHERE name LIKE 'view_%'");
    }
    elseif ($access_type === "custom" && !empty($permissions)) {
        $perm_stmt = $conn->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
        foreach ($permissions as $perm_id) {
            $perm_id = (int)$perm_id;
            $perm_stmt->bind_param("ii", $role_id, $perm_id);
            $perm_stmt->execute();
        }
    }

    $conn->commit();

    echo json_encode([
        "success" => true,
        "message" => "Role created with permissions successfully",
        "role_id" => $role_id
    ]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        "success" => false,
        "message" => "Server error",
        "error" => $e->getMessage()
    ]);
}
?>