<?php
/**
 * Trade History - Shows Binary and CFD trades
 */
$pageTitle = 'Trade History';
require_once 'includes/header.php';

$userId = $user['id'];
$currency = defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : '₹';

// Filter by trade type
$tradeTypeFilter = $_GET['type'] ?? 'all';
$accountFilter = $_GET['account'] ?? 'all';

// Get trades
$whereClause = "WHERE user_id = ?";
$params = [$userId];

if ($tradeTypeFilter !== 'all') {
    $whereClause .= " AND trade_type = ?";
    $params[] = $tradeTypeFilter;
}

if ($accountFilter !== 'all') {
    $whereClause .= " AND is_demo = ?";
    $params[] = ($accountFilter === 'demo') ? 1 : 0;
}

$trades = [];
try {
    $trades = dbFetchAll("SELECT t.*, a.name as asset_name FROM trades t LEFT JOIN assets a ON t.asset_id = a.id $whereClause ORDER BY t.created_at DESC LIMIT 100", $params);
} catch (Exception $e) {
    echo "<div class='alert alert-danger'>Error loading trades: " . htmlspecialchars($e->getMessage()) . "</div>";
    error_log("History Error: " . $e->getMessage());
}

// Calculate stats
$stats = ['total' => count($trades), 'won' => 0, 'lost' => 0, 'profit' => 0];
foreach ($trades as $trade) {
    if ($trade['result'] === 'won') {
        $stats['won']++;
        $stats['profit'] += (float)$trade['actual_profit'];
    } elseif ($trade['result'] === 'lost') {
        $stats['lost']++;
        $stats['profit'] -= (float)$trade['amount'];
    }
}
$winRate = $stats['total'] > 0 ? round(($stats['won'] / $stats['total']) * 100, 1) : 0;
?>

<div class="card">
    <div class="card-title" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:1rem">
        <span><i class="fas fa-history"></i> Trade History</span>
        <div style="display:flex;gap:.5rem">
            <select onchange="filterTrades('type', this.value)" style="padding:8px 12px;border-radius:8px;background:var(--bg-secondary);border:1px solid var(--border-color);color:var(--text-primary)">
                <option value="all" <?=$tradeTypeFilter==='all'?'selected':''?>>All Types</option>
                <option value="binary" <?=$tradeTypeFilter==='binary'?'selected':''?>>Binary</option>
                <option value="cfd" <?=$tradeTypeFilter==='cfd'?'selected':''?>>CFD</option>
            </select>
            <select onchange="filterTrades('account', this.value)" style="padding:8px 12px;border-radius:8px;background:var(--bg-secondary);border:1px solid var(--border-color);color:var(--text-primary)">
                <option value="all" <?=$accountFilter==='all'?'selected':''?>>All Accounts</option>
                <option value="demo" <?=$accountFilter==='demo'?'selected':''?>>Demo</option>
                <option value="real" <?=$accountFilter==='real'?'selected':''?>>Real</option>
            </select>
        </div>
    </div>
    
    <!-- Stats -->
    <div class="stats-grid" style="margin-bottom:1.5rem">
        <div class="stat-card">
            <div class="stat-label">Total Trades</div>
            <div class="stat-value"><?=$stats['total']?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">Won</div>
            <div class="stat-value green"><?=$stats['won']?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">Lost</div>
            <div class="stat-value red"><?=$stats['lost']?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">Win Rate</div>
            <div class="stat-value <?=$winRate>=50?'green':'red'?>"><?=$winRate?>%</div>
        </div>
    </div>
    
    <!-- Trades Table -->
    <div style="overflow-x:auto">
        <table style="width:100%;border-collapse:collapse">
            <thead>
                <tr style="background:var(--bg-secondary)">
                    <th style="padding:12px;text-align:left;border-bottom:1px solid var(--border-color)">Date</th>
                    <th style="padding:12px;text-align:left;border-bottom:1px solid var(--border-color)">Asset</th>
                    <th style="padding:12px;text-align:left;border-bottom:1px solid var(--border-color)">Type</th>
                    <th style="padding:12px;text-align:left;border-bottom:1px solid var(--border-color)">Direction</th>
                    <th style="padding:12px;text-align:right;border-bottom:1px solid var(--border-color)">Amount</th>
                    <th style="padding:12px;text-align:center;border-bottom:1px solid var(--border-color)">Result</th>
                    <th style="padding:12px;text-align:right;border-bottom:1px solid var(--border-color)">Profit</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($trades)): ?>
                <tr><td colspan="7" style="padding:40px;text-align:center;color:var(--text-muted)">No trades found</td></tr>
                <?php else: ?>
                <?php foreach ($trades as $trade): ?>
                <tr style="border-bottom:1px solid var(--border-color)">
                    <td style="padding:12px"><?=date('d M Y H:i', strtotime($trade['created_at']))?></td>
                    <td style="padding:12px"><?=htmlspecialchars($trade['asset_name'] ?? $trade['symbol'])?></td>
                    <td style="padding:12px"><span style="padding:4px 8px;border-radius:4px;background:<?=$trade['trade_type']==='binary'?'#3b82f6':'#8b5cf6'?>;font-size:.75rem"><?=ucfirst($trade['trade_type'])?></span></td>
                    <td style="padding:12px">
                        <span style="color:<?=in_array($trade['direction'],['up','buy'])?'var(--green)':'var(--red)'?>">
                            <i class="fas fa-arrow-<?=in_array($trade['direction'],['up','buy'])?'up':'down'?>"></i>
                            <?=strtoupper($trade['direction'])?>
                        </span>
                    </td>
                    <td style="padding:12px;text-align:right"><?=$currency?><?=number_format($trade['amount'],2)?></td>
                    <td style="padding:12px;text-align:center">
                        <?php if ($trade['result'] === 'won'): ?>
                            <span style="padding:4px 12px;border-radius:20px;background:rgba(0,208,156,0.1);color:var(--green);font-weight:600">WON</span>
                        <?php elseif ($trade['result'] === 'lost'): ?>
                            <span style="padding:4px 12px;border-radius:20px;background:rgba(255,71,87,0.1);color:var(--red);font-weight:600">LOST</span>
                        <?php else: ?>
                            <span style="padding:4px 12px;border-radius:20px;background:rgba(251,191,36,0.1);color:var(--accent-yellow);font-weight:600"><?=strtoupper($trade['result'])?></span>
                        <?php endif; ?>
                    </td>
                    <td style="padding:12px;text-align:right;font-weight:600;color:<?=($trade['actual_profit']??0)>=0?'var(--green)':'var(--red)'?>">
                        <?=($trade['actual_profit']??0)>=0?'+':''?><?=$currency?><?=number_format($trade['actual_profit']??0,2)?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
function filterTrades(type, value) {
    const url = new URL(window.location);
    url.searchParams.set(type, value);
    window.location = url;
}
</script>

<?php require_once 'includes/footer.php'; ?>
