<?php
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.php";

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

$request_id = intval($data['request_id'] ?? 0);
$action     = $data['action'] ?? ''; // approve / reject
$admin_comment = $data['admin_comment'] ?? '';

// validate
if(!$request_id || !in_array($action, ['approve','reject'])) {
    echo json_encode(["success"=>false,"error"=>"Invalid parameters"]);
    exit;
}

// get request
$stmt = $conn->prepare("SELECT * FROM deposit_requests WHERE id=? LIMIT 1");
$stmt->bind_param("i", $request_id);
$stmt->execute();
$request = $stmt->get_result()->fetch_assoc();

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

if($action === 'reject') {
    $stmt = $conn->prepare("UPDATE deposit_requests SET status='rejected', admin_comment=? WHERE id=?");
    $stmt->bind_param("si", $admin_comment, $request_id);
    $stmt->execute();
    echo json_encode(["success"=>true,"message"=>"Deposit rejected"]);
    exit;
}

// ✅ If approve: call MT5 API
$api = new MTWebAPI("AdminApp");
$ret = $api->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, 300, MT5_MANAGER_LOGIN, MT5_MANAGER_PASSWORD);

if($ret != MTRetCode::MT_RET_OK) {
    echo json_encode(["success"=>false,"error"=>"MT5 connection failed","code"=>$ret]);
    exit;
}

$ticket = 0;
$deal_action = ($request['type'] === 'bonus') 
    ? MTEnDealAction::DEAL_BALANCE_BONUS 
    : MTEnDealAction::DEAL_BALANCE;

$mt5_ret = $api->TradeBalance((int)$request['trade_id'], $deal_action, (float)$request['amount'], $admin_comment, $ticket);

if($mt5_ret == MTRetCode::MT_RET_OK) {
    // update DB as approved
    $stmt = $conn->prepare("UPDATE deposit_requests SET status='approved', admin_comment=? WHERE id=?");
    $stmt->bind_param("si", $admin_comment, $request_id);
    $stmt->execute();

    echo json_encode([
        "success"=>true,
        "message"=>"Deposit approved & applied in MT5",
        "mt5_ticket"=>$ticket
    ]);
} else {
    echo json_encode([
        "success"=>false,
        "error"=>"Failed to apply deposit in MT5",
        "code"=>$mt5_ret
    ]);
}

$api->Disconnect();
