<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST, OPTIONS");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    http_response_code(200);
    exit;
}

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

// ---------- includes ----------
include_once __DIR__ . "/../config.php";
include_once __DIR__ . "/../connection.php"; 
// --------------------------------

$response = ["success" => false, "message" => ""];

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

$email    = trim($data["email"] ?? '');
$trade_id = trim($data["trade_id"] ?? '');
$amount   = floatval($data["amount"] ?? 0);
$action   = $data["action_type"] ?? null; // add / remove
$comment  = trim($data["comment"] ?? "");

// validation
if ($email === '' || $trade_id === '' || $amount <= 0 || !in_array($action, ['add','remove'])) {
    echo json_encode(["success" => false, "message" => "Missing/invalid input. Required: email, trade_id, amount>0, action_type in (add,remove)."]);
    exit;
}

// get user by email
$stmt = $conn->prepare("SELECT id FROM loginusers WHERE email = ? LIMIT 1");
if (!$stmt) { echo json_encode(["success"=>false,"message"=>"DB prepare error (loginusers)"]); exit; }
$stmt->bind_param("s", $email);
$stmt->execute();
$res = $stmt->get_result();
if ($res->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "User not found with email: $email"]);
    exit;
}
$user = $res->fetch_assoc();
$user_id = (int)$user['id'];
$stmt->close();

// fetch live account and account_type (we need account_type for CENT handling)
$stmt = $conn->prepare("SELECT id, account_type FROM liveaccounts WHERE trade_id = ? AND user_id = ? LIMIT 1");
if (!$stmt) { echo json_encode(["success"=>false,"message"=>"DB prepare error (liveaccounts)"]); exit; }
$stmt->bind_param("si", $trade_id, $user_id);
$stmt->execute();
$res = $stmt->get_result();
if ($res->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "Trading account not found for this user/trade_id"]);
    exit;
}
$acct = $res->fetch_assoc();
$live_acc_id = (int)$acct['id'];
$account_type = strtoupper(trim($acct['account_type'] ?? '') );
$stmt->close();

// connect to MT5 via your MT5Connection wrapper
$mt5 = new MT5Connection();
if (!$mt5->connect()) {
    echo json_encode(["success" => false, "message" => "MT5 connection failed", "mt5_error" => $mt5->lastError() ?? null]);
    exit;
}

// Determine MT5 deal type and amount
// We want to change BONUS on MT5 (DEAL_BONUS). For add => positive, remove => negative.
$dealType = MTEnDealAction::DEAL_BONUS;
$centMultiplier = ($account_type === 'CENT') ? 0.01 : 1.0;

// Convert amount to MT5 units for CENT accounts (same conversion used in your other code)
$mt5Amount = $amount;
if ($centMultiplier !== 1.0) {
    // their previous logic used deposit_amt / centMultiplier, which for centMultiplier=0.01 results in amount*100
    $mt5Amount = $amount / $centMultiplier;
}

// make negative for removal
if ($action === 'remove') {
    $mt5Amount = -1.0 * $mt5Amount;
}

// perform MT5 balance change
$ticket = 0;
$ret = $mt5->api->TradeBalance((int)$trade_id, $dealType, $mt5Amount, "ADMIN BONUS {$action}: {$comment}", $ticket);

if ($ret !== MTRetCode::MT_RET_OK) {
    // disconnect for safety
    if (method_exists($mt5, 'disconnect')) { $mt5->disconnect(); }
    echo json_encode([
        "success" => false,
        "message" => "MT5 TradeBalance failed",
        "mt5_code" => $ret
    ]);
    exit;
}

// optionally refresh balance if you want (not required)
// $mt5UserAfter = new MTUser();
// if ($mt5->api->UserGet((int)$trade_id, $mt5UserAfter) == MTRetCode::MT_RET_OK) { $newBalance = $mt5UserAfter->Balance ?? null; }

// update local liveaccounts table
if ($action === 'add') {
    // increment bonusDeposit (existing behaviour in your snippets)
    $upd = $conn->prepare("UPDATE liveaccounts SET bonusDeposit = bonusDeposit + ? WHERE id = ?");
} else {
    // log removal into wBonusDeposit column as earlier code did
    $upd = $conn->prepare("UPDATE liveaccounts SET wBonusDeposit = wBonusDeposit + ? WHERE id = ?");
}
if (!$upd) {
    echo json_encode(["success"=>false,"message"=>"DB prepare error (update liveaccounts): ".$conn->error]);
    exit;
}
$upd->bind_param("di", $amount, $live_acc_id);
$upd->execute();
$upd->close();

// insert admin log into admin_bonus
$log = $conn->prepare("INSERT INTO admin_bonus (email, trade_id, amount, action_type, comment) VALUES (?, ?, ?, ?, ?)");
if (!$log) {
    echo json_encode(["success"=>false,"message"=>"DB prepare error (admin_bonus): ".$conn->error]);
    exit;
}
$log->bind_param("ssdss", $email, $trade_id, $amount, $action, $comment);
$ok = $log->execute();
$log->close();

if (!$ok) {
    echo json_encode(["success"=>false,"message"=>"Failed to write admin bonus log"]);
    exit;
}

// success
echo json_encode([
    "success" => true,
    "message" => "Bonus " . ($action === 'add' ? 'added' : 'removed') . " successfully",
    "mt5_ticket" => $ticket,
    "email" => $email,
    "trade_id" => $trade_id,
    "amount" => $amount,
    "action" => $action
]);
exit;
?>
