<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

include "config.php";       // DB config
include "connection.php";   // includes mt5_api already

$data = json_decode(file_get_contents("php://input"), true);
$trade_id = $data['trade_id'] ?? 0;

if (!$trade_id) {
    echo json_encode(["success" => false, "message" => "Missing trade_id"]);
    exit;
}

// ✅ Initialize MT5
$mt5 = new MT5Connection();
if (!$mt5->connect()) {
    echo json_encode([
        "success" => false,
        "message" => "MT5 connection failed",
        "error_code" => $mt5->lastError()
    ]);
    exit;
}

$api = $mt5->api; // MTWebAPI instance

// ✅ Fetch account
$account = null;
if (($error = $api->UserAccountGet($trade_id, $account)) != MTRetCode::MT_RET_OK) {
    echo json_encode([
        "success" => false,
        "message" => "Failed to fetch account",
        "error_code" => $error
    ]);
    exit;
}

// ✅ Convert MT5 account object into array
$account_data = [];
foreach ($account as $key => $value) {
    $account_data[$key] = $value;
}

// ✅ Fetch deposits
$deposits = [];
$sql = "SELECT id, deposit_amount, deposit_type, company_bank, client_bank, account_number, deposed_date, Status, utr_number, ifsc 
        FROM wallet_deposit WHERE trade_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $trade_id);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    $deposits[] = $row;
}
$stmt->close();

// ✅ Fetch withdrawals
$withdrawals = [];
$sql = "SELECT id, withdraw_amount, withdraw_type, company_bank, client_bank, account_holder_name, withdraw_date, Status, transaction_id, account_number 
        FROM wallet_withdraw WHERE trade_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $trade_id);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    $withdrawals[] = $row;
}
$stmt->close();

// ✅ Fetch internal transfers (check both from_trade and to_trade)
$transfers = [];
$sql = "SELECT id, from_trade, to_trade, amount, ticket_from, ticket_to, status, notes, created_at 
        FROM internal_transfers 
        WHERE from_trade = ? OR to_trade = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $trade_id, $trade_id);
$stmt->execute();
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
    $transfers[] = $row;
}
$stmt->close();

// ✅ Build final JSON response
echo json_encode([
    "success" => true,
    "account" => $account_data,
    "deposits" => $deposits,
    "withdrawals" => $withdrawals,
    "internal_transfers" => $transfers
], JSON_PRETTY_PRINT);
?>
