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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

include_once 'config.php';

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

$response = ["success" => false, "message" => "Invalid request"];

if (isset($data->empId) && isset($data->role_id)) {
    $empId = $conn->real_escape_string($data->empId);
    $role_id = (int)$data->role_id;

    // Optional: validate role exists
    $check = $conn->query("SELECT id FROM roles WHERE id = $role_id");
    if ($check->num_rows == 0) {
        $response["message"] = "Invalid role";
        echo json_encode($response);
        exit;
    }

    $stmt = $conn->prepare("UPDATE adminlogins SET role_id = ? WHERE empId = ?");
    $stmt->bind_param("is", $role_id, $empId);

    if ($stmt->execute()) {
        $response = ["success" => true, "message" => "Role assigned successfully"];
    } else {
        $response["message"] = "Failed to assign role";
    }
    $stmt->close();
} else {
    $response["message"] = "empId and role_id required";
}

echo json_encode($response);
?>