<?php
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");

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

// Path to connection.php
$filePath = __DIR__ . "/../connection.php";

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

$ip = $input["ip"] ?? null;
$port = $input["port"] ?? null;
$login = $input["login"] ?? null;
$password = $input["password"] ?? null;

// Validate input
if (!$ip || !$port || !$login || !$password) {
    echo json_encode(["success" => false, "message" => "Missing required fields"]);
    exit;
}

// Read the existing file
$fileContent = file_get_contents($filePath);

// Replace define() lines using regex
$fileContent = preg_replace('/define\("MT5_SERVER_IP",\s*".*?"\);/', 'define("MT5_SERVER_IP", "' . $ip . '");', $fileContent);
$fileContent = preg_replace('/define\("MT5_SERVER_PORT",\s*\d+\);/', 'define("MT5_SERVER_PORT", ' . $port . ');', $fileContent);
$fileContent = preg_replace('/define\("MT5_SERVER_WEB_LOGIN",\s*".*?"\);/', 'define("MT5_SERVER_WEB_LOGIN", "' . $login . '");', $fileContent);
$fileContent = preg_replace('/define\("MT5_SERVER_WEB_PASSWORD",\s*".*?"\);/', 'define("MT5_SERVER_WEB_PASSWORD", "' . $password . '");', $fileContent);

// Save back to file
if (file_put_contents($filePath, $fileContent)) {
    echo json_encode(["success" => true, "message" => "Configuration updated successfully"]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to update configuration file"]);
}
?>
