<?php
// Enable full error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

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

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

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

// -------------------------
// 1️⃣ Fetch user accounts with MT5 balance
// -------------------------
if (isset($data['action']) && $data['action'] === 'fetch_accounts') {
    $accounts = [];
    $user_id = $data['user_id'] ?? 0;

    $stmt = $conn->prepare("SELECT id, trade_id, email, account_name, account_type FROM liveaccounts WHERE user_id=?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    // 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"]);
        exit;
    }

    while ($row = $result->fetch_assoc()) {
    $user = new MTUser();
$account = new MTAccount();

if ($api->UserGet(intval($row['trade_id']), $user) == MTRetCode::MT_RET_OK) {
    $row['deposit'] = $user->Balance ?? 0;
    $row['leverage'] = $user->Leverage ?? 0;

    // Fetch live account data (Equity, Margin, etc.)
    if ($api->UserAccountGet(intval($row['trade_id']), $account) == MTRetCode::MT_RET_OK) {
        $row['equity'] = $account->Equity ?? 0;
    } else {
        $row['equity'] = 0;
    }
} else {
    $row['deposit'] = 0;
    $row['equity']  = 0;
    $row['leverage'] = 0;
}


    // Update DB deposit
    $stmtUpdate = $conn->prepare("UPDATE liveaccounts SET deposit=?, leverage=? WHERE id=?");
    $depositVal = $row['deposit'];
    $leverageVal = $row['leverage'];
    $stmtUpdate->bind_param("dii", $depositVal, $leverageVal, $row['id']);
    $stmtUpdate->execute();

    $accounts[] = $row;
}


    $api->Disconnect();
    echo json_encode(["success" => true, "accounts" => $accounts]);
    exit;
}

// -------------------------
// 2️⃣ Transfer funds
// -------------------------
$fromTrade = $data['fromTrade'] ?? '';
$toTrade   = $data['toTrade'] ?? '';
$amount    = floatval($data['amount'] ?? 0);

if (!$fromTrade || !$toTrade || $fromTrade === $toTrade || $amount <= 0) {
    echo json_encode(["success" => false, "error" => "Invalid parameters"]);
    exit;
}

// Get both accounts
$stmt = $conn->prepare("SELECT id, user_id, trade_id, account_name, deposit FROM liveaccounts WHERE trade_id=? OR trade_id=?");
$stmt->bind_param("ss", $fromTrade, $toTrade);
$stmt->execute();
$accountsRes = $stmt->get_result();

$fromAccount = $toAccount = null;
while ($row = $accountsRes->fetch_assoc()) {
    if ($row['trade_id'] === $fromTrade) $fromAccount = $row;
    if ($row['trade_id'] === $toTrade) $toAccount = $row;
}

if (!$fromAccount || !$toAccount) {
    echo json_encode(["success" => false, "error" => "Accounts not found"]);
    exit;
}

// 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"]);
    exit;
}

// Fetch MT5 balance for source
$userFrom = new MTUser();
$api->UserGet(intval($fromAccount['trade_id']), $userFrom);

if ($userFrom->Balance < $amount) {
    echo json_encode(["success" => false, "error" => "Insufficient balance in source account"]);
    exit;
}

// MT5 transfer
$ticketFrom = 0;
$ret1 = $api->TradeBalance($userFrom->Login, MTEnDealAction::DEAL_BALANCE, -$amount, "Transfer to " . $toAccount['trade_id'], $ticketFrom);

$userTo = new MTUser();
$api->UserGet(intval($toAccount['trade_id']), $userTo);
$ticketTo = 0;
$ret2 = $api->TradeBalance($userTo->Login, MTEnDealAction::DEAL_BALANCE, $amount, "Transfer from " . $fromAccount['trade_id'], $ticketTo);

if ($ret1 == MTRetCode::MT_RET_OK && $ret2 == MTRetCode::MT_RET_OK) {

    // -------------------------
    // Update DB deposits
    // -------------------------
    $newDepositFrom = $userFrom->Balance - $amount;
    $stmtUpdate = $conn->prepare("UPDATE liveaccounts SET deposit=? WHERE id=?");
    $stmtUpdate->bind_param("di", $newDepositFrom, $fromAccount['id']);
    $stmtUpdate->execute();

    $newDepositTo = $userTo->Balance + $amount;
    $stmtUpdate2 = $conn->prepare("UPDATE liveaccounts SET deposit=? WHERE id=?");
    $stmtUpdate2->bind_param("di", $newDepositTo, $toAccount['id']);
    $stmtUpdate2->execute();

    // -------------------------
    // Insert into internal_transfers
    // -------------------------
    $stmtLog = $conn->prepare("
        INSERT INTO internal_transfers (user_id, from_trade, to_trade, amount, ticket_from, ticket_to, notes, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $user_id = $fromAccount['user_id'];
    $notes = "Transfer from $fromTrade to $toTrade";
    $status = "approved";

    // Use variables only for bind_param
    $ticketFromInt = intval($ticketFrom);
    $ticketToInt   = intval($ticketTo);

    $stmtLog->bind_param(
        "issdiiss",
        $user_id,
        $fromTrade,
        $toTrade,
        $amount,
        $ticketFromInt,
        $ticketToInt,
        $notes,
        $status
    );

    try {
        $stmtLog->execute();
    } catch (Exception $e) {
        echo json_encode([
            "success" => false,
            "error" => "Internal transfer logging failed: " . $e->getMessage()
        ]);
        exit;
    }

    echo json_encode([
        "success" => true,
        "message" => "Transfer successful",
        "transfer_id" => $conn->insert_id
    ]);

} else {
    echo json_encode(["success" => false, "error" => "MT5 transfer failed"]);
}

$api->Disconnect();
?>
