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

include_once __DIR__ . "/connection.php";

// Get filter parameters from GET or POST
$group = $_GET['group'] ?? 'All';
$symbol = $_GET['symbol'] ?? 'All';
$type   = $_GET['type'] ?? 'All';
$start_date = $_GET['start_date'] ?? date('Y-m-d', strtotime('-1 month'));
$end_date   = $_GET['end_date'] ?? date('Y-m-d');
$duration   = $_GET['duration'] ?? 'All';

$start_timestamp = strtotime($start_date);
$end_timestamp   = strtotime($end_date) + 86399; // include full day

$mt5 = new MT5Connection();

if (!$mt5->connect()) {
    echo json_encode([
        "success" => false,
        "error" => "MT5 connection failed",
        "details" => $mt5->lastError()
    ]);
    exit;
}

// Fetch all logins (clients)
$logins = [];
if ($group === 'All') {
    // fetch all groups
    $total_groups = 0;
    $mt5->api->GroupTotal($total_groups);
    for ($i = 0; $i < $total_groups; $i++) {
        $grp = null;
        $mt5->api->GroupNext($i, $grp);
        $group_logins = [];
        $mt5->api->UserLogins($grp->name, $group_logins);
        $logins = array_merge($logins, $group_logins);
    }
} else {
    // fetch logins of selected group
    $mt5->api->UserLogins($group, $logins);
}

$all_trades = [];
$total_pl = 0;
$total_volume = 0;
$total_swaps = 0;
$total_pips = 0;

// Loop through each login and fetch trade history
foreach ($logins as $login) {
    $total_deals = 0;
    $mt5->api->HistoryGetTotal($login, $start_timestamp, $end_timestamp, $total_deals);

    if ($total_deals > 0) {
        $deals = [];
        $mt5->api->HistoryGetPage($login, $start_timestamp, $end_timestamp, 0, $total_deals, $deals);

        foreach ($deals as $deal) {
            // Filter by symbol
            if ($symbol !== 'All' && $deal->symbol !== $symbol) continue;

            // Filter by type
            if ($type !== 'All') {
                if ($type === 'Buy' && $deal->type != 0) continue;
                if ($type === 'Sell' && $deal->type != 1) continue;
            }

            // Calculate pips (simple example for Forex)
            $pips = ($deal->type == 0) ? ($deal->price_close - $deal->price_open) : ($deal->price_open - $deal->price_close);
            if (strpos(strtolower($deal->symbol), "jpy") !== false) $pips *= 100; // JPY pair adjustment
            else $pips *= 10000;

            $all_trades[] = [
                "ticket"      => $deal->ticket,
                "client"      => $login,
                "open_time"   => date('Y-m-d H:i:s', $deal->time_msc_open/1000),
                "close_time"  => date('Y-m-d H:i:s', $deal->time_msc_close/1000),
                "symbol"      => $deal->symbol,
                "type"        => ($deal->type == 0) ? 'Buy' : 'Sell',
                "volume"      => $deal->volume,
                "open_price"  => $deal->price_open,
                "close_price" => $deal->price_close,
                "pips"        => round($pips, 2),
                "comm"        => $deal->commission,
                "swap"        => $deal->swap,
                "pl"          => $deal->profit
            ];

            $total_pl += $deal->profit;
            $total_volume += $deal->volume;
            $total_swaps += $deal->swap;
            $total_pips += $pips;
        }
    }
}

echo json_encode([
    "success" => true,
    "total_pl" => round($total_pl, 2),
    "total_pips" => round($total_pips, 2),
    "total_volume" => round($total_volume, 2),
    "total_swaps" => round($total_swaps, 2),
    "trades" => $all_trades
]);
