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

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

// Handle 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 || !is_array($data)) {
    echo json_encode([
        'success' => false,
        'error'   => 'Invalid input data',
        'raw'     => $input
    ]);
    exit;
}

include_once __DIR__ . '/connection.php'; // reuse MT5 connection class

class AddBonus {
    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 addBonus($data) {
        $login  = (int)($data['login'] ?? 0);
        $amount = (float)($data['amount'] ?? 0);
        $comment = $data['comment'] ?? 'Bonus via UI';

        if (!$login || $amount <= 0) {
            return [
                'success' => false,
                'error'   => 'Invalid login or amount'
            ];
        }

        // Fetch user first
        $user = null;
        $ret = $this->mt5->UserGet($login, $user);
        if ($ret !== MTRetCode::MT_RET_OK) {
            return [
                'success' => false,
                'error'   => 'User not found',
                'details' => $ret
            ];
        }

        // Add bonus
        $ticket = 0;
        $ret = $this->mt5->TradeBalance($user->Login, MTEnDealAction::DEAL_BONUS, $amount, $comment, $ticket);

        if ($ret === MTRetCode::MT_RET_OK) {
            return [
                'success' => true,
                'message' => "✅ Bonus added successfully!"
            ];
        } else {
            return [
                'success' => false,
                'error'   => "❌ Failed to add bonus",
                'details' => $ret
            ];
        }
    }
}

$bonus = new AddBonus();
$result = $bonus->addBonus($data);
echo json_encode($result);
