<?php
// Enable full error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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");

include_once __DIR__ . "/connection.php"; // $conn should be mysqli
include_once __DIR__ . "/config.php";

try {
    // 1️⃣ Get POST input
    $input = json_decode(file_get_contents("php://input"), true);

    $slave_email     = $input['slave_email'] ?? '';
    $slave_trade_id  = $input['slavetrade'] ?? '';
    $master_trade_id = $input['mastertrade'] ?? '';
    $strategy_name   = $input['strategyname'] ?? '';
    $strategy_image  = $input['strategyimage'] ?? '';
    $commission      = (float)($input['commission'] ?? 0);
    $volume_select   = $input['volumeselect'] ?? 'normal';

    if (!$slave_email || !$slave_trade_id || !$master_trade_id) {
        throw new Exception("Missing required parameters");
    }

    // 2️⃣ Get mindeposit and account_name from DB (mysqli)
    $stmt = $conn->prepare("SELECT mindeposit, account_name FROM liveaccounts WHERE trade_id = ?");
    if (!$stmt) throw new Exception("Prepare statement failed: " . $conn->error);

    $stmt->bind_param("s", $master_trade_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $master_account_info = $result->fetch_assoc();
    $stmt->close();

    if (!$master_account_info) {
        throw new Exception("Master account not found");
    }

    $mindeposit  = (float)$master_account_info['mindeposit'];
    $master_name = $master_account_info['account_name'] ?? 'Master';

    // 3️⃣ Connect to MT5 safely
    $mt5 = new MT5Connection();
    if (!$mt5->connect()) {
        throw new Exception("Failed to connect to MT5 server");
    }

    // 4️⃣ Fetch slave account safely
    $slave_name = 'Slave';
    $slave_balance = 0.0;
    $slave_account = new MTAccount();
    $ret_slave = $mt5->api->UserAccountGet((int)$slave_trade_id, $slave_account);
    if ($ret_slave === MTRetCode::MT_RET_OK && isset($slave_account->Balance)) {
        $slave_name = $slave_account->Name ?? 'Slave';
        $slave_balance = $slave_account->Balance;
    } else {
        throw new Exception("Failed to fetch slave account info from MT5");
    }

    // 5️⃣ Fetch master account safely
    $master_balance = 0.0;
    $master_account = new MTAccount();
    $ret_master = $mt5->api->UserAccountGet((int)$master_trade_id, $master_account);
    if ($ret_master === MTRetCode::MT_RET_OK && isset($master_account->Balance)) {
        $master_balance = $master_account->Balance;
    }

    // 6️⃣ Check if slave has enough balance
    $investment_amount = $mindeposit;
    if ($slave_balance < $investment_amount) {
        echo json_encode([
            "status" => "error",
            "message" => "Insufficient balance for this investment",
            "slave_balance" => $slave_balance,
            "required_amount" => $investment_amount,
            "mindeposit" => $mindeposit
        ]);
        exit;
    }

    $commission_amount = ($investment_amount * $commission) / 100;

    // 7️⃣ Deduct investment from slave account
    $ticket = 0;
    $ret_trade = $mt5->api->TradeBalance(
        (int)$slave_trade_id,
        MTEnDealAction::DEAL_BALANCE,
        -$investment_amount,
        "Investment to master: $master_trade_id",
        $ticket
    );
    if ($ret_trade !== MTRetCode::MT_RET_OK) {
        throw new Exception("Failed to execute investment on slave account");
    }

    // 8️⃣ Insert into copyaccounts table (mysqli)
    $volume     = $investment_amount;
    $status     = 1;
    $followdate = date("Y-m-d H:i:s");
    $date_now   = date("Y-m-d H:i:s");

    $stmt = $conn->prepare("
        INSERT INTO copyaccounts
        (email, mastername, mastertrade, strategyimage, strategyname, commission, slavename, slavetrade, volumeselect, volume, status, followdate, Date)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    if (!$stmt) throw new Exception("Prepare insert failed: " . $conn->error);

    $stmt->bind_param(
        "ssssssssdisss",
        $slave_email,
        $master_name,
        $master_trade_id,
        $strategy_image,
        $strategy_name,
        $commission,
        $slave_name,
        $slave_trade_id,
        $volume_select,
        $volume,
        $status,
        $followdate,
        $date_now
    );
    $stmt->execute();
    $stmt->close();

    // 9️⃣ Success response
    echo json_encode([
        "status" => "success",
        "message" => "Investment created successfully",
        "slave_balance" => $slave_balance - $investment_amount,
        "master_balance" => $master_balance,
        "investment_amount" => $investment_amount,
        "commission_amount" => $commission_amount,
        "mindeposit_used" => $mindeposit,
        "ticket" => $ticket
    ]);

} catch (Exception $e) {
    echo json_encode([
        "status" => "error",
        "message" => $e->getMessage()
    ]);
    exit;
}
