<?php
include __DIR__ . '/includes/header.php';

if (!$user) {
    header('Location: /auth/login.php');
    exit;
}

$tab = $_GET['tab'] ?? 'all';
$db = db();

if ($tab === 'all') {
    // Combine transactions and trading orders
    $stmt = $db->prepare("SELECT type, amount, symbol, status, created_at, 'finance' as source, NULL as direction, NULL as pnl FROM transactions WHERE user_id = ? 
                          UNION ALL
                          SELECT 'binary' as type, amount, symbol, status, created_at, 'trading' as source, direction, (CASE WHEN status='won' THEN (amount * profit_rate / 100) WHEN status='lost' THEN -amount ELSE 0 END) as pnl FROM binary_orders WHERE user_id = ?
                          UNION ALL
                          SELECT 'contract' as type, amount, symbol, status, created_at, 'trading' as source, direction, profit as pnl FROM contract_orders WHERE user_id = ?
                          ORDER BY created_at DESC LIMIT 100");
    $stmt->execute([$user['id'], $user['id'], $user['id']]);
    $records = $stmt->fetchAll();
} else {
    if ($tab === 'binary') {
        $stmt = $db->prepare("SELECT 'binary' as type, amount, symbol, status, created_at, 'trading' as source, direction, (CASE WHEN status='won' THEN (amount * profit_rate / 100) WHEN status='lost' THEN -amount ELSE 0 END) as pnl FROM binary_orders WHERE user_id = ? ORDER BY created_at DESC LIMIT 100");
        $stmt->execute([$user['id']]);
    } elseif ($tab === 'contract') {
        $stmt = $db->prepare("SELECT 'contract' as type, amount, symbol, status, created_at, 'trading' as source, direction, profit as pnl FROM contract_orders WHERE user_id = ? ORDER BY created_at DESC LIMIT 100");
        $stmt->execute([$user['id']]);
    } elseif ($tab === 'spot') {
        $stmt = $db->prepare("SELECT 'spot' as type, amount, symbol, status, created_at, 'trading' as source, side as direction, 0 as pnl FROM spot_orders WHERE user_id = ? ORDER BY created_at DESC LIMIT 100");
        $stmt->execute([$user['id']]);
    } else {
        $stmt = $db->prepare("SELECT *, 'finance' as source, NULL as direction, NULL as pnl FROM transactions WHERE user_id = ? AND type LIKE ? ORDER BY created_at DESC LIMIT 100");
        $stmt->execute([$user['id'], $tab . '%']);
    }
    $records = $stmt->fetchAll();
}

$types_map = [
    'recharge' => ['name' => __('recharge'), 'color' => 'success'],
    'withdrawal' => ['name' => __('withdrawal'), 'color' => 'danger'],
    'binary' => ['name' => __('sec_contract'), 'color' => 'primary'],
    'contract' => ['name' => __('contract'), 'color' => 'warning'],
    'spot' => ['name' => __('spot'), 'color' => 'info'],
    'binary_win' => ['name' => __('binary_win'), 'color' => 'success'],
    'binary_loss' => ['name' => __('binary_loss'), 'color' => 'danger'],
];
?>

<div class="container py-5">
    <div class="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center gap-3 mb-4">
        <h2 class="fw-bold text-white mb-0"><?= __('orders') ?></h2>
        <div class="btn-group bg-dark p-1 rounded-3">
            <a href="?tab=all" class="btn btn-sm px-3 <?= $tab === 'all' ? 'btn-primary shadow' : 'text-white-50 border-0' ?>"><?= __('all') ?? 'All' ?></a>
            <a href="?tab=binary" class="btn btn-sm px-3 <?= $tab === 'binary' ? 'btn-primary shadow' : 'text-white-50 border-0' ?>"><?= __('sec_contract') ?></a>
            <a href="?tab=spot" class="btn btn-sm px-3 <?= $tab === 'spot' ? 'btn-primary shadow' : 'text-white-50 border-0' ?>"><?= __('spot') ?></a>
            <a href="?tab=contract" class="btn btn-sm px-3 <?= $tab === 'contract' ? 'btn-primary shadow' : 'text-white-50 border-0' ?>"><?= __('contract') ?></a>
        </div>
    </div>

    <div class="card bg-surface border-secondary rounded-4 overflow-hidden shadow-lg border-opacity-50">
        <div class="d-none d-md-block table-responsive">
            <table class="table table-dark table-hover mb-0 align-middle">
                <thead class="bg-black bg-opacity-50 text-white-50 small">
                    <tr>
                        <th class="ps-4 py-3 border-secondary"><?= __('type') ?></th>
                        <th class="py-3 border-secondary"><?= __('amount') ?>/<?= __('direction') ?></th>
                        <th class="py-3 border-secondary"><?= __('pnl') ?? 'PnL' ?></th>
                        <th class="py-3 border-secondary"><?= __('status') ?></th>
                        <th class="text-end pe-4 py-3 border-secondary"><?= __('time') ?></th>
                    </tr>
                </thead>
                <tbody class="border-0">
                    <?php if (empty($records)): ?>
                    <tr>
                        <td colspan="5" class="text-center py-5 text-muted opacity-50">
                            <i class="bi bi-inbox fs-1 d-block mb-3"></i>
                            <div class="fs-5"><?= __('no_records_found') ?></div>
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($records as $r): 
                            $typeKey = $r['type'];
                            $type = $types_map[$typeKey] ?? ['name' => __($typeKey), 'color' => 'secondary'];
                            $pnl = (float)($r['pnl'] ?? 0);
                        ?>
                        <tr class="border-secondary border-opacity-10">
                            <td class="ps-4 py-4">
                                <div class="d-flex align-items-center gap-3">
                                    <div class="bg-<?= $type['color'] ?> bg-opacity-10 text-<?= $type['color'] ?> rounded-circle d-flex align-items-center justify-content-center" style="width: 32px; height: 32px;">
                                        <i class="bi bi-<?= $typeKey === 'recharge' ? 'arrow-down-left' : ($typeKey === 'withdrawal' ? 'arrow-up-right' : 'activity') ?>"></i>
                                    </div>
                                    <div>
                                        <div class="text-white fw-bold"><?= $type['name'] ?></div>
                                        <div class="text-white-50 small"><?= $lang === 'zh' ? __($r['symbol']) : $r['symbol'] ?></div>
                                    </div>
                                </div>
                            </td>
                            <td class="py-4">
                                <div class="fw-bold text-white"><?= number_format($r['amount'], 2) ?></div>
                                <?php if ($r['direction']): 
                                    $dir = strtolower($r['direction']);
                                    $dirText = $dir;
                                    if ($dir === 'up') $dirText = __('buy_up');
                                    elseif ($dir === 'down') $dirText = __('buy_down');
                                    elseif ($dir === 'buy') $dirText = __('buy');
                                    elseif ($dir === 'sell') $dirText = __('sell');
                                    elseif ($dir === 'long') $dirText = __('long');
                                    elseif ($dir === 'short') $dirText = __('short');
                                ?>
                                    <div class="small <?= (strpos($dir, 'up') !== false || strpos($dir, 'long') !== false || strpos($dir, 'buy') !== false) ? 'text-success' : 'text-danger' ?>">
                                        <?= $dirText ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td class="py-4">
                                <?php if ($r['source'] === 'trading'): ?>
                                    <div class="fw-bold <?= $pnl >= 0 ? 'text-success' : 'text-danger' ?>">
                                        <?= $pnl >= 0 ? '+' : '' ?><?= number_format($pnl, 2) ?>
                                    </div>
                                <?php else: ?>
                                    <span class="text-white-50">--</span>
                                <?php endif; ?>
                            </td>
                            <td class="py-4">
                                <?php 
                                $status = strtolower($r['status']);
                                if ($status === 'completed' || $status === 'won' || $status === 'settled'): ?>
                                    <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 rounded-pill px-3 py-1">
                                        <i class="bi bi-check-circle-fill me-1"></i><?= __('completed') ?>
                                    </span>
                                <?php elseif ($status === 'lost' || $status === 4 || $status === 'cancelled'): ?>
                                    <span class="badge bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25 rounded-pill px-3 py-1">
                                        <i class="bi bi-x-circle-fill me-1"></i><?= __($status) ?>
                                    </span>
                                <?php else: ?>
                                    <span class="badge bg-warning bg-opacity-10 text-warning border border-warning border-opacity-25 rounded-pill px-3 py-1">
                                        <i class="bi bi-clock-fill me-1"></i><?= __(0) ?>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td class="text-end pe-4 py-4 text-white-50 small">
                                <?= date('Y-m-d H:i:s', strtotime($r['created_at'])) ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        <!-- Mobile Orders List -->
        <div class="d-md-none p-3">
            <?php if (empty($records)): ?>
                <div class="text-center py-5 text-muted opacity-50"><?= __('no_records_found') ?></div>
            <?php else: ?>
                <?php foreach ($records as $r): 
                    $typeKey = $r['type'];
                    $type = $types_map[$typeKey] ?? ['name' => __($typeKey), 'color' => 'secondary'];
                    $pnl = (float)($r['pnl'] ?? 0);
                    $status = strtolower($r['status']);
                    $statusClass = ($status === 'completed' || $status === 'won' || $status === 'settled') ? 'text-success' : (($status === 'lost' || $status === 4 || $status === 'cancelled') ? 'text-danger' : 'text-warning');
                ?>
                <div class="p-3 mb-3 rounded-4 bg-black bg-opacity-20 border border-secondary border-opacity-50">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div class="d-flex align-items-center gap-2">
                            <span class="badge bg-<?= $type['color'] ?> p-1 rounded-circle" style="width: 8px; height: 8px; padding: 0 !important;"></span>
                            <span class="text-white fw-bold small"><?= $type['name'] ?></span>
                            <span class="text-white-50 x-small"><?= $lang === 'zh' ? __($r['symbol']) : $r['symbol'] ?></span>
                        </div>
                        <span class="text-white-50 x-small"><?= date('m-d H:i', strtotime($r['created_at'])) ?></span>
                    </div>
                    <div class="d-flex justify-content-between align-items-end">
                        <div>
                            <div class="text-white fw-bold"><?= number_format($r['amount'], 2) ?></div>
                            <?php if ($r['direction']): 
                                $dir = strtolower($r['direction']);
                                $dirText = $dir === 'up' ? __('buy_up') : ($dir === 'down' ? __('buy_down') : ($dir === 'buy' ? __('buy') : ($dir === 'sell' ? __('sell') : ($dir === 'long' ? __('long') : __('short')))));
                            ?>
                                <div class="x-small <?= (strpos($dir, 'up') !== false || strpos($dir, 'long') !== false || strpos($dir, 'buy') !== false) ? 'text-success' : 'text-danger' ?>">
                                    <?= $dirText ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div class="text-end">
                            <?php if ($r['source'] === 'trading'): ?>
                                <div class="fw-bold <?= $pnl >= 0 ? 'text-success' : 'text-danger' ?> small">
                                    <?= $pnl >= 0 ? '+' : '' ?><?= number_format($pnl, 2) ?>
                                </div>
                            <?php endif; ?>
                            <div class="<?= $statusClass ?> x-small fw-bold"><?= __($status) ?></div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>
<style>
    .x-small { font-size: 11px; }
</style>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
