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

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

include_once __DIR__ . '/connection.php';      // MySQL connection
include_once __DIR__ . "/mt5_api/mt5_api.php"; // MT5 connection
include_once __DIR__ . "/config.php";          // Config

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

$trade_id = $data['trade_id'] ?? '';
$action   = $data['action'] ?? '';
$value    = $data['value'] ?? '';

if (!$trade_id || !$action || !$value) {
    echo json_encode(["success" => false, "error" => "Invalid parameters"]);
    exit;
}

// Fetch user MT5 account info
$stmt = $conn->prepare("SELECT trade_id, account_type, account_name FROM liveaccounts WHERE trade_id=? LIMIT 1");
$stmt->bind_param("i", $trade_id);
$stmt->execute();
$userResult = $stmt->get_result();
$userRow = $userResult->fetch_assoc();

if (!$userRow) {    
    echo json_encode(["success" => false, "error" => "Trade ID not found"]);
    exit;
}

$mt5Login = intval($userRow['trade_id']);

// Connect to MT5
$api = new MTWebAPI("WebAPITesterLocal", "./logs", true);
$ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 5, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
if ($ret != MTRetCode::MT_RET_OK) {
    echo json_encode(["success" => false, "error" => "MT5 connection failed: $ret"]);
    exit;
}

// Fetch MT5 user
$userMT5 = new MTUser();
$ret = $api->UserGet($mt5Login, $userMT5);
if ($ret != MTRetCode::MT_RET_OK) {
    $api->Disconnect();
    echo json_encode(["success" => false, "error" => "User not found in MT5"]);
    exit;
}

// Perform update
switch ($action) {
    case "leverage":
    $leverage = str_replace("1:", "", $value);  // Remove "1:" prefix if present
    $userMT5->Leverage = (int)$leverage;

    // Update leverage in liveaccounts
    $stmt = $conn->prepare("UPDATE liveaccounts SET leverage=? WHERE trade_id=?");
    $stmt->bind_param("si", $leverage, $trade_id);
    $stmt->execute();
    break;


    case "mainPassword":
        $userMT5->MainPassword = $value;

        $stmt = $conn->prepare("UPDATE liveaccounts SET trader_pwd=? WHERE trade_id=?");
        $stmt->bind_param("si", $value, $trade_id);
        $stmt->execute();
        break;

    case "investPassword":
        $userMT5->InvestPassword = $value;

        $stmt = $conn->prepare("UPDATE liveaccounts SET invester_pwd=? WHERE trade_id=?");
        $stmt->bind_param("si", $value, $trade_id);
        $stmt->execute();
        break;

    default:
        $api->Disconnect();
        echo json_encode(["success" => false, "error" => "Invalid action"]);
        exit;
}

// Update MT5 user
$updatedUser = null;
$retUpdate = $api->UserUpdate($userMT5, $updatedUser);
$api->Disconnect();

if ($retUpdate === MTRetCode::MT_RET_OK) {
    echo json_encode([
        "success" => true,
        "message" => "✅ {$action} updated successfully!",
        "login" => $mt5Login
    ]);
} else {
    echo json_encode([
        "success" => false,
        "error" => "❌ Failed to update {$action}",
        "details" => $retUpdate
    ]);
}
?>
