<?php
session_start();

/*
|--------------------------------------------------------------------------
| PLAY TOUR - My Matches Page
| File: public_html/my_matches.php
|--------------------------------------------------------------------------
*/

/* Login protection */
if (
    empty($_SESSION['user_id']) ||
    empty($_SESSION['user_logged_in']) ||
    $_SESSION['user_logged_in'] !== true
) {
    header('Location: login.php');
    exit;
}

$balanceDisplay = '0.00';
$matches = [];
$userId = (int) $_SESSION['user_id'];
$userEmail = $_SESSION['email'] ?? '';
$userName = $_SESSION['username'] ?? '';

/* Database connection & Fetch user matches */
$configPath = __DIR__ . '/php/config.php';
try {
    if (is_file($configPath)) {
        require_once $configPath;
        if (function_exists('getDbConnection')) {
            $db = getDbConnection();
            $db->set_charset('utf8mb4');

            /* Fetch User Balance */
            $sqlUser = "SELECT balance FROM Rahim10x_Users WHERE id = ? LIMIT 1";
            $stmtUser = $db->prepare($sqlUser);
            if ($stmtUser) {
                $stmtUser->bind_param('i', $userId);
                $stmtUser->execute();
                $stmtUser->bind_result($dbBalance);
                if ($stmtUser->fetch() && $dbBalance !== null) {
                    $balanceDisplay = number_format((float)$dbBalance, 2, '.', ',');
                }
                $stmtUser->close();
            }

            /* Fetch Matches joined by this specific user from joiners & freefire tables */
            $sqlMatches = "SELECT j.match_id, f.match_title, f.match_time, f.entry_fee, j.winning 
                           FROM joiners j 
                           JOIN freefire f ON j.match_id = f.id 
                           WHERE j.user_id = ? OR j.email = ? OR j.name = ? 
                           ORDER BY j.match_id DESC";
            
            $stmtMatches = $db->prepare($sqlMatches);
            if ($stmtMatches) {
                $stmtMatches->bind_param('iss', $userId, $userEmail, $userName);
                $stmtMatches->execute();
                $resMatches = $stmtMatches->get_result();
                
                $serialCount = 1;
                while ($row = $resMatches->fetch_assoc()) {
                    $matches[] = [
                        'serial' => (string)$serialCount++,
                        'title' => $row['match_title'] ?? 'Free Fire Tournament',
                        'date' => !empty($row['match_time']) ? 'Time: ' . $row['match_time'] : 'Recently Played',
                        'match_fee' => '৳' . ($row['entry_fee'] ?? '0'),
                        'winning' => ($row['winning'] !== null && $row['winning'] > 0) ? '৳' . $row['winning'] : '৳0'
                    ];
                }
                $stmtMatches->close();
            }

            $db->close();
        }
    }
} catch (Throwable $e) {
    error_log('My Matches DB error: ' . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#080317">
<title>PLAY TOUR | My Matches</title>

<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>

<!-- Font Awesome Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@700;800;900&family=Plus+Jakarta+Sans:wght@500;600;700;800&display=swap" rel="stylesheet">

<style>
* {
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
}

html, body {
    margin: 0;
    padding: 0;
    background: #04010b;
    color: white;
    font-family: 'Plus Jakarta Sans', sans-serif;
    overflow-x: hidden;
    scrollbar-width: none;
}

::-webkit-scrollbar {
    display: none;
}

body {
    padding-bottom: 95px;
}

.font-orbitron { font-family: 'Orbitron', sans-serif; }

/* Cyberpunk Card Styling */
.match-card {
    background: linear-gradient(135deg, #130a2a 0%, #080315 100%);
    border: 1px solid rgba(139, 92, 246, 0.25);
    box-shadow: 0 0 15px rgba(139, 92, 246, 0.15);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.match-card:active {
    transform: scale(0.98);
    border-color: rgba(168, 85, 247, 0.5);
}

/* Bottom Nav Button Glow */
.cyber-play-btn {
    clip-path: polygon(30% 0%, 70% 0%, 100% 30%, 100% 70%, 70% 100%, 30% 100%, 0% 70%, 0% 30%);
}

.play-btn-glow {
    animation: cyberPulse 2.2s infinite ease-in-out;
}

@keyframes cyberPulse {
    0%, 100% { filter: drop-shadow(0 0 8px rgba(168, 85, 247, .8)); }
    50% { filter: drop-shadow(0 0 17px rgba(192, 132, 252, .95)); }
}

.nav-item.active .icon-box {
    background: rgba(147, 51, 234, .30);
    border: 1px solid rgba(192, 132, 252, .75);
    box-shadow: 0 0 13px rgba(168, 85, 247, .28);
}

body, img, a, button, h1, h2, h3, h4, p, span {
    user-select: none;
    -webkit-user-select: none;
}
</style>
</head>

<body class="max-w-md mx-auto min-h-screen relative border-x border-purple-950/40">

<!-- HEADER -->
<header class="flex items-center justify-between px-4 py-4 bg-[#080317]/90 border-b border-purple-950/50 sticky top-0 z-50 backdrop-blur-xl">
    <div class="flex items-center gap-3">
        <a href="home.php" class="w-10 h-10 bg-[#130b2e] border border-purple-800/40 rounded-xl flex items-center justify-center text-gray-300 active:scale-90 transition-all shadow-lg">
            <i class="fa-solid fa-chevron-left text-sm"></i>
        </a>
        <div>
            <h1 class="font-orbitron font-black text-sm text-white tracking-widest uppercase">MY MATCHES</h1>
            <p class="text-[9px] text-purple-400 font-extrabold uppercase tracking-widest">MATCH HISTORY</p>
        </div>
    </div>

    <div class="flex items-center gap-2">
        <div class="flex items-center bg-[#130b2e] border border-purple-800/40 rounded-full px-3.5 py-1.5 gap-2 shadow-inner">
            <span class="w-4 h-4 rounded-full bg-amber-500 text-black font-black text-[9px] flex items-center justify-center shadow-md">S</span>
            <span class="text-xs font-black text-white tracking-wider"><?php echo htmlspecialchars($balanceDisplay, ENT_QUOTES, 'UTF-8'); ?></span>
        </div>
    </div>
</header>

<main class="p-4 space-y-4">

    <!-- LIST HEADER LABEL -->
    <div class="flex items-center justify-between px-2 text-[10px] font-orbitron font-bold text-purple-300 uppercase tracking-widest">
        <span># Sl & Details</span>
        <div class="flex gap-6">
            <span>Fee</span>
            <span>Win</span>
        </div>
    </div>

    <!-- MATCHES ITEM LIST -->
    <div class="space-y-3">
        <?php if (!empty($matches)): ?>
            <?php foreach ($matches as $item): ?>
            <div class="match-card rounded-2xl p-3.5 flex items-center justify-between gap-2">
                
                <!-- SERIAL & TITLE SECTION -->
                <div class="flex items-center gap-3 flex-1 min-w-0">
                    <!-- SERIAL NUMBER -->
                    <div class="w-9 h-9 rounded-xl bg-purple-950/70 border border-purple-800/40 flex items-center justify-center font-orbitron font-black text-xs text-purple-300 shadow-inner flex-shrink-0">
                        <?php echo htmlspecialchars($item['serial'], ENT_QUOTES, 'UTF-8'); ?>
                    </div>

                    <!-- TITLE & DATE -->
                    <div class="min-w-0 flex-1">
                        <h3 class="font-orbitron font-extrabold text-xs text-white truncate tracking-wide">
                            <?php echo htmlspecialchars($item['title'], ENT_QUOTES, 'UTF-8'); ?>
                        </h3>
                        <p class="text-[10px] text-gray-400 font-semibold mt-0.5 flex items-center gap-1">
                            <i class="fa-regular fa-clock text-[9px] text-purple-400"></i>
                            <span><?php echo htmlspecialchars($item['date'], ENT_QUOTES, 'UTF-8'); ?></span>
                        </p>
                    </div>
                </div>

                <!-- FEE & WINNING SECTION -->
                <div class="flex items-center gap-3 flex-shrink-0">
                    <!-- MATCH FEE -->
                    <div class="text-center min-w-[38px]">
                        <span class="block text-[8px] text-gray-500 font-bold uppercase tracking-wider">Fee</span>
                        <span class="font-orbitron font-extrabold text-xs text-gray-300">
                            <?php echo htmlspecialchars($item['match_fee'], ENT_QUOTES, 'UTF-8'); ?>
                        </span>
                    </div>

                    <!-- WINNING -->
                    <div class="text-center min-w-[48px] bg-purple-950/50 py-1.5 px-2 rounded-xl border border-purple-800/30">
                        <span class="block text-[8px] text-emerald-400 font-bold uppercase tracking-wider">Win</span>
                        <span class="font-orbitron font-black text-xs text-emerald-400">
                            <?php echo htmlspecialchars($item['winning'], ENT_QUOTES, 'UTF-8'); ?>
                        </span>
                    </div>
                </div>

            </div>
            <?php endforeach; ?>
        <?php else: ?>
            <!-- EMPTY STATE -->
            <div class="text-center py-16 px-4 bg-[#080317]/60 rounded-2xl border border-purple-900/40">
                <div class="w-12 h-12 rounded-full bg-purple-900/30 border border-purple-500/30 flex items-center justify-center mx-auto text-purple-400 text-lg mb-3">
                    <i class="fa-solid fa-trophy"></i>
                </div>
                <h3 class="font-orbitron font-bold text-xs text-white uppercase tracking-wider">No Matches Joined Yet</h3>
                <p class="text-[10px] text-gray-400 mt-1">Join any tournament or match from home to see your history here.</p>
            </div>
        <?php endif; ?>
    </div>

</main>

<!-- BOTTOM NAVIGATION -->
<div class="fixed bottom-0 left-0 right-0 max-w-md mx-auto z-40 px-2.5 pb-2">
    <nav id="bottomNav" class="relative bg-[#09031a]/95 backdrop-blur-xl border border-purple-500/30 rounded-2xl px-2 py-1.5 flex justify-between items-center shadow-[0_-5px_30px_rgba(139,92,246,0.3)]">

        <div class="absolute top-0 left-1/2 -translate-x-1/2 w-3/4 h-px bg-gradient-to-r from-transparent via-purple-400/90 to-transparent"></div>

        <a href="home.php" class="nav-item flex flex-col items-center justify-center w-12 py-1 text-gray-400 font-extrabold">
            <div class="icon-box px-2.5 py-1.5 rounded-xl border border-transparent">
                <i class="fa-solid fa-house text-xs"></i>
            </div>
            <span class="text-[9px] tracking-wider mt-0.5">HOME</span>
        </a>

        <a href="my_matches.php" class="nav-item active flex flex-col items-center justify-center w-12 py-1 text-purple-300 font-black">
            <div class="icon-box px-2.5 py-1.5 rounded-xl">
                <i class="fa-solid fa-trophy text-xs"></i>
            </div>
            <span class="text-[9px] tracking-wider mt-0.5">MATCHES</span>
        </a>

        <a href="home.php#battleSection" class="flex flex-col items-center relative -top-3">
            <div class="relative flex items-center justify-center play-btn-glow">
                <div class="w-[52px] h-[52px] bg-gradient-to-tr from-purple-500 via-indigo-400 to-cyan-400 p-[2px] cyber-play-btn">
                    <div class="w-full h-full bg-gradient-to-b from-[#1c0c42] via-[#10062a] to-[#080218] cyber-play-btn flex items-center justify-center">
                        <i class="fa-solid fa-shield-halved text-purple-300 text-base"></i>
                    </div>
                </div>
            </div>
            <span class="text-[9px] font-black font-orbitron text-purple-300 tracking-wider mt-0.5">PLAY</span>
        </a>

        <a href="result.php" class="nav-item flex flex-col items-center justify-center w-12 py-1 text-gray-400 font-extrabold">
            <div class="icon-box px-2.5 py-1.5 rounded-xl border border-transparent">
                <i class="fa-solid fa-chart-simple text-xs"></i>
            </div>
            <span class="text-[9px] tracking-wider mt-0.5">RESULTS</span>
        </a>

        <a href="profile.php" class="nav-item flex flex-col items-center justify-center w-12 py-1 text-gray-400 font-extrabold">
            <div class="icon-box px-2.5 py-1.5 rounded-xl border border-transparent">
                <i class="fa-solid fa-user text-xs"></i>
            </div>
            <span class="text-[9px] tracking-wider mt-0.5">PROFILE</span>
        </a>
    </nav>
</div>

</body>
</html>
