<?php
/**
 * Admin - Trade Management
 */

$pageTitle = 'Trade Management';
require_once 'includes/header.php';
require_once '../includes/TradingEngine.php';

// Handle actions
if (isPost()) {
    $action = post('action');
    $tradeId = (int)post('trade_id');
    
    if (!verifyCsrfToken(post('csrf_token'))) {
        jsonError('Invalid request');
    }
    
    switch ($action) {
        case 'override':
            $result = post('result');
            if (!in_array($result, ['won', 'lost'])) {
                jsonError('Invalid result');
            }
            
            $trade = dbFetch("SELECT * FROM trades WHERE id = :id", ['id' => $tradeId]);
            if (!$trade) {
                jsonError('Trade not found');
            }
            
            if ($trade['result'] !== 'pending') {
                jsonError('Trade already closed');
            }
            
            dbUpdate('trades', [
                'admin_override' => 1,
                'override_result' => $result,
                'override_by' => auth()->getAdminId()
            ], 'id = :id', ['id' => $tradeId]);
            
            logActivity('admin', auth()->getAdminId(), 'trade_override', "Set trade #{$tradeId} to {$result}");
            jsonSuccess("Trade will be marked as {$result} when it expires");
            break;
            
        case 'close_now':
            $trade = dbFetch("SELECT * FROM trades WHERE id = :id", ['id' => $tradeId]);
            if (!$trade) {
                jsonError('Trade not found');
            }
            
            if ($trade['result'] !== 'pending') {
                jsonError('Trade already closed');
            }
            
            // Update end time to now
            dbUpdate('trades', ['end_time' => date('Y-m-d H:i:s')], 'id = :id', ['id' => $tradeId]);
            
            // Close the trade
            $trade['end_time'] = date('Y-m-d H:i:s');
            $closeResult = trading()->closeTrade($trade);
            
            if ($closeResult['success']) {
                logActivity('admin', auth()->getAdminId(), 'trade_close', "Closed trade #{$tradeId} early");
                jsonSuccess("Trade closed with result: {$closeResult['result']}");
            } else {
                jsonError($closeResult['error']);
            }
            break;
            
        default:
            jsonError('Invalid action');
    }
}

// Get filters
$status = get('status', '');
$symbol = get('symbol', '');
$userId = get('user_id', '');
$dateFrom = get('date_from', '');
$dateTo = get('date_to', '');
$page = max(1, (int)get('page', 1));
$perPage = 50;

// Build query
$where = "1=1";
$params = [];

if ($status) {
    $where .= " AND t.result = :status";
    $params['status'] = $status;
}

if ($symbol) {
    $where .= " AND t.symbol = :symbol";
    $params['symbol'] = $symbol;
}

if ($userId) {
    $where .= " AND t.user_id = :user_id";
    $params['user_id'] = $userId;
}

if ($dateFrom) {
    $where .= " AND DATE(t.created_at) >= :date_from";
    $params['date_from'] = $dateFrom;
}

if ($dateTo) {
    $where .= " AND DATE(t.created_at) <= :date_to";
    $params['date_to'] = $dateTo;
}

$total = dbFetch("SELECT COUNT(*) as count FROM trades t WHERE {$where}", $params)['count'];
$pagination = paginate($total, $perPage, $page, 'trades.php');

$trades = dbFetchAll(
    "SELECT t.*, u.email, u.first_name, u.user_id as user_code, a.name as asset_name
     FROM trades t 
     LEFT JOIN users u ON t.user_id = u.id 
     LEFT JOIN assets a ON t.asset_id = a.id
     WHERE {$where}
     ORDER BY t.created_at DESC
     LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}",
    $params
);

// Get assets for filter
$assets = dbFetchAll("SELECT symbol, name FROM assets ORDER BY sort_order");

// Get summary stats
$summary = dbFetch(
    "SELECT 
        COUNT(*) as total_trades,
        SUM(CASE WHEN result = 'won' THEN 1 ELSE 0 END) as won,
        SUM(CASE WHEN result = 'lost' THEN 1 ELSE 0 END) as lost,
        SUM(CASE WHEN result = 'pending' THEN 1 ELSE 0 END) as pending,
        SUM(amount) as total_volume,
        SUM(CASE WHEN result = 'won' THEN actual_profit ELSE 0 END) as total_payouts,
        SUM(CASE WHEN result = 'lost' THEN amount ELSE 0 END) as total_losses
     FROM trades t WHERE {$where} AND is_demo = 0",
    $params
);
?>

<style>
.trade-stats {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 1rem;
    margin-bottom: 1.5rem;
}

@media (max-width: 1200px) {
    .trade-stats { grid-template-columns: repeat(3, 1fr); }
}

@media (max-width: 768px) {
    .trade-stats { grid-template-columns: repeat(2, 1fr); }
}

.trade-stat {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-md);
    padding: 1rem;
    text-align: center;
}

.trade-stat-value {
    font-size: 1.5rem;
    font-weight: 700;
    font-family: var(--font-mono);
}

.trade-stat-label {
    font-size: 0.75rem;
    color: var(--text-muted);
    text-transform: uppercase;
}

.direction-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.25rem 0.5rem;
    border-radius: var(--radius-sm);
    font-size: 0.75rem;
    font-weight: 600;
}

.direction-badge.up {
    background: rgba(0, 208, 156, 0.15);
    color: var(--accent-green);
}

.direction-badge.down {
    background: rgba(255, 82, 82, 0.15);
    color: var(--accent-red);
}

.trade-timer {
    font-family: var(--font-mono);
    font-size: 0.875rem;
}

.override-badge {
    font-size: 0.65rem;
    background: var(--accent-yellow);
    color: #000;
    padding: 0.1rem 0.3rem;
    border-radius: 2px;
    margin-left: 0.25rem;
}
</style>

<!-- Summary Stats -->
<div class="trade-stats">
    <div class="trade-stat">
        <div class="trade-stat-value"><?= number_format($summary['total_trades'] ?? 0) ?></div>
        <div class="trade-stat-label">Total Trades</div>
    </div>
    <div class="trade-stat">
        <div class="trade-stat-value text-green"><?= number_format($summary['won'] ?? 0) ?></div>
        <div class="trade-stat-label">Won Trades</div>
    </div>
    <div class="trade-stat">
        <div class="trade-stat-value text-red"><?= number_format($summary['lost'] ?? 0) ?></div>
        <div class="trade-stat-label">Lost Trades</div>
    </div>
    <div class="trade-stat">
        <div class="trade-stat-value"><?= formatCurrency($summary['total_volume'] ?? 0) ?></div>
        <div class="trade-stat-label">Trading Volume</div>
    </div>
    <div class="trade-stat">
        <?php $platformProfit = ($summary['total_losses'] ?? 0) - ($summary['total_payouts'] ?? 0); ?>
        <div class="trade-stat-value <?= $platformProfit >= 0 ? 'text-green' : 'text-red' ?>">
            <?= formatCurrency(abs($platformProfit)) ?>
        </div>
        <div class="trade-stat-label">Platform <?= $platformProfit >= 0 ? 'Profit' : 'Loss' ?></div>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <form class="filters-bar d-flex gap-2 flex-wrap" method="GET">
            <select name="status" class="form-control form-select" style="width: auto;">
                <option value="">All Results</option>
                <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
                <option value="won" <?= $status === 'won' ? 'selected' : '' ?>>Won</option>
                <option value="lost" <?= $status === 'lost' ? 'selected' : '' ?>>Lost</option>
                <option value="tie" <?= $status === 'tie' ? 'selected' : '' ?>>Tie</option>
            </select>
            
            <select name="symbol" class="form-control form-select" style="width: auto;">
                <option value="">All Assets</option>
                <?php foreach ($assets as $asset): ?>
                <option value="<?= $asset['symbol'] ?>" <?= $symbol === $asset['symbol'] ? 'selected' : '' ?>>
                    <?= $asset['name'] ?> (<?= $asset['symbol'] ?>)
                </option>
                <?php endforeach; ?>
            </select>
            
            <input type="date" name="date_from" class="form-control" value="<?= $dateFrom ?>" style="width: auto;">
            <input type="date" name="date_to" class="form-control" value="<?= $dateTo ?>" style="width: auto;">
            
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-search"></i> Filter
            </button>
            <a href="trades.php" class="btn btn-secondary">
                <i class="fas fa-times"></i> Clear
            </a>
        </form>
    </div>
</div>

<!-- Trades Table -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">Trades (<?= number_format($total) ?>)</h3>
        <div class="d-flex gap-2">
            <button class="btn btn-sm btn-secondary" onclick="location.reload()">
                <i class="fas fa-sync"></i> Refresh
            </button>
            <button class="btn btn-sm btn-primary" onclick="exportTrades()">
                <i class="fas fa-download"></i> Export
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>Trade ID</th>
                        <th>User</th>
                        <th>Asset</th>
                        <th>Direction</th>
                        <th>Amount</th>
                        <th>Entry/Exit</th>
                        <th>Payout</th>
                        <th>Result</th>
                        <th>Time</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($trades as $trade): ?>
                    <tr id="trade-<?= $trade['id'] ?>">
                        <td>
                            <div class="font-mono font-semibold"><?= $trade['trade_id'] ?></div>
                            <?php if ($trade['is_demo']): ?>
                            <span class="badge badge-info">Demo</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div><?= htmlspecialchars($trade['first_name'] ?? 'N/A') ?></div>
                            <div class="text-muted" style="font-size: 0.75rem;"><?= $trade['user_code'] ?></div>
                        </td>
                        <td>
                            <div class="font-semibold"><?= $trade['asset_name'] ?></div>
                            <div class="text-muted" style="font-size: 0.75rem;"><?= $trade['symbol'] ?></div>
                        </td>
                        <td>
                            <span class="direction-badge <?= $trade['direction'] ?>">
                                <i class="fas fa-arrow-<?= $trade['direction'] ?>"></i>
                                <?= strtoupper($trade['direction']) ?>
                            </span>
                        </td>
                        <td class="font-mono"><?= formatCurrency($trade['amount']) ?></td>
                        <td>
                            <div class="font-mono"><?= number_format($trade['entry_price'], 8) ?></div>
                            <?php if ($trade['exit_price']): ?>
                            <div class="font-mono text-muted" style="font-size: 0.75rem;">
                                → <?= number_format($trade['exit_price'], 8) ?>
                            </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div><?= formatPercent($trade['payout_percent']) ?></div>
                            <?php if ($trade['result'] === 'won'): ?>
                            <div class="text-green" style="font-size: 0.75rem;">
                                +<?= formatCurrency($trade['actual_profit']) ?>
                            </div>
                            <?php elseif ($trade['result'] === 'lost'): ?>
                            <div class="text-red" style="font-size: 0.75rem;">
                                -<?= formatCurrency($trade['amount']) ?>
                            </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php
                            $resultClasses = ['won' => 'success', 'lost' => 'danger', 'pending' => 'warning', 'tie' => 'info'];
                            $resultClass = $resultClasses[$trade['result']] ?? 'secondary';
                            ?>
                            <span class="badge badge-<?= $resultClass ?>">
                                <?= ucfirst($trade['result']) ?>
                            </span>
                            <?php if ($trade['admin_override']): ?>
                            <span class="override-badge">OVERRIDE</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div><?= formatDateTime($trade['start_time'], 'H:i:s') ?></div>
                            <div class="text-muted" style="font-size: 0.75rem;">
                                <?= formatDate($trade['created_at']) ?>
                            </div>
                            <?php if ($trade['result'] === 'pending'): ?>
                            <div class="trade-timer text-yellow" data-end="<?= $trade['end_time'] ?>">
                                --:--
                            </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($trade['result'] === 'pending'): ?>
                            <div class="d-flex gap-1">
                                <button class="btn btn-sm btn-success" onclick="overrideTrade(<?= $trade['id'] ?>, 'won')" title="Set to Win">
                                    <i class="fas fa-trophy"></i>
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="overrideTrade(<?= $trade['id'] ?>, 'lost')" title="Set to Lose">
                                    <i class="fas fa-times"></i>
                                </button>
                                <button class="btn btn-sm btn-secondary" onclick="closeTradeNow(<?= $trade['id'] ?>)" title="Close Now">
                                    <i class="fas fa-stop"></i>
                                </button>
                            </div>
                            <?php else: ?>
                            <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($trades)): ?>
                    <tr>
                        <td colspan="10" class="text-center text-muted py-4">No trades found</td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php if ($total > $perPage): ?>
    <div class="card-footer">
        <?= $pagination['html'] ?>
    </div>
    <?php endif; ?>
</div>

<script>
// Update countdown timers
function updateTimers() {
    document.querySelectorAll('.trade-timer').forEach(timer => {
        const endTime = new Date(timer.dataset.end).getTime();
        const now = Date.now();
        const diff = Math.max(0, Math.floor((endTime - now) / 1000));
        
        if (diff <= 0) {
            timer.textContent = 'Expired';
            timer.classList.remove('text-yellow');
            timer.classList.add('text-red');
        } else {
            const mins = Math.floor(diff / 60);
            const secs = diff % 60;
            timer.textContent = `${mins}:${secs.toString().padStart(2, '0')}`;
        }
    });
}

setInterval(updateTimers, 1000);
updateTimers();

function overrideTrade(tradeId, result) {
    const action = result === 'won' ? 'make this trade WIN' : 'make this trade LOSE';
    if (confirm(`Are you sure you want to ${action}?`)) {
        ajaxRequest('trades.php', {
            action: 'override',
            trade_id: tradeId,
            result: result,
            csrf_token: '<?= generateCsrfToken() ?>'
        }, function(response) {
            if (response.success) {
                showToast(response.message);
                location.reload();
            } else {
                showToast(response.error, 'danger');
            }
        });
    }
}

function closeTradeNow(tradeId) {
    if (confirm('Are you sure you want to close this trade now? The result will be determined by current price.')) {
        ajaxRequest('trades.php', {
            action: 'close_now',
            trade_id: tradeId,
            csrf_token: '<?= generateCsrfToken() ?>'
        }, function(response) {
            if (response.success) {
                showToast(response.message);
                location.reload();
            } else {
                showToast(response.error, 'danger');
            }
        });
    }
}

function exportTrades() {
    window.location.href = 'export.php?type=trades&<?= http_build_query($_GET) ?>';
}

// Auto-refresh every 30 seconds
setInterval(() => {
    if (document.querySelector('.trade-timer')) {
        // Only refresh if there are pending trades
        // location.reload();
    }
}, 30000);
</script>

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