<?php
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if ($origin === 'http://localhost:3000') {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
} else {
    header("Access-Control-Allow-Origin: *");
}

header('Content-Type: application/json');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header('Access-Control-Max-Age: 1728000');

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

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);

// Debug received data
error_log("Received request: " . print_r($data, true));

// ✅ Fetch pending deposits
if(isset($data['action']) && $data['action'] === 'fetch_pending_deposits') {
    $deposits = [];

    $query = "
    SELECT dr.*, 
           l.trade_id, 
           l.account_name, 
           l.account_type, 
           COALESCE(lu.first_name, 'Unknown') as first_name, 
           COALESCE(lu.last_name, 'User') as last_name,
           lu.email  
    FROM deposit_requests dr
    LEFT JOIN liveaccounts l ON l.trade_id = dr.trade_id
    LEFT JOIN loginusers lu ON lu.id = l.user_id
    ORDER BY dr.created_at DESC
    ";

    if (!$stmt = $conn->prepare($query)) {
        echo json_encode(["success" => false, "error" => "Prepare failed: " . $conn->error]);
        exit;
    }

    if (!$stmt->execute()) {
        echo json_encode(["success" => false, "error" => "Execute failed: " . $stmt->error]);
        exit;
    }

    $result = $stmt->get_result();
    while($row = $result->fetch_assoc()) {
        $deposits[] = $row;
    }

    echo json_encode(["success" => true, "deposits" => $deposits]);
    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 deposit_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 request"]);
        exit;
    }

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

        if(!$userRow){
            echo json_encode(["success"=>false,"error"=>"User not found in liveaccounts"]);
            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($userRow['trade_id']), $userMT5);
        if($ret != MTRetCode::MT_RET_OK){
            $api->Disconnect();
            echo json_encode(["success"=>false,"error"=>"User not found in MT5"]);
            exit;
        }

        // --- Deposit into MT5 ---
        $ticket = 0;
        $dealType = ($request['type']==='bonus') ? MTEnDealAction::DEAL_BONUS : MTEnDealAction::DEAL_BALANCE;
        $ret = $api->TradeBalance($userMT5->Login, $dealType, floatval($request['amount']), "Deposit approved", $ticket);

        if($ret == MTRetCode::MT_RET_OK){
            // --- Update DB only if MT5 succeeded ---
            if($request['type'] === 'balance'){
                $stmt = $conn->prepare("UPDATE liveaccounts SET deposit = deposit + ? WHERE trade_id = ?");
            } else {
                $stmt = $conn->prepare("UPDATE liveaccounts SET bonusDeposit = bonusDeposit + ? WHERE trade_id = ?");
            }
            $stmt->bind_param("ds", $request['amount'], $request['trade_id']);
            if(!$stmt->execute()) {
                echo json_encode(["success"=>false, "error"=>"Failed to update balance"]);
                $api->Disconnect();
                exit;
            }
        } else {
            $api->Disconnect();
            echo json_encode(["success"=>false,"error"=>"MT5 deposit failed: $ret"]);
            exit;
        }

        $api->Disconnect();
    }

    // Update request status
    $status = $data['action'] === 'approve' ? 'approved' : 'rejected';
    $stmt = $conn->prepare("UPDATE deposit_requests SET status = ?, admin_comment = ? WHERE id = ?");
    $stmt->bind_param("ssi", $status, $admin_comment, $request_id);

    if($stmt->execute()) {
        echo json_encode(["success"=>true, "message"=>"Deposit request {$status} successfully"]);
    } else {
        echo json_encode(["success"=>false, "error"=>"Failed to update request"]);
    }
    exit;
}

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