<?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);
$level = intval($input['level'] ?? 0);
$types = $input['types'] ?? ["standard","cent","pro","prime","pamm","demo"];

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

$added = [];
$skipped = [];

foreach ($types as $type) {
    $columnName = "level_{$level}_{$type}_commission";
    // Check if column exists
    $check = $conn->query("SHOW COLUMNS FROM ranks LIKE '$columnName'");
    if ($check->num_rows > 0) {
        $skipped[] = $columnName;
        continue;
    }

    $sql = "ALTER TABLE ranks ADD COLUMN `$columnName` DOUBLE DEFAULT 1";
    if ($conn->query($sql) === TRUE) {
        $added[] = $columnName;
    } else {
        $skipped[] = $columnName;
    }
}

echo json_encode([
    "status"=>"success",
    "level"=>$level,
    "columns_added"=>$added,
    "columns_skipped_or_error"=>$skipped
]);
?>
