<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require 'config/db.php';

if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit(); }
$user_id = $_SESSION['user_id'];

try {
    // সেটিংস থেকে কারেন্সি আনা
    $stmt_set = $pdo->query("SELECT currency FROM settings LIMIT 1");
    $settings = $stmt_set->fetch();
    $currency = $settings['currency'] ?? '৳';

    $stmt_user = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt_user->execute([$user_id]);
    $user = $stmt_user->fetch();

    $status_filter = $_GET['status'] ?? 'all';
    $fee_filter = $_GET['fee'] ?? 'all';

    $query = "SELECT t.*, (SELECT COUNT(*) FROM tournament_participants tp WHERE tp.tournament_id = t.id) as joined_count FROM tournaments t WHERE 1=1";
    $params = [];

    if ($status_filter !== 'all') {
        $query .= " AND t.status = ?";
        $params[] = $status_filter;
    } else {
        $query .= " AND t.status != 'ended'"; 
    }

    if ($fee_filter === 'free') { $query .= " AND t.entry_fee = 0"; }
    elseif ($fee_filter === 'paid') { $query .= " AND t.entry_fee > 0"; }

    $query .= " ORDER BY (t.status = 'live') DESC, t.start_time ASC"; 
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $tournaments = $stmt->fetchAll();

    $joined_stmt = $pdo->prepare("SELECT tournament_id FROM tournament_participants WHERE user_id = ?");
    $joined_stmt->execute([$user_id]);
    $my_joined = $joined_stmt->fetchAll(PDO::FETCH_COLUMN);

} catch (PDOException $e) { error_log($e->getMessage()); }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Tournaments - Ludo Pro</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        body { background: #020617; color: #f1f5f9; font-family: 'Rajdhani', sans-serif; background-image: radial-gradient(circle at 50% 0%, #1e1b4b 0%, #020617 70%); }
        .glass-card { background: rgba(30, 41, 59, 0.4); backdrop-filter: blur(12px); border: 1px solid rgba(255,255,255,0.05); }
        .nav-btn { color: #64748b; transition: all 0.3s; }
        .nav-btn.active { color: #3b82f6; text-shadow: 0 0 10px rgba(59, 130, 246, 0.5); }
        .no-scrollbar::-webkit-scrollbar { display: none; }
    </style>
</head>
<body class="pb-24 antialiased">

    <header class="p-5 flex justify-between items-center sticky top-0 z-40 bg-[#020617]/80 backdrop-blur-md">
        <button onclick="location.href='dashboard.php'" class="w-10 h-10 rounded-xl glass-card flex items-center justify-center text-slate-300 active:scale-95">
            <i class="fas fa-arrow-left"></i>
        </button>
        <h2 class="text-xl font-bold tracking-wide uppercase">Tournaments</h2>
        <div class="flex items-center gap-2 bg-blue-600/10 px-3 py-1.5 rounded-full border border-blue-500/20">
            <span class="text-xs font-bold text-blue-400"><?= $currency ?><?= number_format($user['balance'] + $user['win_balance'], 2) ?></span>
        </div>
    </header>

    <div class="max-w-md mx-auto px-5 mt-4 space-y-6">

        <div class="flex gap-2 overflow-x-auto no-scrollbar">
            <a href="tournaments.php?status=all" class="px-6 py-2.5 rounded-xl text-xs font-bold uppercase tracking-widest transition whitespace-nowrap <?= $status_filter == 'all' ? 'bg-blue-600 text-white shadow-lg shadow-blue-600/30' : 'glass-card text-slate-400' ?>">All Match</a>
            <a href="tournaments.php?status=live" class="px-6 py-2.5 rounded-xl text-xs font-bold uppercase tracking-widest transition whitespace-nowrap <?= $status_filter == 'live' ? 'bg-red-600 text-white shadow-lg shadow-red-600/30' : 'glass-card text-slate-400' ?>">Live</a>
            <a href="tournaments.php?status=open" class="px-6 py-2.5 rounded-xl text-xs font-bold uppercase tracking-widest transition whitespace-nowrap <?= $status_filter == 'open' ? 'bg-green-600 text-white shadow-lg shadow-green-600/30' : 'glass-card text-slate-400' ?>">Upcoming</a>
        </div>

        <form action="">
            <input type="hidden" name="status" value="<?= $status_filter ?>">
            <select name="fee" onchange="this.form.submit()" class="w-full bg-slate-900/50 border border-white/5 text-slate-300 text-xs font-bold py-4 px-4 rounded-2xl outline-none focus:border-blue-500/50">
                <option value="all">All Entry Fees</option>
                <option value="free" <?= $fee_filter == 'free' ? 'selected' : '' ?>>Free Entry</option>
                <option value="paid" <?= $fee_filter == 'paid' ? 'selected' : '' ?>>Paid Entry</option>
            </select>
        </form>

        <div class="space-y-6">
            <?php foreach($tournaments as $t): 
                $is_joined = in_array($t['id'], $my_joined);
                $is_full = $t['joined_count'] >= $t['max_players'];
                $progress = ($t['joined_count'] / $t['max_players']) * 100;
            ?>
            <div class="glass-card rounded-[2.5rem] overflow-hidden border-t border-white/10 shadow-2xl relative">
                
                <?php if($t['status'] == 'live'): ?>
                    <div class="absolute top-5 right-6 z-10 flex items-center gap-1.5 bg-red-600 px-3 py-1 rounded-full text-[10px] font-black uppercase tracking-tighter animate-pulse shadow-lg shadow-red-600/40">
                        <span class="w-1.5 h-1.5 bg-white rounded-full"></span> Live
                    </div>
                <?php endif; ?>

                <div class="p-6">
                    <div class="flex items-center gap-4 mb-5">
                        <div class="w-16 h-16 rounded-3xl bg-gradient-to-br from-blue-600 to-indigo-700 flex items-center justify-center shadow-lg shadow-blue-600/20">
                            <i class="fas fa-trophy text-2xl text-white"></i>
                        </div>
                        <div>
                            <h3 class="text-xl font-black text-white uppercase tracking-wide leading-none"><?= htmlspecialchars($t['title']) ?></h3>
                            <p class="text-[10px] font-bold text-slate-500 uppercase tracking-widest mt-2 flex items-center gap-2">
                                <i class="far fa-calendar-alt text-blue-500"></i>
                                <?= date('d M • h:i A', strtotime($t['start_time'])) ?>
                            </p>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-3 mb-6">
                        <div class="glass-card p-4 rounded-3xl text-center border-b-4 border-yellow-500/30">
                            <p class="text-[9px] text-slate-500 uppercase font-black tracking-[0.2em] mb-1">Prize Pool</p>
                            <p class="text-lg font-black text-white"><?= $currency ?><?= number_format($t['prize_pool']) ?></p>
                        </div>
                        <div class="glass-card p-4 rounded-3xl text-center border-b-4 border-green-500/30">
                            <p class="text-[9px] text-slate-500 uppercase font-black tracking-[0.2em] mb-1">Entry Fee</p>
                            <p class="text-lg font-black text-white"><?= $t['entry_fee'] == 0 ? 'FREE' : $currency.number_format($t['entry_fee']) ?></p>
                        </div>
                    </div>

                    <div class="mb-6 px-1">
                        <div class="flex justify-between items-center text-[10px] font-bold uppercase tracking-widest mb-2">
                            <span class="text-slate-500">Total Joined</span>
                            <span class="<?= $is_full ? 'text-red-500' : 'text-blue-400' ?>"><?= $t['joined_count'] ?> / <?= $t['max_players'] ?></span>
                        </div>
                        <div class="w-full bg-slate-800/50 h-2 rounded-full border border-white/5">
                            <div class="h-full <?= $is_full ? 'bg-red-600' : 'bg-blue-600' ?> rounded-full shadow-[0_0_10px_rgba(59,130,246,0.5)] transition-all duration-1000" style="width: <?= $progress ?>%"></div>
                        </div>
                    </div>

                    <?php if ($t['status'] == 'live' && $is_joined): ?>
                        <button onclick="location.href='playmatch.php?id=<?= $t['id'] ?>'" class="w-full bg-gradient-to-r from-green-600 to-green-400 py-4 rounded-2xl font-black uppercase tracking-widest text-sm text-white shadow-xl shadow-green-600/20 active:scale-95 transition-all">
                           <i class="fas fa-play mr-2 animate-bounce"></i> Play Now
                        </button>
                    <?php elseif ($is_joined): ?>
                        <button disabled class="w-full glass-card py-4 rounded-2xl font-black uppercase tracking-widest text-sm text-slate-500 flex items-center justify-center gap-2">
                            <i class="fas fa-check-circle text-green-500"></i> Already Joined
                        </button>
                    <?php elseif ($t['status'] == 'live'): ?>
                        <button disabled class="w-full bg-slate-800 py-4 rounded-2xl font-black uppercase tracking-widest text-sm text-slate-600">
                            Match Started
                        </button>
                    <?php elseif ($is_full): ?>
                        <button disabled class="w-full bg-red-900/10 py-4 rounded-2xl font-black uppercase tracking-widest text-sm text-red-500/50 border border-red-500/10">
                            Match Full
                        </button>
                    <?php else: ?>
                        <form action="api/join_tournament.php" method="POST">
                            <input type="hidden" name="tournament_id" value="<?= $t['id'] ?>">
                            <button type="submit" class="w-full bg-gradient-to-r from-blue-600 to-blue-500 py-4 rounded-2xl font-black uppercase tracking-widest text-sm text-white shadow-xl shadow-blue-600/20 active:scale-95 transition-all">
                                Join Match
                            </button>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <nav class="fixed bottom-0 left-0 right-0 max-w-md mx-auto bg-[#0f172a]/90 backdrop-blur-xl border-t border-white/5 px-6 py-2 flex justify-between items-center z-50">
        <a href="dashboard.php" class="nav-btn flex flex-col items-center gap-1 p-2"><i class="fas fa-home text-lg"></i><span class="text-[9px] font-bold">Home</span></a>
        <a href="tournaments.php" class="nav-btn active flex flex-col items-center gap-1 p-2"><i class="fas fa-trophy text-lg"></i><span class="text-[9px] font-bold">Events</span></a>
        <div class="relative -top-6"><div onclick="location.href='tournaments.php'" class="bg-blue-600 w-14 h-14 rounded-2xl flex items-center justify-center shadow-2xl border-4 border-[#020617] cursor-pointer"><i class="fas fa-gamepad text-white text-xl"></i></div></div>
        <a href="wallet.php" class="nav-btn flex flex-col items-center gap-1 p-2"><i class="fas fa-wallet text-lg"></i><span class="text-[9px] font-bold">Wallet</span></a>
        <a href="profile.php" class="nav-btn flex flex-col items-center gap-1 p-2"><i class="fas fa-user text-lg"></i><span class="text-[9px] font-bold">Profile</span></a>
    </nav>

    <?php if(isset($_GET['msg'])): ?>
    <script>
        Swal.fire({
            icon: '<?= $_GET['status'] == 'success' ? 'success' : 'error' ?>',
            title: '<?= $_GET['status'] == 'success' ? 'Success' : 'Error' ?>',
            text: '<?= htmlspecialchars($_GET['msg']) ?>',
            background: '#1e293b', color: '#fff', confirmButtonColor: '#3b82f6'
        });
    </script>
    <?php endif; ?>
</body>
</html>