<?php
require_once __DIR__ . '/connection.php';
require_once __DIR__ . '/mt5_api/mt5_api.php';

function ensure_mt5_stats_cache_table($conn) {
    $sql = "CREATE TABLE IF NOT EXISTS mt5_stats_cache (
        trade_id VARCHAR(64) PRIMARY KEY,
        volume DOUBLE DEFAULT 0,
        sum_profit DOUBLE DEFAULT 0,
        floating_pl DOUBLE DEFAULT 0,
        active_trades INT DEFAULT 0,
        closed_trades INT DEFAULT 0,
        profitable_trades INT DEFAULT 0,
        loss_trades INT DEFAULT 0,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB";
    $conn->query($sql);
}

function get_mt5_stats($conn, $mt5, $trade_id, $ttl_seconds = 300, $force_refresh = false) {
    ensure_mt5_stats_cache_table($conn);
    $stats = null;
    if (!$force_refresh) {
        $stmt = $conn->prepare("SELECT volume, sum_profit, floating_pl, active_trades, closed_trades, profitable_trades, loss_trades FROM mt5_stats_cache WHERE trade_id = ? AND updated_at >= DATE_SUB(NOW(), INTERVAL ? SECOND)");
        $stmt->bind_param("si", $trade_id, $ttl_seconds);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
            $stats = [
                'volume' => (float)($row['volume'] ?? 0),
                'sumProfit' => (float)($row['sum_profit'] ?? 0),
                'floatingPL' => (float)($row['floating_pl'] ?? 0),
                'activeTrades' => (int)($row['active_trades'] ?? 0),
                'closedTrades' => (int)($row['closed_trades'] ?? 0),
                'profitableTrades' => (int)($row['profitable_trades'] ?? 0),
                'lossTrades' => (int)($row['loss_trades'] ?? 0)
            ];
        }
        $stmt->close();
    }
    if ($stats !== null) return $stats;

    $volume = 0.0;
    $sumProfit = 0.0;
    $floatingPL = 0.0;
    $activeTrades = 0;
    $closedTrades = 0;
    $profitableTrades = 0;
    $lossTrades = 0;

    $totalDeals = 0;
    $ret_total = $mt5->DealGetTotal($trade_id, 0, 0, $totalDeals);
    if ($ret_total == MTRetCode::MT_RET_OK && $totalDeals > 0) {
        $deals = [];
        $ret_page = $mt5->DealGetPage($trade_id, 0, 0, 0, $totalDeals, $deals);
        if ($ret_page == MTRetCode::MT_RET_OK) {
            foreach ($deals as $deal) {
                $vol_closed_raw = isset($deal->VolumeClosed) ? (float)$deal->VolumeClosed : 0;
                $vol_lots = $vol_closed_raw > 0 ? $vol_closed_raw * 0.0001 : 0;
                $order_id = isset($deal->Order) ? (int)$deal->Order : 0;
                if ($vol_lots > 0) $volume += $vol_lots;
                if ($order_id !== 0 && $vol_lots > 0) {
                    $profit = isset($deal->Profit) ? (float)$deal->Profit : 0;
                    $sumProfit += $profit;
                    $closedTrades++;
                    if ($profit > 0) $profitableTrades++;
                    elseif ($profit < 0) $lossTrades++;
                }
            }
        }
    }

    $positions = [];
    $totalPositions = 0;
    if ($mt5->PositionGetTotal($trade_id, $totalPositions) == MTRetCode::MT_RET_OK && $totalPositions > 0) {
        $ret_positions = $mt5->PositionGetPage($trade_id, 0, $totalPositions, $positions);
        if ($ret_positions == MTRetCode::MT_RET_OK) {
            foreach ($positions as $pos) {
                $floatingPL += isset($pos->Profit) ? (float)$pos->Profit : 0;
                $activeTrades++;
            }
        }
    }

    $stmt_up = $conn->prepare("INSERT INTO mt5_stats_cache (trade_id, volume, sum_profit, floating_pl, active_trades, closed_trades, profitable_trades, loss_trades, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE volume=VALUES(volume), sum_profit=VALUES(sum_profit), floating_pl=VALUES(floating_pl), active_trades=VALUES(active_trades), closed_trades=VALUES(closed_trades), profitable_trades=VALUES(profitable_trades), loss_trades=VALUES(loss_trades), updated_at=NOW()");
    $stmt_up->bind_param("sddddiii", $trade_id, $volume, $sumProfit, $floatingPL, $activeTrades, $closedTrades, $profitableTrades, $lossTrades);
    $stmt_up->execute();
    $stmt_up->close();

    return [
        'volume' => $volume,
        'sumProfit' => $sumProfit,
        'floatingPL' => $floatingPL,
        'activeTrades' => $activeTrades,
        'closedTrades' => $closedTrades,
        'profitableTrades' => $profitableTrades,
        'lossTrades' => $lossTrades
    ];
}

?>
