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

ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(E_ALL);

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

// Read input
$input = json_decode(file_get_contents("php://input"), true);
$id = $input['id'] ?? null;

if (!$id) {
    echo json_encode(["success" => false, "message" => "Reward ID is required"]);
    exit;
}

try {
    // Fetch reward details
    $stmt = $conn->prepare("SELECT * FROM lots_reward_users WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $reward = $stmt->get_result()->fetch_assoc();
    if (!$reward) throw new Exception("Reward not found");

    $trade_id = $reward['trade_id'];
    $amount = (float)$reward['reward_amount'];
    $account_type_name = $reward['account_type'];

    if ($amount <= 0) throw new Exception("Reward amount is zero, cannot transfer");

    // Check if account type is Cent
    $stmt_ac = $conn->prepare("SELECT ac_name FROM account_types WHERE ac_name = ?");
    $stmt_ac->bind_param("s", $account_type_name);
    $stmt_ac->execute();
    $ac_result = $stmt_ac->get_result()->fetch_assoc();
    $is_cent = ($ac_result['ac_name'] === 'Cent');

    // Correct conversion: Cent account rewards should be multiplied by 100
    $transfer_amount = $is_cent ? ($amount * 100) : $amount;

    // Connect to MT5
    $mt5 = new MTWebAPI();
    $ret = $mt5->Connect(MT5_SERVER_IP, MT5_SERVER_PORT, MT5_TIMEOUT, MT5_SERVER_WEB_LOGIN, MT5_SERVER_WEB_PASSWORD);
    if ($ret != MTRetCode::MT_RET_OK) throw new Exception("MT5 connection failed: $ret");

    $comment = "Lots reward transfer ID: {$id}";
    $ticket = null;
    $ret_trade = $mt5->TradeBalance($trade_id, MTEnDealAction::DEAL_BALANCE, $transfer_amount, $comment, $ticket);
    if ($ret_trade != MTRetCode::MT_RET_OK) throw new Exception("MT5 reward transfer failed: $ret_trade");

    // Mark reward as transferred
    $stmt2 = $conn->prepare("UPDATE lots_reward_users SET reward_amount = 0 WHERE id = ?");
    $stmt2->bind_param("i", $id);
    $stmt2->execute();

    // Insert log
    $stmt_log = $conn->prepare("INSERT INTO lots_reward_logs (reward_id, user_email, account_name, account_type, action, amount, ticket) VALUES (?, ?, ?, ?, 'transfer', ?, ?)");
    $stmt_log->bind_param("isssds", $id, $reward['user_email'], $reward['account_name'], $account_type_name, $amount, $ticket);
    $stmt_log->execute();

    $mt5->Disconnect();

    echo json_encode([
        "success" => true,
        "message" => "Reward transferred successfully",
        "ticket" => $ticket
    ]);

} catch (Throwable $e) {
    echo json_encode([
        "success" => false,
        "message" => $e->getMessage()
    ]);
}
?>
