<?php
ob_start();
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    ob_end_flush();
    exit;
}

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

// Read input: prefer JSON, fallback to $_POST
$raw = file_get_contents("php://input");
$data = json_decode($raw, true);
if (!is_array($data)) {
    $data = $_POST ?? [];
}

$user_id = $data['user_id'] ?? 0;

// fetch only accounts for this user
function fetch_accounts_list($conn, $user_id) {
    $accounts = [];
    $sql = "SELECT id, email, trade_id, account_name, account_type, deposit, bonusDeposit 
            FROM liveaccounts WHERE user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $row['deposit'] = floatval($row['deposit']);
        $row['bonusDeposit'] = floatval($row['bonusDeposit']);
        $accounts[] = $row;
    }
    $stmt->close();
    return $accounts;
}

// if frontend requests accounts
if (isset($data['action']) && $data['action'] === 'fetch_accounts') {
    $accounts = fetch_accounts_list($conn, $user_id);
    echo json_encode([
        "success" => true,
        "accounts" => $accounts
    ]);
    exit;
}


// optional recent withdrawals endpoint
if ((isset($_GET['action']) && $_GET['action'] === 'recent') || (isset($data['action']) && $data['action'] === 'recent')) {
    $recentWithdrawals = [];
    $recentStmt = $conn->prepare("
        SELECT email, account_name, account_type, withdraw, bonusWithdraw, Registered_Date 
        FROM liveaccounts 
        WHERE withdraw > 0 OR bonusWithdraw > 0
        ORDER BY Registered_Date DESC
        LIMIT 5
    ");
    if ($recentStmt) {
        $recentStmt->execute();
        $recentResult = $recentStmt->get_result();
        while ($row = $recentResult->fetch_assoc()) {
            $recentWithdrawals[] = [
                "email" => $row['email'],
                "amount" => floatval($row['withdraw']),
                "bonus" => floatval($row['bonusWithdraw']),
                "account_name" => $row['account_name'],
                "account_type" => $row['account_type'],
                "created_at" => $row['Registered_Date']
            ];
        }
    }
    echo json_encode([
        "success" => true,
        "withdrawals" => $recentWithdrawals
    ]);
    exit;
}

// --- Normal withdrawal flow ---
if (!isset($data['action']) || $data['action'] !== 'withdraw') {
    echo json_encode(["success" => false, "error" => "Invalid action"]);
    exit;
}

$trade_id = trim($data['trade_id'] ?? '');
$amount   = floatval($data['amount'] ?? 0);
$type     = ($data['type'] ?? 'balance');
$comment  = $data['comment'] ?? 'Withdrawal via UI';

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

// Fetch user details by trade_id
$stmt = $conn->prepare("SELECT id, trade_id, deposit, bonusDeposit FROM liveaccounts WHERE trade_id=? LIMIT 1");
$stmt->bind_param("s", $trade_id);

if (!$stmt) {
    error_log("Prepare failed: " . $conn->error);
    echo json_encode(["success" => false, "error" => "Server error"]);
    exit;
}
$stmt->execute();
$userResult = $stmt->get_result();
$userRow = $userResult->fetch_assoc();
$stmt->close();

if (!$userRow) {
    echo json_encode(["success" => false, "error" => "User 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) {
    error_log("MT5 connect failed code: $ret");
    echo json_encode(["success" => false, "error" => "MT5 connection failed"]);
    exit;
}

// Get MT5 user (by numeric login)
$userLoginInt = intval($userRow['trade_id']);
$userMT5 = new MTUser();
$ret = $api->UserGet($userLoginInt, $userMT5);
if ($ret != MTRetCode::MT_RET_OK) {
    $api->Disconnect();
    error_log("MT5 UserGet failed for login $userLoginInt, code: $ret");
    echo json_encode(["success" => false, "error" => "User not found in MT5"]);
    exit;
}

// Check available balance/bonus (use MT5 fields)
$available = ($type === 'bonus') ? floatval($userMT5->Bonus ?? 0) : floatval($userMT5->Balance ?? 0);
if ($amount > $available) {
    $api->Disconnect();
    echo json_encode(["success" => false, "error" => "Insufficient balance"]);
    exit;
}

// Perform withdrawal (negative adjustment)
// NOTE: depending on your mt5_api signature, $ticket may be returned by reference
$ticket = 0;
$dealType = ($type === "bonus") ? MTEnDealAction::DEAL_BONUS : MTEnDealAction::DEAL_BALANCE;

$ret = $api->TradeBalance($userMT5->Login, $dealType, -$amount, $comment, $ticket);
// If your API uses a different signature (e.g. returns array or object), adjust above accordingly.

if ($ret == MTRetCode::MT_RET_OK) {
    // Update DB properly
    $userId = intval($userRow['id']);
    if ($type === "balance") {
        $stmtUpdate = $conn->prepare("
            UPDATE liveaccounts 
            SET deposit = deposit - ?, withdraw = withdraw + ?, Registered_Date = NOW() 
            WHERE id = ?
        ");
    } else {
        $stmtUpdate = $conn->prepare("
            UPDATE liveaccounts 
            SET bonusDeposit = bonusDeposit - ?, bonusWithdraw = bonusWithdraw + ?, Registered_Date = NOW() 
            WHERE id = ?
        ");
    }

    if (!$stmtUpdate) {
        error_log("Update prepare failed: " . $conn->error);
        $api->Disconnect();
        echo json_encode(["success" => false, "error" => "DB prepare failed"]);
        exit;
    }

    // bind as double, double, int
    $stmtUpdate->bind_param("ddi", $amount, $amount, $userId);

    if ($stmtUpdate->execute()) {
        $stmtUpdate->close();

        // Return refreshed accounts so frontend can update UI immediately
        $accounts = fetch_accounts_list($conn, $userId);


        $api->Disconnect();
        echo json_encode([
            "success" => true,
            "ticket"  => $ticket,
            "login"   => $userMT5->Login,
            "accounts" => $accounts
        ]);
        exit;
    } else {
        error_log("DB update failed: " . $stmtUpdate->error);
        $stmtUpdate->close();
        $api->Disconnect();
        echo json_encode(["success" => false, "error" => "DB update failed"]);
        exit;
    }
} else {
    error_log("MT5 TradeBalance failed for login {$userMT5->Login}, code: $ret");
    $api->Disconnect();
    echo json_encode(["success" => false, "error" => "MT5 withdrawal failed"]);
    exit;
}
