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

include_once __DIR__ . '/config.php';
include_once __DIR__ . '/connection.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

$input = json_decode(file_get_contents("php://input"), true);
$rank_number = intval($input['rank_number'] ?? 0);
$min_active_clients = intval($input['min_active_clients'] ?? 0);
$rank_name = trim($input['rank_name'] ?? '');

if ($rank_number < 1 || $min_active_clients < 0 || empty($rank_name)) {
    echo json_encode(["status"=>"error","message"=>"Invalid input"]);
    exit;
}

// Insert new rank
$stmt = $conn->prepare("INSERT INTO ranks (rank_number, min_active_clients, rank_name) VALUES (?, ?, ?)");
$stmt->bind_param("iis", $rank_number, $min_active_clients, $rank_name);

if ($stmt->execute()) {
    echo json_encode([
        "status"=>"success",
        "message"=>"Rank added successfully",
        "rank_id"=>$stmt->insert_id
    ]);
} else {
    echo json_encode([
        "status"=>"error",
        "message"=>"Error: ".$conn->error
    ]);
}
$stmt->close();
?>
