<?php
// Enable full 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);

// -------------------------
// 1️⃣ Fetch user accounts with MT5 balance
// -------------------------
if (isset($data['action']) && $data['action'] === 'fetch_accounts') {
    $accounts = [];
    $user_id = $data['user_id'] ?? 0;

    // $stmt = $conn->prepare("SELECT id, trade_id, email, account_name, account_type FROM liveaccounts WHERE user_id=?");
    // 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%'
");

    $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()) {
        $user = new MTUser();
        if ($api->UserGet(intval($row['trade_id']), $user) == MTRetCode::MT_RET_OK) {
            $row['deposit'] = $user->Balance; // Real MT5 balance
        } else {
            $row['deposit'] = 0;
        }

        // Update DB deposit
        $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;
}

// -------------------------
// 2️⃣ Transfer funds
// -------------------------
$fromTrade = $data['fromTrade'] ?? '';
$toTrade   = $data['toTrade'] ?? '';
$amount    = floatval($data['amount'] ?? 0);

if (!$fromTrade || !$toTrade || $fromTrade === $toTrade || $amount <= 0) {
    echo json_encode(["success" => false, "error" => "Invalid parameters"]);
    exit;
}

// Get both accounts
$stmt = $conn->prepare("SELECT id, user_id, trade_id, account_name, account_type, deposit FROM liveaccounts WHERE trade_id=? OR trade_id=?");
$stmt->bind_param("ss", $fromTrade, $toTrade);
$stmt->execute();
$accountsRes = $stmt->get_result();

$fromAccount = $toAccount = null;
while ($row = $accountsRes->fetch_assoc()) {
    if ($row['trade_id'] === $fromTrade) $fromAccount = $row;
    if ($row['trade_id'] === $toTrade) $toAccount = $row;
}

if (!$fromAccount || !$toAccount) {
    echo json_encode(["success" => false, "error" => "Accounts not found"]);
    exit;
}

// 🚫 BLOCK TRANSFERS FOR DEMO ACCOUNTS
$demoKeywords = ['demo', 'Demo', 'DEMO'];

foreach ($demoKeywords as $dk) {
    if (stripos($fromAccount['account_type'], $dk) !== false ||
        stripos($toAccount['account_type'], $dk) !== false) {

        echo json_encode([
            "success" => false,
            "error" => "Transfers are not allowed from or to Demo accounts"
        ]);
        exit;
    }
}
// // 🚫 BLOCK TRANSFERS FOR CENT ACCOUNTS
// $centKeywords = ['cent', 'Cent', 'CENT'];

// foreach ($centKeywords as $ck) {
//     if (stripos($fromAccount['account_type'], $ck) !== false ||
//         stripos($toAccount['account_type'], $ck) !== false) {

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

// Fetch MT5 balance for source
$userFrom = new MTUser();
$api->UserGet(intval($fromAccount['trade_id']), $userFrom);

if ($userFrom->Balance < $amount) {
    echo json_encode(["success" => false, "error" => "Insufficient balance in source account"]);
    exit;
}

// ✔️ Currency Conversion Logic Between CENT and NORMAL
$isFromCent = stripos($fromAccount['account_type'], 'cent') !== false;
$isToCent   = stripos($toAccount['account_type'], 'cent') !== false;

// Default — no conversion
$transferAmount = $amount;

// CENT ➜ NORMAL (Divide by 100)
if ($isFromCent && !$isToCent) {
    $transferAmount = $amount / 100;
}

// NORMAL ➜ CENT (Multiply by 100)
if (!$isFromCent && $isToCent) {
    $transferAmount = $amount * 100;
}

// MT5 transfer
$ticketFrom = 0;
// $ret1 = $api->TradeBalance($userFrom->Login, MTEnDealAction::DEAL_BALANCE, -$amount, "Transfer to " . $toAccount['trade_id'], $ticketFrom);
$ret1 = $api->TradeBalance(
    $userFrom->Login,
    MTEnDealAction::DEAL_BALANCE,
    -$amount, // Deduct original amount from source
    "Transfer to " . $toAccount['trade_id'],
    $ticketFrom
);

$userTo = new MTUser();
$api->UserGet(intval($toAccount['trade_id']), $userTo);
$ticketTo = 0;
// $ret2 = $api->TradeBalance($userTo->Login, MTEnDealAction::DEAL_BALANCE, $amount, "Transfer from " . $fromAccount['trade_id'], $ticketTo);
$ret2 = $api->TradeBalance(
    $userTo->Login,
    MTEnDealAction::DEAL_BALANCE,
    $transferAmount, // Add converted amount to destination
    "Transfer from " . $fromAccount['trade_id'],
    $ticketTo
);

if ($ret1 == MTRetCode::MT_RET_OK && $ret2 == MTRetCode::MT_RET_OK) {

    // RE-FETCH UPDATED BALANCES FROM MT5
    $api->UserGet(intval($fromAccount['trade_id']), $userFrom);
    $api->UserGet(intval($toAccount['trade_id']), $userTo);

    // -------------------------
    // Update DB deposits
    // -------------------------
    $newDepositFrom = $userFrom->Balance;
    $stmtUpdate = $conn->prepare("UPDATE liveaccounts SET deposit=? WHERE id=?");
    $stmtUpdate->bind_param("di", $newDepositFrom, $fromAccount['id']);
    $stmtUpdate->execute();

    $newDepositTo = $userTo->Balance;
    $stmtUpdate2 = $conn->prepare("UPDATE liveaccounts SET deposit=? WHERE id=?");
    $stmtUpdate2->bind_param("di", $newDepositTo, $toAccount['id']);
    $stmtUpdate2->execute();

    // -------------------------
    // Insert into internal_transfers
    // -------------------------
    $stmtLog = $conn->prepare("
        INSERT INTO internal_transfers 
        (user_id, from_trade, to_trade, amount, ticket_from, ticket_to, notes, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $user_id = $fromAccount['user_id'];
    $notes = "Transfer from $fromTrade to $toTrade";
    $status = "approved";

    $ticketFromInt = intval($ticketFrom);
    $ticketToInt   = intval($ticketTo);

    $stmtLog->bind_param(
        "issdiiss",
        $user_id,
        $fromTrade,
        $toTrade,
        $amount,
        $ticketFromInt,
        $ticketToInt,
        $notes,
        $status
    );

    $stmtLog->execute();

    echo json_encode([
        "success" => true,
        "message" => "Transfer successful",
        "transfer_id" => $conn->insert_id
    ]);
}

else {
    echo json_encode(["success" => false, "error" => "MT5 transfer failed"]);
}

$api->Disconnect();
?>
