<?php
// File: /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 check ─────────────────────────────────────────
$uRow = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT account_id FROM users WHERE wallet='$wallet' LIMIT 1"
));
if (!$uRow) {
    echo json_encode(["status" => "error", "message" => "User not found"]);
    exit;
}

// ── 2. Total investment ───────────────────────────────────
$total_inv = floatval(mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT COALESCE(SUM(amount),0) AS amt FROM deposits WHERE wallet='$wallet' AND status='success'"
))['amt']);

// ── 3. User's personal trade rate ────────────────────────
// $500+ = 7%, otherwise 4%
// ── 3. User's personal trade rate (SYNC WITH DASHBOARD) ────────
$user_trade_rate = 4.0; // Default base rate

// Rewards Tiers check aur Auto-Update logic
$uFull = mysqli_fetch_assoc(mysqli_query($conn,
    "SELECT reward_tier_1, reward_tier_2, reward_tier_3, account_id FROM users WHERE wallet='$wallet' LIMIT 1"
));

if ($uFull) {
    $reward_tier_1 = intval($uFull['reward_tier_1']);
    $reward_tier_2 = intval($uFull['reward_tier_2']);
    $reward_tier_3 = intval($uFull['reward_tier_3']);
    $acc_id = $uFull['account_id'];

    // DASHBOARD WALA SAME LOGIC: Tier 1 check (3 Directs)
    if ($reward_tier_1 == 0) {
        $check_t1 = mysqli_fetch_assoc(mysqli_query($conn, 
            "SELECT COUNT(DISTINCT u.wallet) as cnt FROM users u 
             JOIN deposits d ON u.wallet = d.wallet 
             WHERE u.referral_id = '$acc_id' AND d.status = 'success' AND d.amount >= 100"));
        
        if ($check_t1['cnt'] >= 3) {
            mysqli_query($conn, "UPDATE users SET reward_tier_1 = 1 WHERE account_id = '$acc_id'");
            $reward_tier_1 = 1;
        }
    }

    // Rate Calculation (Exactly same as get-user.php)
    if ($reward_tier_3 == 1)      { $user_trade_rate = 7.0; }
    elseif ($reward_tier_2 == 1)  { $user_trade_rate = 6.0; }
    elseif ($reward_tier_1 == 1)  { $user_trade_rate = 5.0; }
}

// ── 4. Check trade_logs columns ───────────────────────────
$cols = [];
$colQ = mysqli_query($conn, "SHOW COLUMNS FROM trade_logs");
if ($colQ) {
    while ($c = mysqli_fetch_assoc($colQ)) $cols[] = $c['Field'];
}

$has_pnl      = in_array('pnl_amount', $cols);
$has_day_type = in_array('day_type',   $cols);
$has_rate     = in_array('rate',       $cols);
$has_position = in_array('position',   $cols);
$has_cat      = in_array('created_at', $cols);
$has_date     = in_array('date',       $cols);

$date_sel     = $has_cat  ? "created_at" : ($has_date ? "date AS created_at" : "NOW() AS created_at");
$pnl_sel      = $has_pnl      ? "pnl_amount"  : "0 AS pnl_amount";
$day_sel      = $has_day_type ? "day_type"     : "'profit' AS day_type";
$rate_sel     = $has_rate     ? "rate"         : "0 AS rate";
$pos_sel      = $has_position ? "position"     : "'BUY' AS position";

// ── 5. Fetch trade logs ───────────────────────────────────
$logQ = mysqli_query($conn,
    "SELECT id, amount, $pnl_sel, $rate_sel, $day_sel, $pos_sel, $date_sel
     FROM trade_logs
     WHERE wallet = '$wallet'
     ORDER BY id DESC
     LIMIT 100"
);

$logs       = [];
$net_pnl    = 0;
$total_profit = 0;
$total_loss   = 0;
$profit_count = 0;
$loss_count   = 0;
$buy_count    = 0;
$sell_count   = 0;

if ($logQ) {
    while ($row = mysqli_fetch_assoc($logQ)) {
        $amt       = floatval($row['amount']     ?? 0);
        $pnl       = floatval($row['pnl_amount'] ?? 0);
        $stored_rate = floatval($row['rate']     ?? 0);
        $day_type  = $row['day_type'] ?? 'profit';
        $position  = $row['position'] ?? 'BUY';

        // ── Correct the rate ────────────────────────────
        // If stored rate looks like decimal (0.04) convert to percent
        // If 0 or missing, use user's personal rate
        $display_rate = $user_trade_rate;
        if ($stored_rate > 0) {
            if ($stored_rate < 1) {
                // Stored as decimal e.g. 0.04 → 4%
                $display_rate = round($stored_rate * 100, 2);
            } else {
                // Stored as percent e.g. 4.0 → 4%
                $display_rate = round($stored_rate, 2);
            }
        }

        // ── Recalculate pnl if stored value is 0 ────────
        // pnl_amount should be signed: positive = profit, negative = loss
        if ($pnl == 0 && $amt > 0) {
            $calculated_pnl = $amt * ($display_rate / 100);
            $pnl = ($day_type === 'loss') ? -$calculated_pnl : $calculated_pnl;
        }

        // Ensure sign matches day_type
        if ($day_type === 'loss' && $pnl > 0) $pnl = -$pnl;
        if ($day_type === 'profit' && $pnl < 0) $pnl = abs($pnl);

        // Stats
        $net_pnl += $pnl;
        if ($pnl > 0) { $total_profit += $pnl; $profit_count++; }
        elseif ($pnl < 0) { $total_loss += abs($pnl); $loss_count++; }
        if ($position === 'BUY') $buy_count++;
        else $sell_count++;

        // Format date
        $date_raw = $row['created_at'] ?? '';
        try {
            $d_fmt = date('d M Y, h:i A', strtotime($date_raw));
        } catch (Exception $e) {
            $d_fmt = $date_raw;
        }

        $logs[] = [
            'id'         => $row['id'],
            'position'   => $position,
            'amount'     => round($amt, 4),
            'pnl_amount' => round($pnl, 4),     // ✅ SIGNED: positive=profit, negative=loss
            'rate'       => $display_rate,        // ✅ User's personal rate in %
            'day_type'   => $day_type,            // ✅ profit / loss
            'created_at' => $d_fmt,
        ];
    }
}

// ── 6. Check for active trade (not yet logged) ────────────
// We can't know this from DB alone — frontend handles it via localStorage
// But we return a flag if needed

// ── 7. Summary ────────────────────────────────────────────
$summary = [
    'total_investment' => $total_inv,
    'user_trade_rate'  => $user_trade_rate,
    'net_pnl'          => round($net_pnl, 4),
    'total_profit'     => round($total_profit, 4),
    'total_loss'       => round($total_loss, 4),
    'profit_count'     => $profit_count,
    'loss_count'       => $loss_count,
    'buy_count'        => $buy_count,
    'sell_count'       => $sell_count,
    'total_trades'     => count($logs),
];

echo json_encode([
    "status"       => "success",
    "summary"      => $summary,
    "logs"         => $logs,
    "active_trade" => null, // frontend handles active state via localStorage
]);
?>