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

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

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

// Check if file exists
if (!file_exists($filePath)) {
    echo json_encode(["success" => false, "message" => "Configuration file not found"]);
    exit;
}

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

// Extract values using regex
$ip = null;
$port = null;
$login = null;
$password = null;

if (preg_match('/define\("MT5_SERVER_IP",\s*"(.*?)"\);/', $fileContent, $matches)) {
    $ip = $matches[1];
}
if (preg_match('/define\("MT5_SERVER_PORT",\s*(\d+)\);/', $fileContent, $matches)) {
    $port = $matches[1];
}
if (preg_match('/define\("MT5_SERVER_WEB_LOGIN",\s*"(.*?)"\);/', $fileContent, $matches)) {
    $login = $matches[1];
}
if (preg_match('/define\("MT5_SERVER_WEB_PASSWORD",\s*"(.*?)"\);/', $fileContent, $matches)) {
    $password = $matches[1];
}

// Check if all values were found
if ($ip && $port && $login && $password) {
    echo json_encode([
        "success" => true,
        "data" => [
            "MT5_SERVER_IP" => $ip,
            "MT5_SERVER_PORT" => (int)$port,
            "MT5_SERVER_WEB_LOGIN" => $login,
            "MT5_SERVER_WEB_PASSWORD" => $password
        ]
    ]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to parse configuration"]);
}
?>
