<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
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 __DIR__ . "/config.php";

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

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

$rank_id = intval($input['rank_id']);
unset($input['rank_id']); // Remove it so we only update other fields

if (empty($input)) {
    echo json_encode(["success" => false, "message" => "No fields provided to update"]);
    exit;
}

try {
    // Build dynamic SQL query
    $updateFields = [];
    $params = [];
    $types = '';

    foreach ($input as $key => $value) {
        $updateFields[] = "$key = ?";
        $params[] = $value;
        // Detect parameter type automatically
        $types .= is_numeric($value) ? 'd' : 's';
    }

    $sql = "UPDATE ranks SET " . implode(", ", $updateFields) . " WHERE rank_id = ?";
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        throw new Exception("Failed to prepare SQL: " . $conn->error);
    }

    $types .= 'i'; // rank_id type
    $params[] = $rank_id;

    // Bind parameters dynamically
    $stmt->bind_param($types, ...$params);

    if ($stmt->execute()) {
        echo json_encode([
            "success" => true,
            "message" => "Rank updated successfully."
        ]);
    } else {
        echo json_encode([
            "success" => false,
            "message" => "Failed to update rank: " . $stmt->error
        ]);
    }

    $stmt->close();
} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Error: " . $e->getMessage()
    ]);
}

$conn->close();
?>
