<?php
session_start();
header('Content-Type: application/json');

require_once "../include/db.php";

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['html' => '', 'count' => 0]);
    exit;
}

$userId = intval($_SESSION['user_id']);
$now = date('Y-m-d H:i:s');

// First, update any 'pending' trades that should now be 'running'
// (Pending for 3 seconds then becomes running - simulates order processing)
mysqli_query($conn, "UPDATE trades SET status = 'running' 
    WHERE user_id = $userId AND status = 'pending' 
    AND created_at <= DATE_SUB(NOW(), INTERVAL 3 SECOND)");

// Check for expired trades and settle them
$expiredSql = "SELECT * FROM trades 
    WHERE user_id = $userId AND status = 'running' 
    AND expires_at <= NOW()";
$expiredResult = mysqli_query($conn, $expiredSql);

while ($trade = mysqli_fetch_assoc($expiredResult)) {
    settleTrade($trade, $conn);
}

// Now fetch all active positions (pending + running)
$sql = "SELECT * FROM trades 
    WHERE user_id = $userId AND status IN ('pending', 'running') 
    ORDER BY created_at DESC";
$result = mysqli_query($conn, $sql);

$activeTrades = [];
while ($row = mysqli_fetch_assoc($result)) {
    $activeTrades[] = $row;
}

// Build HTML
ob_start();
if (empty($activeTrades)): ?>
    <div class="p-8 text-center text-slate-500">
        <div class="flex flex-col items-center gap-2">
            <div class="w-12 h-12 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center mb-2">
                <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="text-slate-400"><path d="M12 2v4m0 12v4M4.93 4.93l2.83 2.83m8.48 8.48l2.83 2.83M2 12h4m12 0h4M4.93 19.07l2.83-2.83m8.48-8.48l2.83-2.83"/></svg>
            </div>
            <p class="text-sm">No active positions</p>
            <p class="text-xs text-slate-400">Place a trade to get started</p>
        </div>
    </div>
<?php else: ?>
    <div class="divide-y divide-slate-200 dark:divide-slate-700/50">
        <?php foreach ($activeTrades as $trade): 
            $isPending = $trade['status'] === 'pending';
            $tradeType = strtoupper($trade['trade_type']);
            $typeColor = $tradeType === 'BUY' ? 'text-emerald-500' : 'text-rose-500';
            $typeBg = $tradeType === 'BUY' ? 'bg-emerald-500/10' : 'bg-rose-500/10';
            $typeBorder = $tradeType === 'BUY' ? 'border-emerald-500/20' : 'border-rose-500/20';
            
            // Calculate remaining time
            $expires = strtotime($trade['expires_at']);
            $now_ts = time();
            $remaining = max(0, $expires - $now_ts);
            $duration = intval($trade['duration']) * 60;
            $elapsed = $duration - $remaining;
            $progress = $duration > 0 ? min(100, ($elapsed / $duration) * 100) : 0;
        ?>
        <div class="p-4 hover:bg-slate-50 dark:hover:bg-slate-800/50 transition-colors position-card" data-trade-id="<?= $trade['id'] ?>">
            <div class="flex items-center justify-between mb-3">
                <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-xl <?= $typeBg ?> border <?= $typeBorder ?> flex items-center justify-center">
                        <span class="text-xs font-bold <?= $typeColor ?>"><?= $tradeType ?></span>
                    </div>
                    <div>
                        <div class="text-sm font-bold text-slate-900 dark:text-white"><?= htmlspecialchars($trade['asset']) ?></div>
                        <div class="text-xs text-slate-500">$<?= number_format($trade['amount'], 2) ?> • <?= $trade['duration'] ?>min</div>
                    </div>
                </div>
                <div class="text-right">
                    <?php if ($isPending): ?>
                    <span class="px-2 py-1 bg-amber-500/10 text-amber-500 text-[10px] font-bold rounded-full border border-amber-500/20 flex items-center gap-1">
                        <span class="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse"></span> PENDING
                    </span>
                    <?php else: ?>
                    <span class="px-2 py-1 bg-theme/10 text-theme text-[10px] font-bold rounded-full border border-theme/20 timer-active flex items-center gap-1">
                        <span class="w-1.5 h-1.5 rounded-full bg-theme animate-pulse"></span> RUNNING
                    </span>
                    <?php endif; ?>
                </div>
            </div>
            
            <?php if (!$isPending): ?>
            <div class="space-y-2">
                <div class="flex justify-between text-xs">
                    <span class="text-slate-500">Time Remaining</span>
                    <span class="font-mono font-bold text-theme" id="timer-<?= $trade['id'] ?>">
                        <?= floor($remaining / 60) ?>:<?= str_pad($remaining % 60, 2, '0', STR_PAD_LEFT) ?>
                    </span>
                </div>
                <div class="w-full bg-slate-200 dark:bg-slate-700 rounded-full h-2 overflow-hidden">
                    <div id="progress-<?= $trade['id'] ?>" class="bg-theme h-2 rounded-full transition-all duration-1000" style="width: <?= $progress ?>%"></div>
                </div>
                <div class="flex justify-between text-xs mt-1">
                    <span class="text-slate-500">Entry: <span class="font-mono text-slate-700 dark:text-slate-300">$<?= number_format($trade['entry_price'], 4) ?></span></span>
                    <span class="text-slate-500">Current: <span class="font-mono text-theme" id="current-<?= $trade['id'] ?>">--</span></span>
                </div>
            </div>
            <?php else: ?>
            <div class="mt-2">
                <div class="flex items-center gap-2 text-xs text-amber-500">
                    <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24" class="animate-spin"><path d="M12 2v4m0 12v4M4.93 4.93l2.83 2.83m8.48 8.48l2.83 2.83M2 12h4m12 0h4M4.93 19.07l2.83-2.83m8.48-8.48l2.83-2.83"/></svg>
                    Processing order...
                </div>
            </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>
<?php endif;

$html = ob_get_clean();
echo json_encode(['html' => $html, 'count' => count($activeTrades)]);

// Helper function to settle expired trades
function settleTrade($trade, $conn) {
    $tradeId = intval($trade['id']);
    $userId = intval($trade['user_id']);
    $amount = floatval($trade['amount']);
    
    // Get trading settings
    $settingsSql = "SELECT setting_name, setting_value FROM trading_settings";
    $settingsResult = mysqli_query($conn, $settingsSql);
    $settings = [];
    while ($row = mysqli_fetch_assoc($settingsResult)) {
        $settings[$row['setting_name']] = $row['setting_value'];
    }
    
    // Determine outcome (admin controlled or auto)
    $isWin = false;
    if (isset($settings['win_rate_enabled']) && $settings['win_rate_enabled'] == '1') {
        $winRate = intval($settings['admin_win_rate'] ?? 20);
        $isWin = mt_rand(1, 100) <= $winRate;
    } else {
        $isWin = mt_rand(1, 100) <= 20; // 20% default win rate
    }
    
    // Calculate exit price (small movement from entry)
    $entryPrice = floatval($trade['entry_price']);
    $exitPrice = $isWin ? $entryPrice * 1.002 : $entryPrice * 0.998;