<?php
// ===== DEBUG SETTINGS (remove in production) =====
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// ===== HEADERS =====
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// ===== INCLUDE FILES =====
include_once __DIR__ . "/config.php";
include_once __DIR__ . "/connection.php";

// ===== OPTIONAL ERROR LOG FILE =====
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/transfer_balance_error.log');

// ===== SAFETY CHECK FOR CONNECTION =====
if (!isset($conn) || !$conn) {
    echo json_encode(["success" => false, "message" => "Database connection failed."]);
    exit;
}

// ===== HANDLE JSON INPUT =====
$input = json_decode(file_get_contents("php://input"), true);

if (!isset($input['email'], $input['trade_id'], $input['amount'])) {
    echo json_encode(["success" => false, "message" => "Missing required parameters."]);
    exit;
}

$email = trim($input['email']);
$trade_id = trim($input['trade_id']);
$amount = round(floatval($input['amount']), 2);

if ($amount <= 0) {
    echo json_encode(["success" => false, "message" => "Invalid amount."]);
    exit;
}

// ===== FETCH AVAILABLE COMMISSION =====
$sql = "SELECT available_commission FROM ib_total_commission WHERE ib_email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "IB email not found in database."]);
    exit;
}

$row = $result->fetch_assoc();
$available_commission = floatval($row['available_commission']);

if ($available_commission < $amount) {
    echo json_encode(["success" => false, "message" => "Insufficient available commission."]);
    exit;
}

// ===== CONNECT TO MT5 =====
$mt5 = new MT5Connection();
if (!$mt5->connect()) {
    echo json_encode(["success" => false, "message" => "Failed to connect to MT5 server."]);
    exit;
}

// ===== DEFINE CONSTANT IF MISSING =====
if (!defined('DEAL_BALANCE')) {
    define('DEAL_BALANCE', 2); // standard balance deal action
}

// ===== VERIFY MT5 USER =====
$user = null;
$ret = $mt5->api->UserGet((int)$trade_id, $user);
if ($ret !== MTRetCode::MT_RET_OK) {
    echo json_encode(["success" => false, "message" => "Invalid MT5 login ID or user not found. Code: " . $ret]);
    exit;
}

// ===== PERFORM BALANCE TRANSFER =====
$comment = "Commission transferred from partner portal ($email)";
$ret = $mt5->api->TradeBalance((int)$trade_id, DEAL_BALANCE, $amount, $comment);

if ($ret !== MTRetCode::MT_RET_OK) {
    echo json_encode(["success" => false, "message" => "MT5 balance transfer failed. Code: " . $ret]);
    exit;
}

// ===== UPDATE COMMISSION TABLE =====
$update_sql = "UPDATE ib_total_commission 
               SET available_commission = available_commission - ? 
               WHERE ib_email = ?";
$update_stmt = $conn->prepare($update_sql);
$update_stmt->bind_param("ds", $amount, $email);

if (!$update_stmt->execute()) {
    echo json_encode(["success" => false, "message" => "Database update failed."]);
    exit;
}

// ===== OPTIONAL LOGGING (recommended) =====
$log_sql = "CREATE TABLE IF NOT EXISTS ib_commission_transfer_log (
    id INT AUTO_INCREMENT PRIMARY KEY,
    ib_email VARCHAR(255) NOT NULL,
    trade_id VARCHAR(50) NOT NULL,
    amount DECIMAL(10,2) NOT NULL,
    comment TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)";
$conn->query($log_sql);

$log_insert = "INSERT INTO ib_commission_transfer_log (ib_email, trade_id, amount, comment, created_at)
               VALUES (?, ?, ?, ?, NOW())";
$log_stmt = $conn->prepare($log_insert);
$log_stmt->bind_param("sdss", $email, $trade_id, $amount, $comment);
$log_stmt->execute();

// ===== SUCCESS RESPONSE =====
echo json_encode([
    "success" => true,
    "message" => "Balance transferred successfully.",
    "data" => [
        "email" => $email,
        "trade_id" => $trade_id,
        "amount_transferred" => $amount
    ]
]);
?>
