<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

$view = strtolower(trim((string) ($_GET['view'] ?? 'future')));
if (!in_array($view, ['future', 'previous', 'all'], true)) {
    $view = 'future';
}

$dateFrom = trim((string) ($_GET['from'] ?? ''));
$dateTo = trim((string) ($_GET['to'] ?? ''));

if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateFrom) !== 1) {
    $dateFrom = '';
}

if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateTo) !== 1) {
    $dateTo = '';
}

$fixtures = [];
$fixtureFilterTitle = 'Competition fixtures';
$fixtureFilterEyebrow = 'Upcoming schedule';
$fixtureFilterEmptyState = 'No fixtures match the selected filters.';
$queryParams = [];
$whereClauses = [];
$orderBy = 'COALESCE(f.match_date, "9999-12-31") ASC, COALESCE(f.match_time, "23:59:59") ASC, f.id ASC';

if ($view === 'previous') {
    $fixtureFilterTitle = 'Previous matches';
    $fixtureFilterEyebrow = 'Played schedule';
    $whereClauses[] = 'f.match_date IS NOT NULL AND TIMESTAMP(f.match_date, COALESCE(f.match_time, "23:59:59")) < NOW()';
    $orderBy = 'f.match_date DESC, COALESCE(f.match_time, "23:59:59") DESC, f.id DESC';
} elseif ($view === 'all') {
    $fixtureFilterTitle = 'All fixtures';
    $fixtureFilterEyebrow = 'Full schedule';
} else {
    $whereClauses[] = '(f.match_date IS NULL OR TIMESTAMP(f.match_date, COALESCE(f.match_time, "23:59:59")) >= NOW())';
}

if ($dateFrom !== '') {
    $whereClauses[] = 'f.match_date >= :date_from';
    $queryParams['date_from'] = $dateFrom;
}

if ($dateTo !== '') {
    $whereClauses[] = 'f.match_date <= :date_to';
    $queryParams['date_to'] = $dateTo;
}

$fixturesFilterUrl = static function (string $targetView) use ($dateFrom, $dateTo): string {
    $query = ['view' => $targetView];

    if ($dateFrom !== '') {
        $query['from'] = $dateFrom;
    }

    if ($dateTo !== '') {
        $query['to'] = $dateTo;
    }

    return base_url('app/public/fixtures.php?' . http_build_query($query));
};

try {
    $fixtures = db_fetch_all(
        'SELECT f.id, f.matchday, f.match_date, f.match_time, f.status, f.stage_type, f.group_label, f.knockout_round,
                hc.name AS home_club, ac.name AS away_club,
            c.name AS competition_name, c.type AS competition_type, v.name AS venue_name,
                mr.home_score, mr.away_score, mr.result_status
         FROM fixtures f
         INNER JOIN clubs hc ON hc.id = f.home_club_id
         INNER JOIN clubs ac ON ac.id = f.away_club_id
         INNER JOIN competitions c ON c.id = f.competition_id
         LEFT JOIN venues v ON v.id = f.venue_id
         LEFT JOIN match_results mr ON mr.fixture_id = f.id'
            . ($whereClauses === [] ? '' : ' WHERE ' . implode(' AND ', $whereClauses))
            . ' ORDER BY ' . $orderBy
            . ' LIMIT 20',
        $queryParams
    );
} catch (Throwable) {
}

render_public_page('Fixtures', 'Scheduled matches and matchday planning for JLFC competitions.', static function () use ($fixtures, $view, $dateFrom, $dateTo, $fixtureFilterTitle, $fixtureFilterEyebrow, $fixtureFilterEmptyState, $fixturesFilterUrl): void {
?>
    <section class="panel-card">
        <div class="panel-card-header mb-3">
            <div>
                <p class="eyebrow mb-1"><?php echo e($fixtureFilterEyebrow); ?></p>
                <h2 class="h4 mb-0"><?php echo e($fixtureFilterTitle); ?></h2>
            </div>
        </div>
        <div class="d-flex flex-wrap gap-2 mb-3">
            <a class="btn btn-sm <?php echo $view === 'future' ? 'btn-jlfc' : 'btn-outline-jlfc'; ?>" href="<?php echo e($fixturesFilterUrl('future')); ?>">Future matches</a>
            <a class="btn btn-sm <?php echo $view === 'previous' ? 'btn-jlfc' : 'btn-outline-jlfc'; ?>" href="<?php echo e($fixturesFilterUrl('previous')); ?>">Previous matches</a>
            <a class="btn btn-sm <?php echo $view === 'all' ? 'btn-jlfc' : 'btn-outline-jlfc'; ?>" href="<?php echo e($fixturesFilterUrl('all')); ?>">All matches</a>
        </div>
        <form class="row g-3 align-items-end mb-4" method="get" action="<?php echo e(base_url('app/public/fixtures.php')); ?>">
            <input type="hidden" name="view" value="<?php echo e($view); ?>">
            <div class="col-12 col-md-4">
                <label class="form-label" for="fixtures-from">From date</label>
                <input class="form-control" id="fixtures-from" name="from" type="date" value="<?php echo e($dateFrom); ?>">
            </div>
            <div class="col-12 col-md-4">
                <label class="form-label" for="fixtures-to">To date</label>
                <input class="form-control" id="fixtures-to" name="to" type="date" value="<?php echo e($dateTo); ?>">
            </div>
            <div class="col-12 col-md-4 d-flex gap-2">
                <button class="btn btn-jlfc" type="submit">Apply filter</button>
                <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/public/fixtures.php?view=' . urlencode($view))); ?>">Clear dates</a>
            </div>
        </form>
        <?php if ($fixtures === []): ?>
            <p class="text-muted mb-0"><?php echo e($fixtureFilterEmptyState); ?></p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>Matchday</th>
                            <th>Fixture</th>
                            <th>Competition</th>
                            <th>Date</th>
                            <th>Venue</th>
                            <th>Status</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($fixtures as $fixture): ?>
                            <tr>
                                <td><?php echo e((string) $fixture['matchday']); ?></td>
                                <td>
                                    <strong class="public-fixture-team"><?php echo e($fixture['home_club']); ?></strong> vs <strong class="public-fixture-team"><?php echo e($fixture['away_club']); ?></strong>
                                    <?php if ($fixture['home_score'] !== null && $fixture['away_score'] !== null): ?>
                                        <div class="small text-muted"><?php echo e((string) $fixture['home_score']); ?> - <?php echo e((string) $fixture['away_score']); ?><?php echo !empty($fixture['result_status']) ? ' · ' . e(ucfirst((string) $fixture['result_status'])) : ''; ?></div>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo e($fixture['competition_name']); ?><div class="small text-muted"><?php echo e(competition_stage_label($fixture)); ?></div>
                                </td>
                                <td><?php echo e(format_match_date_time($fixture['match_date'] ?? null, $fixture['match_time'] ?? null, '-', 'Time TBC')); ?></td>
                                <td><?php echo e($fixture['venue_name'] ?? 'TBC'); ?></td>
                                <td><span class="badge badge-soft-success"><?php echo e(ucfirst($fixture['status'])); ?></span></td>
                                <td class="text-end"><a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/public/match-details.php?id=' . (int) $fixture['id'])); ?>">Match details</a></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>
<?php
});
