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

include_once __DIR__ . "/config.php";

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

if (!isset($data['role_id'])) {
    echo json_encode(["success" => false, "message" => "role_id is required"]);
    exit;
}

$role_id = intval($data['role_id']);

try {
    // Check if role exists
    $check = $conn->prepare("SELECT id FROM roles WHERE id = ?");
    $check->bind_param("i", $role_id);
    $check->execute();
    $res = $check->get_result();

    if ($res->num_rows === 0) {
        echo json_encode(["success" => false, "message" => "Role not found"]);
        exit;
    }

    // Begin transaction
    $conn->begin_transaction();

    // 1️⃣ Delete role permissions associated with this role
    $stmt1 = $conn->prepare("DELETE FROM role_permissions WHERE role_id = ?");
    $stmt1->bind_param("i", $role_id);
    $stmt1->execute();

    // 2️⃣ Optional: Unassign this role from any admin users
    $stmt2 = $conn->prepare("UPDATE adminlogins SET role_id = NULL, userRole = NULL, userAccessLevel = NULL WHERE role_id = ?");
    $stmt2->bind_param("i", $role_id);
    $stmt2->execute();

    // 3️⃣ Delete the role itself
    $stmt3 = $conn->prepare("DELETE FROM roles WHERE id = ?");
    $stmt3->bind_param("i", $role_id);
    $stmt3->execute();

    // Commit transaction
    $conn->commit();

    echo json_encode([
        "success" => true,
        "message" => "Role and associated permissions deleted successfully"
    ]);

} catch (Throwable $e) {
    // Rollback in case of error
    if ($conn->errno) {
        $conn->rollback();
    }

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