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

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

// --- Fetch user accounts for dropdown ---
if(isset($data['action']) && $data['action'] === 'fetch_accounts') {
    $accounts = [];
    $user_id = $data['user_id'] ?? 0;

    $stmt = $conn->prepare("SELECT trade_id, email, account_name, account_type, deposit FROM liveaccounts WHERE user_id=?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    while($row = $result->fetch_assoc()) {
        $accounts[] = $row;
    }

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

// --- Transfer funds ---
$fromTrade = $data['fromTrade'] ?? 0;
$toTrade   = $data['toTrade'] ?? 0;
$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, trade_id, account_name, deposit FROM liveaccounts WHERE trade_id=? OR trade_id=?");
$stmt->bind_param("ii", $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;
}

if($fromAccount['deposit'] < $amount){
    echo json_encode(["success"=>false,"error"=>"Insufficient deposit in source account"]);
    exit;
}

// --- MT5 Connection ---
$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;
}

// Deduct from source
$userFrom = new MTUser();
$api->UserGet(intval($fromAccount['trade_id']), $userFrom);
$ticketFrom = 0;
$ret1 = $api->TradeBalance($userFrom->Login, MTEnDealAction::DEAL_BALANCE, -$amount, "Transfer to ".$toAccount['trade_id'], $ticketFrom);

// Add to target
$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
    $stmtUpdate = $conn->prepare("UPDATE liveaccounts SET deposit=deposit-? WHERE id=?");
    $stmtUpdate->bind_param("di", $amount, $fromAccount['id']);
    $stmtUpdate->execute();

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

    // Insert into internal_transfers for admin tracking
    $stmtLog = $conn->prepare("
        INSERT INTO internal_transfers (from_trade, to_trade, amount, ticket_from, ticket_to, notes, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $notes = "Transfer from $fromTrade to $toTrade";
    $status = "Approved";
    $stmtLog->bind_param("ssdiiss", $fromTrade, $toTrade, $amount, $ticketFrom, $ticketTo, $notes, $status);
    $stmtLog->execute();

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