<?php
session_start();
require_once "../include/db.php";

if (!isset($_SESSION['user_id'])) exit;

$userId = intval($_SESSION['user_id']);
$limit = intval($_GET['limit'] ?? 10);

$sql = "SELECT * FROM trades WHERE user_id = $userId ORDER BY created_at DESC LIMIT $limit";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) === 0) {
    echo '<div class="p-8 text-center text-slate-500 dark:text-slate-400 text-sm">No trades yet. Start trading!</div>';
    exit;
}
?>

<table class="w-full text-left text-xs">
    <thead class="text-[10px] text-slate-500 dark:text-slate-400 uppercase bg-slate-50 dark:bg-slate-800/50">
        <tr>
            <th class="px-4 py-3 border-b border-slate-200 dark:border-slate-700">Asset</th>
            <th class="px-4 py-3 border-b border-slate-200 dark:border-slate-700">Type</th>
            <th class="px-4 py-3 border-b border-slate-200 dark:border-slate-700">Amount</th>
            <th class="px-4 py-3 border-b border-slate-200 dark:border-slate-700">P&L</th>
            <th class="px-4 py-3 border-b border-slate-200 dark:border-slate-700 text-right">Status</th>
        </tr>
    </thead>
    <tbody class="divide-y divide-slate-100 dark:divide-slate-800/50">
        <?php while ($trade = mysqli_fetch_assoc($result)): 
            $isWin = $trade['status'] === 'WIN';
            $pnlClass = $isWin ? 'text-emerald-500' : ($trade['status'] === 'LOSS' ? 'text-rose-500' : 'text-amber-500');
            $badgeClass = $isWin ? 'badge-win' : ($trade['status'] === 'LOSS' ? 'badge-loss' : 'badge-pending');
            $pnlSign = $trade['pnl'] >= 0 ? '+' : '';
        ?>
        <tr class="hover:bg-slate-50 dark:hover:bg-slate-800/20 transition-colors">
            <td class="px-4 py-3 font-medium text-slate-900 dark:text-slate-200">
                <div class="flex items-center gap-2">
                    <span class="w-1.5 h-1.5 rounded-full <?= $isWin ? 'bg-emerald-500' : 'bg-rose-500' ?>"></span>
                    <?= htmlspecialchars($trade['asset']) ?>
                </div>
            </td>
            <td class="px-4 py-3">
                <span class="<?= $trade['trade_type'] === 'BUY' ? 'text-emerald-500' : 'text-rose-500' ?> font-bold text-[10px] px-2 py-0.5 rounded bg-slate-100 dark:bg-slate-800">
                    <?= $trade['trade_type'] ?>
                </span>
            </td>
            <td class="px-4 py-3 text-slate-700 dark:text-slate-300 font-mono">$<?= number_format($trade['amount'], 2) ?></td>
            <td class="px-4 py-3 <?= $pnlClass ?> font-bold font-mono"><?= $pnlSign ?>$<?= number_format(abs($trade['pnl']), 2) ?></td>
            <td class="px-4 py-3 text-right">
                <span class="<?= $badgeClass ?> text-[10px] font-bold px-2.5 py-1 rounded-full">
                    <?= $trade['status'] ?>
                </span>
            </td>
        </tr>
        <?php endwhile; ?>
    </tbody>
</table>