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

// --- Count Followers ---
$stmt = $conn->prepare("SELECT COUNT(*) as followers FROM copyaccounts WHERE mastertrade=? AND status=2");
$stmt->bind_param("s", $trade_id);
$stmt->execute();
$followerCount = $stmt->get_result()->fetch_assoc();
$stmt->close();
$account['followers'] = $followerCount['followers'] ?? 0;

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

// --- Ensure numeric login ---
$mt5_login = intval($account['trade_id']);

// --- Fetch account info ---
$account_info = [];
$err = $mt5->api->UserAccountGet($mt5_login, $account_info);
if($err != 0){
    $account_info = ["error" => "MT5 account fetch failed", "error_code" => $err];
}

// --- Fetch open positions ---
$open_positions = [];
$total_positions = 0;
$err = $mt5->api->PositionGetTotal($mt5_login, $total_positions);
if($err === 0 && $total_positions > 0){
    $err_page = $mt5->api->PositionGetPage($mt5_login, 0, $total_positions, $open_positions);
}

// --- Fetch trade history ---
$trade_history = [];
$total_deals = 0;
$from = strtotime('-1 year'); // adjust as needed
$to   = time();
$err = $mt5->api->DealGetTotal($mt5_login, $from, $to, $total_deals);
if($err === 0 && $total_deals > 0){
    $err_page = $mt5->api->DealGetPage($mt5_login, $from, $to, 0, $total_deals, $trade_history);
}

// --- Max Drawdown ---
$profit_values = $account['profitvalue'] ? explode(",", (string)$account['profitvalue']) : [];
$max_equity = 0;
$max_drawdown = 0;
foreach($profit_values as $p){
    $p = floatval($p);
    if($p > $max_equity) $max_equity = $p;
    $dd = $max_equity - $p;
    if($dd > $max_drawdown) $max_drawdown = $dd;
}

$account['mt5_info'] = $account_info;
$account['open_positions'] = $open_positions;
$account['trade_history'] = $trade_history;
$account['max_drawdown'] = $max_drawdown;

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