<?php
// Enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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 ACCOUNTS FOR WITHDRAW
// ----------------------------
if (isset($data['action']) && $data['action'] === 'fetch_accounts_withdraw') {

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

    if (!$user_id) {
        echo json_encode(["success" => false, "error" => "Invalid user_id"]);
        exit;
    }

    // Fetch accounts EXCLUDING DEMO
    $stmt = $conn->prepare("
        SELECT id, trade_id, email, account_name, account_type 
        FROM liveaccounts 
        WHERE user_id = ? 
          AND account_type != 'Demo'
          AND account_type != 6
          AND account_type NOT LIKE '%demo%'
        ORDER BY id DESC
    ");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    // 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) {
        echo json_encode(["success" => false, "error" => "MT5 connection failed"]);
        exit;
    }

    while ($row = $result->fetch_assoc()) {

        $trade_id = intval($row['trade_id']);

        // Fetch MTUser (not strictly needed here but can keep for validation)
        $user = new MTUser();
        $api->UserGet($trade_id, $user);

        // Fetch MTAccount for Equity
        $account = null;
        if ($api->UserAccountGet($trade_id, $account) == MTRetCode::MT_RET_OK) {
            $row['deposit'] = $account->Equity; // use Equity as deposit
        } else {
            $row['deposit'] = 0;
        }

        // Update DB deposit with MT5 equity
        $stmtUpdate = $conn->prepare("UPDATE liveaccounts SET deposit=? WHERE id=?");
        $depositVal = $row['deposit'];
        $stmtUpdate->bind_param("di", $depositVal, $row['id']);
        $stmtUpdate->execute();

        $accounts[] = $row;
    }

    $api->Disconnect();

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

echo json_encode(["success" => false, "error" => "Invalid request"]);
exit;
?>
