<?php
require_once 'config.php';

// Get active boards grouped by game
$stmt = $pdo->query("
    SELECT
        b.id, b.name, b.slug, b.bet_amount, b.status, b.payout_structure_type,
        b.rotation_type, b.quarterly_rotation,
        g.id as game_id, g.name as game_name, g.game_type, g.season_year, g.status as game_status
    FROM boards b
    LEFT JOIN games g ON b.game_id = g.id
    WHERE b.status IN ('open', 'locked')
    ORDER BY g.game_datetime DESC, b.bet_amount ASC
");
$boards = $stmt->fetchAll();

// Group boards by game
$gameBoards = [];
foreach ($boards as $board) {
    $gameKey = $board['game_id'] ?? 0;
    if (!isset($gameBoards[$gameKey])) {
        $gameBoards[$gameKey] = [
            'game_name' => $board['game_name'] ?? 'Other Boards',
            'game_type' => $board['game_type'] ?? '',
            'boards' => []
        ];
    }
    $gameBoards[$gameKey]['boards'][] = $board;
}

// Build dynamic results links per active game
$resultsLinks = [];
foreach ($gameBoards as $gameId => $game) {
    $isTournament = false;
    $firstBoardId = null;
    foreach ($game['boards'] as $b) {
        if ($firstBoardId === null) $firstBoardId = $b['id'];
        if ($b['payout_structure_type'] === 'tournament') {
            $isTournament = true;
            break;
        }
    }

    // Check if this game has final scores
    $stmtFinal = $pdo->prepare("SELECT 1 FROM game_scores WHERE game_id = ? AND category = 'FINAL' AND nfc_score IS NOT NULL AND afc_score IS NOT NULL LIMIT 1");
    $stmtFinal->execute([$gameId]);
    $gameOver = ($stmtFinal->fetch() !== false);

    if ($isTournament) {
        // For tournament, check if any tournament games are completed
        $stmtTourney = $pdo->prepare("SELECT COUNT(*) FROM tournament_games WHERE board_id = ? AND winner != 'pending'");
        $stmtTourney->execute([$firstBoardId]);
        $completedGames = $stmtTourney->fetchColumn();
        $hasResults = $completedGames > 0;

        $resultsLinks[] = [
            'url' => '/tournament-results.php?game_id=' . $gameId,
            'name' => $game['game_name'],
            'emoji' => gameEmoji($game['game_type']),
            'game_over' => false,
            'has_results' => $hasResults,
            'is_tournament' => true
        ];
    } else {
        $resultsLinks[] = [
            'url' => '/results2.php',
            'name' => $game['game_name'],
            'emoji' => gameEmoji($game['game_type']),
            'game_over' => $gameOver,
            'has_results' => true,
            'is_tournament' => false
        ];
    }
}

// Build dynamic badge from active games
$badgeText = '';
if (count($gameBoards) === 1) {
    $firstGame = reset($gameBoards);
    $badgeText = $firstGame['game_name'];
} elseif (count($gameBoards) > 1) {
    $badgeText = date('Y') . ' Season';
}

function gameEmoji($gameType) {
    return match($gameType) {
        'NCAAB' => '&#127936;',
        'NCAAF' => '&#127944;',
        'Christmas' => '&#127876;',
        'Thanksgiving' => '&#129411;',
        default => '&#127944;',
    };
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TotalElimination.com</title>
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            background: #f3f4f7;
            color: #333;
            line-height: 1.5;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        /* --- Site Top Bar --- */
        .site-top-bar {
            background: #242a36;
            color: #fff;
            padding: 14px 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }
        .site-top-bar-brand {
            font-size: 18px;
            font-weight: 600;
            color: #fff;
            text-decoration: none;
        }
        .site-top-bar-right {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .site-top-bar-link {
            color: #9ba4b0;
            text-decoration: none;
            font-size: 14px;
            font-weight: 500;
        }
        .site-top-bar-link:hover { color: #fff; }
        .site-top-bar-badge {
            background: rgba(61,196,173,0.15);
            color: #3dc4ad;
            padding: 5px 14px;
            border-radius: 20px;
            font-size: 14px;
            font-weight: 500;
        }
        .site-top-bar-cart {
            display: flex;
            align-items: center;
            gap: 6px;
            background: rgba(61,196,173,0.15);
            color: #3dc4ad;
            padding: 5px 14px;
            border-radius: 20px;
            text-decoration: none;
            font-size: 14px;
            font-weight: 600;
        }

        /* --- Site Footer --- */
        .site-footer {
            background: #242a36;
            color: #9ba4b0;
            text-align: center;
            padding: 16px;
            font-size: 13px;
            margin-top: auto;
        }

        /* --- Container --- */
        .container {
            max-width: 900px;
            margin: 0 auto;
            padding: 24px 16px;
            flex: 1;
            width: 100%;
        }

        /* --- Welcome Section --- */
        .welcome {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 1px 6px rgba(45,54,68,0.07);
            padding: 32px 28px;
            margin-bottom: 24px;
            text-align: center;
        }
        .welcome h2 {
            font-size: 24px;
            font-weight: 700;
            color: #242a36;
            margin-bottom: 6px;
        }
        .welcome p {
            color: #7a8290;
            font-size: 15px;
        }

        /* --- Section --- */
        .section {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 1px 6px rgba(45,54,68,0.07);
            margin-bottom: 20px;
            overflow: hidden;
        }
        .section-header {
            background: #2c3441;
            color: #fff;
            padding: 14px 20px;
            font-size: 16px;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        /* --- Board Grid --- */
        .board-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
            gap: 12px;
            padding: 20px;
        }
        .board-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 14px 16px;
            background: #f9f9fb;
            border: 1px solid #eef0f3;
            border-radius: 6px;
            text-decoration: none;
            color: #333;
            transition: border-color 0.2s, box-shadow 0.2s, background 0.2s;
        }
        .board-link:hover {
            border-color: #3dc4ad;
            box-shadow: 0 2px 8px rgba(61,196,173,0.15);
            background: #fff;
        }
        .board-link .price-tag {
            background: #242a36;
            color: #3dc4ad;
            font-size: 13px;
            font-weight: 700;
            padding: 4px 10px;
            border-radius: 4px;
            white-space: nowrap;
        }
        .board-link .board-name {
            font-size: 14px;
            font-weight: 600;
            color: #4a5361;
        }
        .quarterly-badge {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-size: 10px;
            font-weight: 700;
            padding: 3px 8px;
            border-radius: 10px;
            margin-left: auto;
            white-space: nowrap;
        }
        .tournament-badge {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            font-size: 10px;
            font-weight: 700;
            padding: 3px 8px;
            border-radius: 10px;
            margin-left: auto;
            white-space: nowrap;
        }

        /* --- Tools Grid --- */
        .tools-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
            gap: 12px;
            padding: 20px;
        }
        .tool-link {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 16px;
            background: #f9f9fb;
            border: 1px solid #eef0f3;
            border-radius: 6px;
            text-decoration: none;
            color: #333;
            transition: border-color 0.2s, box-shadow 0.2s, background 0.2s;
        }
        .tool-link:hover {
            border-color: #3dc4ad;
            box-shadow: 0 2px 8px rgba(61,196,173,0.15);
            background: #fff;
        }
        .tool-link .tool-icon {
            width: 38px;
            height: 38px;
            background: rgba(61,196,173,0.12);
            color: #3dc4ad;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            flex-shrink: 0;
        }
        .tool-link .tool-info .tool-name {
            font-size: 15px;
            font-weight: 600;
            color: #4a5361;
        }
        .tool-link .tool-info .tool-desc {
            font-size: 12px;
            color: #9ba4b0;
            margin-top: 2px;
        }

        /* --- Lookup Form --- */
        .lookup-form {
            padding: 24px 20px;
        }
        .lookup-form p {
            color: #7a8290;
            font-size: 14px;
            margin-bottom: 14px;
        }
        .lookup-row {
            display: flex;
            gap: 10px;
        }
        .lookup-row input[type="email"] {
            flex: 1;
            max-width: 320px;
            height: 44px;
            padding: 0 14px;
            font-size: 15px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            background: #f9f9fb;
            color: #333;
            font-family: inherit;
            transition: border-color 0.2s, box-shadow 0.2s;
        }
        .lookup-row input[type="email"]:focus {
            outline: none;
            border-color: #3dc4ad;
            box-shadow: 0 0 0 3px rgba(61,196,173,0.18);
            background: #fff;
        }
        .lookup-row input[type="email"]::placeholder {
            color: #98a0a8;
        }
        .lookup-btn {
            height: 44px;
            padding: 0 24px;
            background: #3dc4ad;
            color: #fff;
            border: none;
            border-radius: 5px;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            font-family: inherit;
            white-space: nowrap;
            transition: background 0.2s, box-shadow 0.2s;
        }
        .lookup-btn:hover {
            background: #34b09b;
            box-shadow: 0 2px 8px rgba(61,196,173,0.25);
        }
        .lookup-btn:active { background: #2c9d8a; }

        /* --- Responsive --- */
        @media (max-width: 700px) {
            .site-top-bar { padding: 12px 16px; }
            .site-top-bar-brand { font-size: 16px; }
            .container { padding: 16px 10px; }
            .welcome { padding: 24px 18px; }
            .welcome h2 { font-size: 20px; }
            .board-grid {
                grid-template-columns: 1fr;
                padding: 14px;
                gap: 10px;
            }
            .tools-grid {
                grid-template-columns: 1fr;
                padding: 14px;
                gap: 10px;
            }
            .lookup-form { padding: 18px 14px; }
            .lookup-row {
                flex-direction: column;
                gap: 12px;
            }
            .lookup-row input[type="email"] {
                max-width: 100%;
                min-height: 52px !important;
                height: auto !important;
                padding: 14px !important;
                font-size: 16px;
            }
            .lookup-btn {
                min-height: 52px;
                font-size: 16px;
            }
        }

        @media (max-width: 400px) {
            .welcome { padding: 20px 14px; }
            .welcome h2 { font-size: 18px; }
            .board-link { padding: 12px; }
            .tool-link { padding: 12px; }
        }
    </style>
</head>
<body>

<?php $isHomePage = true; $siteBadge = $badgeText; ?>
<?php include __DIR__ . '/public/includes/header.php'; ?>

<div class="container">

    <!-- Welcome -->
    <div class="welcome">
        <h2>Welcome to TotalElimination.com!</h2>
        <p>Pick a board below to get started, or use the tools to track your squares.</p>
    </div>

    <?php if (empty($gameBoards)): ?>
        <div class="section">
            <div class="section-header"><span>No Active Boards</span></div>
            <div style="padding: 30px 20px; text-align: center; color: #7a8290;">
                <p>There are no active boards right now. Check back soon!</p>
            </div>
        </div>
    <?php else: ?>
        <?php foreach ($gameBoards as $gameId => $game): ?>
            <div class="section">
                <div class="section-header">
                    <span><?= gameEmoji($game['game_type']) ?> <?= e($game['game_name']) ?></span>
                </div>
                <div class="board-grid">
                    <?php foreach ($game['boards'] as $board): ?>
                        <?php
                            $boardUrl = '/public/board-view.php?id=' . $board['id'];
                            $isQuarterly = ($board['quarterly_rotation'] ?? 0) || ($board['rotation_type'] ?? '') === 'quarterly';
                            $isTournament = $board['payout_structure_type'] === 'tournament';
                        ?>
                        <a href="<?= $boardUrl ?>" class="board-link">
                            <span class="price-tag"><?= formatCurrency($board['bet_amount']) ?></span>
                            <span class="board-name"><?= e($board['name']) ?></span>
                            <?php if ($isTournament): ?>
                                <span class="tournament-badge">Tournament</span>
                            <?php elseif ($isQuarterly): ?>
                                <span class="quarterly-badge">New Numbers Each Qtr</span>
                            <?php endif; ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <!-- View Your Squares -->
    <div class="section">
        <div class="section-header">
            <span>View Your Squares</span>
        </div>
        <div class="lookup-form">
            <p>Enter your email to see all your boards, numbers, and payout chances.</p>
            <form action="/public/my-squares.php" method="post">
                <div class="lookup-row">
                    <input type="email" name="email" placeholder="you@example.com" required>
                    <button type="submit" class="lookup-btn">Look Up</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Tools -->
    <div class="section">
        <div class="section-header">
            <span>Tools</span>
        </div>
        <div class="tools-grid">
            <?php foreach ($resultsLinks as $link): ?>
                <a href="<?= $link['url'] ?>" class="tool-link">
                    <div class="tool-icon"><?php
                        if ($link['game_over']) {
                            echo '&#127942;';
                        } elseif ($link['is_tournament']) {
                            echo $link['emoji'];
                        } else {
                            echo '&#9889;';
                        }
                    ?></div>
                    <div class="tool-info">
                        <div class="tool-name"><?php
                            if ($link['game_over']) {
                                echo e($link['name']) . ' Winners';
                            } elseif ($link['is_tournament']) {
                                echo e($link['name']) . ' Results';
                            } else {
                                echo e($link['name']) . ' Live Results';
                            }
                        ?></div>
                        <div class="tool-desc"><?php
                            if ($link['game_over']) {
                                echo 'Final results &amp; winners';
                            } elseif ($link['is_tournament']) {
                                echo $link['has_results'] ? 'Tournament grid &amp; leaderboard' : 'Results available once games begin';
                            } else {
                                echo 'Real-time scoring updates';
                            }
                        ?></div>
                    </div>
                </a>
            <?php endforeach; ?>
            <a href="https://discord.gg/X4B8XBf" class="tool-link">
                <div class="tool-icon">&#128172;</div>
                <div class="tool-info">
                    <div class="tool-name">Discord</div>
                    <div class="tool-desc">Join for updates</div>
                </div>
            </a>
        </div>
    </div>

</div><!-- .container -->

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

</body>
</html>
