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

// Allow CORS
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

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

// Get POSTed JSON
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data || !isset($data['login'], $data['amount'])) {
    echo json_encode([
        'success' => false,
        'error' => 'Login and amount are required',
        'raw' => $input
    ]);
    exit;
}

// Include MT5 connection
include_once __DIR__ . '/connection.php';

class AddBalance {
    private $mt5;

    public function __construct() {
        $this->mt5 = new MTWebAPI();
        $ret = $this->mt5->Connect(
            MT5_SERVER_IP,
            MT5_SERVER_PORT,
            MT5_TIMEOUT,
            MT5_SERVER_WEB_LOGIN,
            MT5_SERVER_WEB_PASSWORD
        );

        if ($ret !== MTRetCode::MT_RET_OK) {
            echo json_encode([
                'success' => false,
                'error' => '❌ Failed to connect to MT5',
                'details' => $ret
            ]);
            exit;
        }
    }

    public function deposit($login, $amount, $comment = "Deposit via UI") {
        // Fetch user to ensure it exists
        $user = null;
        $ret = $this->mt5->UserGet($login, $user);
        if ($ret !== MTRetCode::MT_RET_OK) {
            return [
                'success' => false,
                'error' => "❌ User not found",
                'details' => $ret
            ];
        }

        $ticket = null;
        $type = MTEnDealAction::DEAL_BALANCE;
        $ret = $this->mt5->TradeBalance($login, $type, (float)$amount, $comment, $ticket);

        if ($ret === MTRetCode::MT_RET_OK) {
            return [
                'success' => true,
                'login' => $login,
                'amount_added' => $amount,
                'ticket' => $ticket
            ];
        } else {
            return [
                'success' => false,
                'error' => "❌ Failed to add balance",
                'details' => $ret
            ];
        }
    }
}

// Run
$balance = new AddBalance();
$result = $balance->deposit($data['login'], $data['amount'], $data['comment'] ?? "Deposit via UI");
echo json_encode($result);
