<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

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

$input = json_decode(file_get_contents('php://input'), true);
if (!is_array($input)) {
    echo json_encode(["success"=>false,"message"=>"Invalid JSON body"]);
    exit;
}

$userId = isset($input['user_id']) ? intval($input['user_id']) : 0;
$email = isset($input['email']) ? trim($input['email']) : '';

if (!$userId && !$email) {
    echo json_encode(["success"=>false,"message"=>"Provide user_id or email"]);
    exit;
}

if (!$userId) {
    $stmt = $conn->prepare("SELECT id,email FROM loginusers WHERE email = ? LIMIT 1");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    if (!$row) {
        echo json_encode(["success"=>false,"message"=>"User not found"]);
        exit;
    }
    $userId = intval($row['id']);
    $email = $row['email'];
    $stmt->close();
} else if ($userId && !$email) {
    $stmt = $conn->prepare("SELECT email FROM loginusers WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    $email = $row ? ($row['email'] ?? '') : '';
    $stmt->close();
}

$tradeIds = [];
$stmt = $conn->prepare("SELECT trade_id FROM liveaccounts WHERE user_id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$result = $stmt->get_result();
while ($r = $result->fetch_assoc()) {
    $tid = (string)($r['trade_id'] ?? '');
    if ($tid !== '') $tradeIds[] = $tid;
}
$stmt->close();

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


$mt5Results = [];
foreach ($tradeIds as $login) {
    $loginNum = intval($login);

    // Check for open positions
    $totalPositions = 0;
    $api->PositionGetTotal($loginNum, $totalPositions);

    // Check for open orders
    $totalOrders = 0;
    $api->OrderGetTotal($loginNum, $totalOrders);

    if ($totalPositions > 0 || $totalOrders > 0) {
        // Cannot delete, still has open positions/orders
        $mt5Results[] = [
            "trade_id" => $login,
            "deleted" => false,
            "ret" => "Has open positions/orders"
        ];
        continue;
    }

    // Try deleting account
    $ret = $api->UserDelete($loginNum);
    $mt5Results[] = [
        "trade_id" => $login,
        "deleted" => ($ret === MTRetCode::MT_RET_OK),
        "ret" => $ret
    ];
}


$deleted = [
    "account_profits"=>0,
    "deposit_requests"=>0,
    "withdrawal_requests"=>0,
    "wallet_deposit"=>0,
    "wallet_withdraw"=>0,
    "internal_transfers"=>0,
    "deposits"=>0,
    "ib_withdraw"=>0,
    "ib_withdraw_request"=>0,
    "kycupload"=>0,
    "liveaccounts"=>0,
    "loginusers"=>0
];

$conn->begin_transaction();

foreach ($tradeIds as $tid) {
    $stmt = $conn->prepare("DELETE FROM account_profits WHERE trade_id = ?");
    $stmt->bind_param("s", $tid);
    $stmt->execute();
    $deleted["account_profits"] += $stmt->affected_rows;
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM deposit_requests WHERE trade_id = ?");
    $stmt->bind_param("s", $tid);
    $stmt->execute();
    $deleted["deposit_requests"] += $stmt->affected_rows;
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM withdrawal_requests WHERE trade_id = ?");
    $stmt->bind_param("s", $tid);
    $stmt->execute();
    $deleted["withdrawal_requests"] += $stmt->affected_rows;
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM wallet_deposit WHERE trade_id = ?");
    $stmt->bind_param("s", $tid);
    $stmt->execute();
    $deleted["wallet_deposit"] += $stmt->affected_rows;
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM wallet_withdraw WHERE trade_id = ?");
    $stmt->bind_param("s", $tid);
    $stmt->execute();
    $deleted["wallet_withdraw"] += $stmt->affected_rows;
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM internal_transfers WHERE from_trade = ? OR to_trade = ?");
    $stmt->bind_param("ss", $tid, $tid);
    $stmt->execute();
    $deleted["internal_transfers"] += $stmt->affected_rows;
    $stmt->close();

    $loginNum = intval($tid);
    $stmt = $conn->prepare("DELETE FROM deposits WHERE login = ?");
    $stmt->bind_param("i", $loginNum);
    $stmt->execute();
    $deleted["deposits"] += $stmt->affected_rows;
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM ib_withdraw WHERE trade_id = ?");
    $stmt->bind_param("s", $tid);
    $stmt->execute();
    $deleted["ib_withdraw"] += $stmt->affected_rows;
    $stmt->close();

    $like = "%".$tid."%";
    $stmt = $conn->prepare("DELETE FROM ib_withdraw_request WHERE trade_ids LIKE ?");
    $stmt->bind_param("s", $like);
    $stmt->execute();
    $deleted["ib_withdraw_request"] += $stmt->affected_rows;
    $stmt->close();
}

$stmt = $conn->prepare("DELETE FROM deposit_requests WHERE user_id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$deleted["deposit_requests"] += $stmt->affected_rows;
$stmt->close();

$stmt = $conn->prepare("DELETE FROM withdrawal_requests WHERE user_id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$deleted["withdrawal_requests"] += $stmt->affected_rows;
$stmt->close();

if ($email !== '') {
    $stmt = $conn->prepare("DELETE FROM wallet_deposit WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $deleted["wallet_deposit"] += $stmt->affected_rows;
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM wallet_withdraw WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $deleted["wallet_withdraw"] += $stmt->affected_rows;
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM deposits WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $deleted["deposits"] += $stmt->affected_rows;
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM ib_withdraw WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $deleted["ib_withdraw"] += $stmt->affected_rows;
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM ib_withdraw_request WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $deleted["ib_withdraw_request"] += $stmt->affected_rows;
    $stmt->close();

    $stmt = $conn->prepare("DELETE FROM kycupload WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $deleted["kycupload"] += $stmt->affected_rows;
    $stmt->close();
}

$stmt = $conn->prepare("DELETE FROM kycupload WHERE user_id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$deleted["kycupload"] += $stmt->affected_rows;
$stmt->close();

$stmt = $conn->prepare("DELETE FROM internal_transfers WHERE user_id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$deleted["internal_transfers"] += $stmt->affected_rows;
$stmt->close();

$stmt = $conn->prepare("DELETE FROM liveaccounts WHERE user_id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$deleted["liveaccounts"] += $stmt->affected_rows;
$stmt->close();

$stmt = $conn->prepare("DELETE FROM loginusers WHERE id = ?");
$stmt->bind_param("i", $userId);
$stmt->execute();
$deleted["loginusers"] += $stmt->affected_rows;
$stmt->close();

$conn->commit();

echo json_encode([
    "success"=>true,
    "user_id"=>$userId,
    "email"=>$email,
    "trade_ids"=>$tradeIds,
    "mt5"=>$mt5Results,
    "deleted"=>$deleted
]);
?>
