<?php
// ══════════════════════════════════════════════════
// EPD — Admin Trade Logs API (FIXED v4)
// File: /backend/api/admin-trade-logs.php
//
// ✅ account_id se join — wallet mismatch issue GONE
// ✅ mysqli ($conn) use karta hai — PDO issue GONE
// ✅ Hamesha valid JSON return karta hai
// ══════════════════════════════════════════════════
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");

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

// ── Date param ──
$date = trim($_GET['date'] ?? date('Y-m-d'));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
    $date = date('Y-m-d');
}

try {

    if (!isset($conn) || !$conn) {
        throw new Exception('DB connection ($conn) not found in db.php');
    }

    // ── account_id column exist karta hai ya nahi check ──
    $colCheck     = mysqli_query($conn, "SHOW COLUMNS FROM trade_logs LIKE 'account_id'");
    $hasAccountId = mysqli_num_rows($colCheck) > 0;

    if ($hasAccountId) {
        // ✅ PREFERRED: account_id se direct join
        $sql = "
            SELECT
                tl.id,
                tl.account_id,
                tl.wallet,
                tl.position,
                tl.amount,
                tl.pnl_amount,
                tl.day_type,
                tl.rate,
                tl.created_at,
                u.name,
                u.mobile
            FROM trade_logs tl
            LEFT JOIN users u ON u.account_id = tl.account_id
            WHERE DATE(tl.created_at) = '$date'
            ORDER BY tl.created_at DESC
        ";
    } else {
        // Fallback: wallet se join
        $sql = "
            SELECT
                tl.id,
                '' AS account_id,
                TRIM(tl.wallet) AS wallet,
                tl.position,
                tl.amount,
                tl.pnl_amount,
                tl.day_type,
                tl.rate,
                tl.created_at,
                u.name,
                u.account_id AS u_account_id,
                u.mobile
            FROM trade_logs tl
            LEFT JOIN users u
                ON LOWER(TRIM(u.wallet)) = LOWER(TRIM(tl.wallet))
            WHERE DATE(tl.created_at) = '$date'
            ORDER BY tl.created_at DESC
        ";
    }

    $res = mysqli_query($conn, $sql);
    if (!$res) {
        throw new Exception('Query failed: ' . mysqli_error($conn));
    }

    $rows   = mysqli_fetch_all($res, MYSQLI_ASSOC);
    $result = [];

    foreach ($rows as $row) {
        $amt        = floatval($row['amount']     ?? 0);
        $pnl        = floatval($row['pnl_amount'] ?? 0);
        $storedRate = floatval($row['rate']       ?? 0);
        $day_type   = $row['day_type'] ?? 'profit';
        $account_id = $row['account_id'] ?: ($row['u_account_id'] ?? '');

        // ── Rate fix ──
        $display_rate = $storedRate;
        if ($storedRate > 0 && $storedRate < 1) {
            $display_rate = round($storedRate * 100, 2);
        }
        if ($display_rate <= 0) $display_rate = 4.0;

        // ── PnL fix ──
        if ($pnl == 0 && $amt > 0) {
            $pnl = $amt * ($display_rate / 100);
            if ($day_type === 'loss') $pnl = -$pnl;
        }

        // ── Sign fix ──
        if ($day_type === 'loss'   && $pnl > 0) $pnl = -$pnl;
        if ($day_type === 'profit' && $pnl < 0) $pnl = abs($pnl);

        $result[] = [
            'id'         => $row['id'],
            'account_id' => $account_id,
            'wallet'     => trim($row['wallet'] ?? ''),
            'position'   => $row['position'] ?? 'BUY',
            'amount'     => round($amt, 4),
            'pnl_amount' => round($pnl, 4),
            'rate'       => $display_rate,
            'day_type'   => $day_type,
            'created_at' => $row['created_at'] ?? '',
            'name'       => $row['name']   ?? '',
            'mobile'     => $row['mobile'] ?? '',
        ];
    }

    echo json_encode(array_values($result));

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}