<?php
// backend/api/trade-stats.php
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");

require_once '../config/db.php';

$wallet = trim($_GET['wallet'] ?? '');
if (empty($wallet)) {
    echo json_encode(["status" => "error", "message" => "Wallet required"]);
    exit;
}

// 1. User Info & Base Investment
$invRes = mysqli_query($conn, "SELECT COALESCE(SUM(amount),0) AS amt FROM deposits WHERE wallet='$wallet' AND status='success'");
$total_inv = floatval(mysqli_fetch_assoc($invRes)['amt']);

// 2. Fetch Logs with ALL columns
$logsRes = mysqli_query($conn, 
    "SELECT id, position, amount, profit, profit_rate, total_return, status, created_at 
     FROM trading_logs 
     WHERE wallet='$wallet' 
     ORDER BY id DESC LIMIT 100"
);

$logs = [];
$total_profit = 0;
$buy_count = 0;
$sell_count = 0;

while ($row = mysqli_fetch_assoc($logsRes)) {
    $p = floatval($row['profit']);
    $total_profit += $p;
    if ($row['position'] === 'BUY') $buy_count++;
    if ($row['position'] === 'SELL') $sell_count++;

    $logs[] = [
        'id'           => $row['id'],
        'position'     => $row['position'],
        'amount'       => floatval($row['amount']),
        'profit'       => $p,
        'profit_rate'  => floatval($row['profit_rate']), // Individual rate from DB
        'total_return' => floatval($row['total_return']),
        'status'       => $row['status'],
        'created_at'   => date('d M, h:i A', strtotime($row['created_at']))
    ];
}

// 3. Check for Active Trade
$activeRes = mysqli_query($conn, "SELECT position, amount, profit_rate, created_at FROM trading_logs WHERE wallet='$wallet' AND status='active' LIMIT 1");
$activeTrade = mysqli_fetch_assoc($activeRes);

echo json_encode([
    "status"  => "success",
    "summary" => [
        "total_investment" => $total_inv,
        "total_profit"     => round($total_profit, 2),
        "buy_count"        => $buy_count,
        "sell_count"       => $sell_count,
        "trade_count"      => count($logs)
    ],
    "active_trade" => $activeTrade ? [
        "position"    => $activeTrade['position'],
        "amount"      => floatval($activeTrade['amount']),
        "profit_rate" => floatval($activeTrade['profit_rate']),
        "created_at"  => date('d M, h:i A', strtotime($activeTrade['created_at']))
    ] : null,
    "logs" => $logs
]);