<?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 preflight request
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    http_response_code(200);
    exit;
}

ini_set("display_errors", 1);
error_reporting(E_ALL);

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

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

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

$email = $input["email"];

// 🔹 Step 1: Fetch user details from DB
$query = $conn->prepare("SELECT * FROM loginusers WHERE email = ?");
$query->bind_param("s", $email);
$query->execute();
$result = $query->get_result();
$user = $result->fetch_assoc();

if (!$user) {
    echo json_encode(["success" => false, "message" => "User not found"]);
    exit;
}

// 🔹 Step 2: Fetch MT5 login (trade_id) from liveaccounts table
$liveQuery = $conn->prepare("SELECT * FROM liveaccounts WHERE email = ?");
$liveQuery->bind_param("s", $email);
$liveQuery->execute();
$liveResult = $liveQuery->get_result();
$liveAccount = $liveResult->fetch_assoc();

if (!$liveAccount || empty($liveAccount["trade_id"])) {
    echo json_encode(["success" => false, "message" => "MT5 Account not found for user"]);
    exit;
}

$mt5_login = (int)$liveAccount["trade_id"];

// 🔹 Step 3: Connect to MetaTrader 5 using connection.php
$mt5Conn = new MT5Connection();

if (!$mt5Conn->connect()) {
    echo json_encode([
        "success" => false,
        "message" => "MT5 connection failed",
        "error_code" => $mt5Conn->lastError()
    ]);
    exit;
}

$api = $mt5Conn->api;

// 🔹 Step 4: Fetch Open Trades (Positions)
$openTrades = [];
$total_positions = 0;
$pos_result = $api->PositionGetTotal($mt5_login, $total_positions);

if ($pos_result == MTRetCode::MT_RET_OK && $total_positions > 0) {
    $positions = [];
    $api->PositionGetPage($mt5_login, 0, $total_positions, $positions);
    foreach ($positions as $pos) {
        $openTrades[] = [
            "ticket" => isset($pos->Ticket) ? $pos->Ticket : (isset($pos->PositionID) ? $pos->PositionID : null),
            "symbol" => $pos->Symbol ?? null,
            "volume" => $pos->Volume ?? null,
            "open_price" => $pos->PriceOpen ?? null,
            "profit" => $pos->Profit ?? null,
            "type" => $pos->Action ?? null,
            "time" => isset($pos->TimeCreate) ? date("Y-m-d H:i:s", $pos->TimeCreate) : null
        ];
    }
}

// 🔹 Step 5: Fetch Closed Trades (Deals)
$closedTrades = [];
$total_deals = 0;
$from = strtotime("-30 days");
$to = time();

$deal_result = $api->DealGetTotal($mt5_login, $from, $to, $total_deals);

if ($deal_result == MTRetCode::MT_RET_OK && $total_deals > 0) {
    $deals = [];
    $api->DealGetPage($mt5_login, $from, $to, 0, $total_deals, $deals);
    foreach ($deals as $deal) {
        $closedTrades[] = [
            "ticket" => $deal->Ticket ?? ($deal->Deal ?? null),
            "symbol" => $deal->Symbol ?? null,
            "volume" => $deal->Volume ?? null,
            "price" => $deal->Price ?? null,
            "profit" => $deal->Profit ?? null,
            "type" => $deal->Action ?? null,
            "time" => isset($deal->Time) ? date("Y-m-d H:i:s", $deal->Time) : null
        ];
    }
}

// 🔹 Step 6: Disconnect MT5
$api->Disconnect();

// 🔹 Step 7: Fetch Deposits
$depositQuery = $conn->prepare("SELECT id, trade_id, deposit_amount, deposit_type, company_bank, client_bank, account_number, deposed_date, Status, btc_amount, utr_number, ifsc 
                                FROM wallet_deposit WHERE email = ? ORDER BY id DESC");
$depositQuery->bind_param("s", $email);
$depositQuery->execute();
$depositResult = $depositQuery->get_result();
$deposits = [];
while ($row = $depositResult->fetch_assoc()) {
    $deposits[] = $row;
}

// 🔹 Step 8: Fetch Withdrawals
$withdrawQuery = $conn->prepare("SELECT id, trade_id, withdraw_amount, withdraw_type, company_bank, client_bank, account_holder_name, account_number, withdraw_date, Status, transaction_id 
                                 FROM wallet_withdraw WHERE email = ? ORDER BY id DESC");
$withdrawQuery->bind_param("s", $email);
$withdrawQuery->execute();
$withdrawResult = $withdrawQuery->get_result();
$withdrawals = [];
while ($row = $withdrawResult->fetch_assoc()) {
    $withdrawals[] = $row;
}

// 🔹 Step 9: Return final response
$response = [
    "success" => true,
    "message" => "User details, trades, deposits, and withdrawals fetched successfully",
    "user_details" => $user,
    "live_account" => $liveAccount,
    "mt5_login" => $mt5_login,
    "open_trades" => $openTrades,
    "closed_trades" => $closedTrades,
    "deposits" => $deposits,
    "withdrawals" => $withdrawals
];

echo json_encode($response, JSON_PRETTY_PRINT);
?>
