<?php
header('Content-Type: application/json');

// CORS headers
header("Access-Control-Allow-Origin: http://localhost:3000"); // allow your React app
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Max-Age: 1728000');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header("HTTP/1.1 200 OK");
    exit(0);
}

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

$input = file_get_contents("php://input");
$data = json_decode($input, true);

// ✅ Fetch all withdrawals
if(isset($data['action']) && $data['action'] === 'fetch_pending_withdrawals') {
    $withdrawals = [];

    $query = "
        SELECT wr.*, 
               COALESCE(l.email, lu.email, 'N/A') as email,
               COALESCE(l.account_name, '') as account_name, 
               COALESCE(l.account_type, '') as account_type, 
               COALESCE(lu.first_name, '') as first_name, 
               COALESCE(lu.last_name, '') as last_name
        FROM withdrawal_requests wr
        LEFT JOIN liveaccounts l ON l.trade_id = wr.trade_id
        LEFT JOIN loginusers lu ON lu.id = l.user_id
        ORDER BY wr.created_at DESC
    ";

    $result = $conn->query($query);
    if($result) {
        while($row = $result->fetch_assoc()) {
            $withdrawals[] = $row;
        }
        echo json_encode(["success" => true, "withdrawals" => $withdrawals]);
    } else {
        echo json_encode(["success" => false, "error" => $conn->error]);
    }
    exit;
}

// ✅ Handle approve/reject
if(isset($data['action']) && ($data['action'] === 'approve' || $data['action'] === 'reject')) {
    $request_id = $data['request_id'] ?? 0;
    $admin_comment = $data['admin_comment'] ?? '';

    // Get request details
    $stmt = $conn->prepare("SELECT * FROM withdrawal_requests WHERE id = ? AND status='pending'");
    $stmt->bind_param("i", $request_id);
    $stmt->execute();
    $request = $stmt->get_result()->fetch_assoc();

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

    $trade_id = $request['trade_id'];
    $withdraw_amount = floatval($request['amount']);
    $type = $request['type'];

    if($data['action'] === 'approve') {
        // --- Fetch user account from liveaccounts ---
        $stmt = $conn->prepare("SELECT * FROM liveaccounts WHERE trade_id = ? LIMIT 1");
        $stmt->bind_param("s", $trade_id);
        $stmt->execute();
        $account = $stmt->get_result()->fetch_assoc();

        if(!$account) {
            echo json_encode(["success"=>false, "error"=>"Live account not found"]);
            exit;
        }

        $available = ($type === 'bonus') ? floatval($account['bonusDeposit']) : floatval($account['deposit']);
        if($withdraw_amount > $available) {
            echo json_encode(["success"=>false, "error"=>"Insufficient balance"]);
            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 user ---
        $userMT5 = new MTUser();
        $ret = $api->UserGet(intval($account['trade_id']), $userMT5);
        if($ret != MTRetCode::MT_RET_OK){
            $api->Disconnect();
            echo json_encode(["success"=>false,"error"=>"User not found in MT5"]);
            exit;
        }

        // --- Perform withdrawal in MT5 (negative amount) ---
        $ticket = 0;
        $dealType = ($type==='bonus') ? MTEnDealAction::DEAL_BONUS : MTEnDealAction::DEAL_BALANCE;
        $ret = $api->TradeBalance($userMT5->Login, $dealType, -$withdraw_amount, "Withdrawal approved", $ticket);

        if($ret == MTRetCode::MT_RET_OK){
            // --- Update DB only if MT5 succeeded ---
            if($type === 'bonus'){
                $stmtUpdate = $conn->prepare("UPDATE liveaccounts SET bonusDeposit = bonusDeposit - ? WHERE trade_id = ?");
            } else {
                $stmtUpdate = $conn->prepare("UPDATE liveaccounts SET deposit = deposit - ? WHERE trade_id = ?");
            }
            $stmtUpdate->bind_param("ds", $withdraw_amount, $trade_id);
            $stmtUpdate->execute();
            $status = 'approved';
        } else {
            $api->Disconnect();
            echo json_encode(["success"=>false,"error"=>"MT5 withdrawal failed: $ret"]);
            exit;
        }

        $api->Disconnect();
    } else {
        $status = 'rejected';
    }

    // --- Update withdrawal request status ---
    $stmt = $conn->prepare("UPDATE withdrawal_requests SET status = ?, admin_comment = ? WHERE id = ?");
    $stmt->bind_param("ssi", $status, $admin_comment, $request_id);
    $stmt->execute();

    // Return updated request
    $stmt = $conn->prepare("
        SELECT wr.*, COALESCE(l.email, lu.email, 'N/A') as email
        FROM withdrawal_requests wr
        LEFT JOIN liveaccounts l ON l.trade_id = wr.trade_id
        LEFT JOIN loginusers lu ON lu.id = l.user_id
        WHERE wr.id = ?
    ");
    $stmt->bind_param("i", $request_id);
    $stmt->execute();
    $updatedRequest = $stmt->get_result()->fetch_assoc();

    echo json_encode([
        "success" => true,
        "message" => "Withdrawal request {$status} successfully",
        "withdrawal" => $updatedRequest
    ]);
    exit;
}

echo json_encode(["success"=>false, "error"=>"Invalid action"]);
