<?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['role_id'])) {
    echo json_encode(["success" => false, "message" => "role_id is required"]);
    exit;
}

$role_id     = (int)$data['role_id'];
$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)

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

try {
    $conn->begin_transaction();

    // 1. Check if role exists
    $check = $conn->prepare("SELECT id FROM roles WHERE id = ?");
    $check->bind_param("i", $role_id);
    $check->execute();
    if ($check->get_result()->num_rows === 0) {
        $conn->rollback();
        echo json_encode(["success" => false, "message" => "Role not found"]);
        exit;
    }

    // 2. Prevent duplicate role name (except for same role)
    $name_check = $conn->prepare("SELECT id FROM roles WHERE name = ? AND id != ?");
    $name_check->bind_param("si", $name, $role_id);
    $name_check->execute();
    if ($name_check->get_result()->num_rows > 0) {
        $conn->rollback();
        echo json_encode(["success" => false, "message" => "Role name already exists"]);
        exit;
    }

    // 3. Update role details
    $stmt = $conn->prepare("UPDATE roles SET name = ?, description = ?, access_type = ? WHERE id = ?");
    $stmt->bind_param("sssi", $name, $description, $access_type, $role_id);
    $stmt->execute();

    // 4. DELETE old permissions
    $conn->query("DELETE FROM role_permissions WHERE role_id = $role_id");

    // 5. INSERT new 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") {
        if (empty($permissions) || !is_array($permissions)) {
            $conn->rollback();
            echo json_encode(["success" => false, "message" => "Custom role must have at least one permission"]);
            exit;
        }

        $perm_stmt = $conn->prepare("INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
        foreach ($permissions as $perm_id) {
            $perm_id = (int)$perm_id;
            if ($perm_id > 0) {
                $perm_stmt->bind_param("ii", $role_id, $perm_id);
                $perm_stmt->execute();
            }
        }
    }

    $conn->commit();

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

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