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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

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

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

$trade_id = $data['trade_id'] ?? null;
if(!$trade_id){
    echo json_encode(["status"=>"error","message"=>"Missing trade_id"]);
    exit;
}

// --- Fetch master account from DB ---
$stmt = $conn->prepare("SELECT * FROM liveaccounts WHERE trade_id=? LIMIT 1");
$stmt->bind_param("s", $trade_id);
$stmt->execute();
$account = $stmt->get_result()->fetch_assoc();
$stmt->close();

if(!$account){
    echo json_encode(["status"=>"error","message"=>"Account not found"]);
    exit;
}

// --- MT5 Connection ---
$mt5 = new MT5Connection();
if(!$mt5->connect()){
    echo json_encode(["status"=>"error","message"=>"MT5 Connection failed","error_code"=>$mt5->lastError()]);
    exit;
}

// --- Fetch master MT5 info ---
$mt5_login = intval($account['trade_id']);
$account_info = [];
if($mt5->api->UserAccountGet($mt5_login, $account_info) === 0){
    $account['Balance'] = $account_info->Balance;
    $account['equity'] = $account_info->Equity;
    $account['totalprofit'] = $account_info->Profit;
} else {
    $account_info = ["error"=>"MT5 account fetch failed"];
}

// --- Fetch open positions ---
$open_positions = [];
$total_positions = 0;

if ($mt5->api->PositionGetTotal($mt5_login, $total_positions) === 0 && $total_positions > 0) {
    $positions = [];
    $mt5->api->PositionGetPage($mt5_login, 0, $total_positions, $positions);

    foreach ($positions as $pos) {
        if (isset($pos->Volume)) {
            $pos->Volume = round($pos->Volume * 0.0001, 2);
        }
        $open_positions[] = $pos;
    }
}

// --- Fetch trade history ---
$trade_history = [];
$total_history = 0;
$from = strtotime('-1 year');
$to   = time();

if ($mt5->api->HistoryGetTotal($mt5_login, $from, $to, $total_history) === 0 && $total_history > 0) {
    $mt5->api->HistoryGetPage($mt5_login, $from, $to, 0, $total_history, $trade_history);
}

// --- Combine open positions into trade history ---
if (!empty($open_positions)) {
    $trade_history = array_merge($trade_history, $open_positions);
}

// --- Count followers + fetch follower details ---
$stmt = $conn->prepare("SELECT * FROM copyaccounts WHERE mastertrade=? AND status=1");
$stmt->bind_param("s", $trade_id);
$stmt->execute();
$followers_res = $stmt->get_result();

$follower_list = [];
$strategyEquity = 0;

while($f = $followers_res->fetch_assoc()){
    $f_login = intval($f['slavetrade']);
    $f_account = [];

    $slave_balance = 0;
    $slave_equity = 0;
    $slave_profit = 0;
    $slave_volume = 0;

    // --- Fetch account type ---
    $slave_type = '';
    $type_query = $conn->prepare("SELECT account_type FROM liveaccounts WHERE trade_id = ?");
    $type_query->bind_param("s", $f['slavetrade']);
    $type_query->execute();
    $type_result = $type_query->get_result()->fetch_assoc();
    if ($type_result) {
        $slave_type = $type_result['account_type'];
    }
    $type_query->close();

    // --- Fetch commission ---
    $commission = null;
    $comm_query = $conn->prepare("SELECT commission FROM liveaccounts WHERE trade_id = ?");
    $comm_query->bind_param("s", $trade_id);
    $comm_query->execute();
    $comm_result = $comm_query->get_result()->fetch_assoc();
    if ($comm_result) {
        $commission = $comm_result['commission'];
    }
    $comm_query->close();

    // --- Fetch slave info from MT5 ---
    if($mt5->api->UserAccountGet($f_login, $f_account) === 0){
        $slave_balance = $f_account->Balance ?? 0;
        $slave_equity  = $f_account->Equity ?? 0;
        $slave_profit  = $f_account->Profit ?? 0;
        $slave_volume = isset($f_account->Volume) ? round($f_account->Volume * 0.0001, 2) : 0;

        $strategyEquity += floatval($slave_equity);
    }

    $risk = ($slave_balance > 0) ? round(($slave_equity / $slave_balance) * 100, 2) : 0;

    $follower_list[] = [
        "slave_trade_id"     => $f['slavetrade'],
        "slave_balance"      => $slave_balance,
        "risk"               => $risk,
        "account_type"       => $slave_type,
        "slave_trade_volume" => $slave_volume,
        "volume_setting"     => $f['volumeselect'],
        "slave_p_l"          => $slave_profit,
        "commission"         => $commission,
        "created_date"       => $f['created_at']
    ];
}

$stmt->close();

// --- Add collected data ---
$account['followers'] = count($follower_list);
$account['strategyEquity'] = round($strategyEquity, 2);
$account['mt5_info'] = $account_info;
$account['open_positions'] = $open_positions;
$account['trade_history'] = $trade_history;
$account['follower_list'] = $follower_list;

// ✅ Fetch max_drawdown directly from DB (no recalculation)
$account['max_drawdown'] = isset($account['max_drawdown']) ? floatval($account['max_drawdown']) : 0.0;

echo json_encode(["status" => "success", "data" => $account]);
exit;
?>
