<?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 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;
}

// --- Fetch recent deposits ---
if ((isset($_GET['action']) && $_GET['action']==='recent') || ($data['action'] ?? '')==='recent') {
    $deposits = [];
    $stmt = $conn->prepare("SELECT email, account_name, account_type, deposit, bonusDeposit, Registered_Date FROM liveaccounts ORDER BY Registered_Date DESC LIMIT 5");
    $stmt->execute();
    $result = $stmt->get_result();
    while($row = $result->fetch_assoc()) {
        $deposits[] = [
            "email"=>$row['email'],
            "amount"=>$row['deposit'],
            "bonus"=>$row['bonusDeposit'],
            "account_name"=>$row['account_name'],
            "account_type"=>$row['account_type'],
            "created_at"=>$row['Registered_Date']
        ];
    }
    echo json_encode(["success"=>true,"deposits"=>$deposits]);
    exit;
}

// --- Normal deposit ---
$trade_id = $data['trade_id'] ?? 0;
$amount = floatval($data['amount'] ?? 0);
$type = $data['type'] ?? 'balance';
$comment = $data['comment'] ?? 'Deposit via UI';

if(!$trade_id || $amount <=0 || !in_array($type,['balance','bonus'])) {
    echo json_encode(["success"=>false,"error"=>"Invalid parameters"]);
    exit;
}

// Get account by trade_id
$stmt = $conn->prepare("SELECT id, email, account_name, account_type, trader_pwd, invester_pwd, phone_pwd, trade_id, deposit, bonusDeposit FROM liveaccounts WHERE trade_id=? LIMIT 1");
$stmt->bind_param("i", $trade_id);
$stmt->execute();
$userRow = $stmt->get_result()->fetch_assoc();
if(!$userRow){
    echo json_encode(["success"=>false,"error"=>"User not found"]);
    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;
}

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

$ticket = 0;
$dealType = ($type==='bonus') ? MTEnDealAction::DEAL_BONUS : MTEnDealAction::DEAL_BALANCE;
$ret = $api->TradeBalance($userMT5->Login, $dealType, $amount, $comment, $ticket);

if($ret == MTRetCode::MT_RET_OK){
    if($type==='balance'){
        $stmtUpdate = $conn->prepare("UPDATE liveaccounts SET deposit=deposit+?, usercp=? WHERE id=?");
    } else {
        $stmtUpdate = $conn->prepare("UPDATE liveaccounts SET bonusDeposit=bonusDeposit+?, usercp=? WHERE id=?");
    }
    $stmtUpdate->bind_param("dsi", $amount, $comment, $userRow['id']);
    $stmtUpdate->execute();

    echo json_encode(["success"=>true,"ticket"=>$ticket, "login"=>$userMT5->Login]);
}else{
    echo json_encode(["success"=>false,"error"=>"MT5 deposit failed: $ret"]);
}

$api->Disconnect();
?>
