<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

table_module_boot();

$pageTitle = 'Standings';
$competitionOptions = table_competition_options();
$selectedCompetitionId = (int) ($_GET['competition_id'] ?? 0);
$selectedCompetition = null;
$tableRows = [];
$groupRows = [];
$knockoutRows = [];
$tableError = null;

if ($selectedCompetitionId > 0) {
    $errors = [];
    $selectedCompetition = table_validate_competition($selectedCompetitionId, $errors);

    if ($selectedCompetition === null) {
        $tableError = $errors['competition_id'] ?? 'Selected competition is invalid.';
    } else {
        if (($selectedCompetition['type'] ?? '') === 'league') {
            $tableRows = league_table_rows($selectedCompetitionId);
        } else {
            $groupRows = fixture_group_stage_standings($selectedCompetitionId);
            foreach (fixture_knockout_round_rows($selectedCompetitionId) as $fixture) {
                $roundLabel = (string) ($fixture['knockout_round'] ?: 'Knockout round');
                $knockoutRows[$roundLabel][] = $fixture;
            }
        }
    }
}

require dirname(__DIR__, 2) . '/includes/header.php';
require dirname(__DIR__, 2) . '/includes/sidebar.php';
require dirname(__DIR__, 2) . '/includes/topbar.php';
require dirname(__DIR__, 2) . '/includes/flash.php';
?>
<section class="panel-card mb-4">
    <div class="panel-card-header mb-3">
        <div>
            <p class="eyebrow mb-1">Standings</p>
            <h2 class="h4 mb-0">Competition standings</h2>
        </div>
        <?php if ($selectedCompetition !== null && ($selectedCompetition['type'] ?? '') === 'league' && can_recalculate_table()): ?>
            <form method="post" action="<?php echo e(base_url('app/modules/table/actions.php')); ?>">
                <?php echo csrf_input(); ?>
                <input type="hidden" name="action" value="recalculate">
                <input type="hidden" name="competition_id" value="<?php echo e((string) $selectedCompetition['id']); ?>">
                <button class="btn btn-outline-jlfc" type="submit"><i class="bi bi-arrow-repeat"></i> Recalculate table</button>
            </form>
        <?php endif; ?>
    </div>

    <form class="row g-3 mb-0" method="get">
        <div class="col-md-8 col-lg-6">
            <label class="form-label" for="competition_id">Competition</label>
            <select class="form-select" id="competition_id" name="competition_id">
                <option value="">Select competition</option>
                <?php foreach ($competitionOptions as $competition): ?>
                    <option value="<?php echo e((string) $competition['id']); ?>" <?php echo $selectedCompetitionId === (int) $competition['id'] ? 'selected' : ''; ?>>
                        <?php echo e($competition['name']); ?> (<?php echo e($competition['season_name']); ?>)
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-4 col-lg-3 d-flex align-items-end gap-2">
            <button class="btn btn-jlfc" type="submit">Load table</button>
            <?php if ($selectedCompetitionId > 0): ?>
                <a class="btn btn-link" href="<?php echo e(base_url('app/modules/table/index.php')); ?>">Reset</a>
            <?php endif; ?>
        </div>
    </form>
</section>

<?php if ($tableError !== null): ?>
    <section class="panel-card">
        <p class="text-danger mb-0"><?php echo e($tableError); ?></p>
    </section>
<?php elseif ($selectedCompetition === null): ?>
    <section class="panel-card">
        <p class="text-muted mb-0">Select a competition to view league or group-stage standings.</p>
    </section>
<?php elseif (($selectedCompetition['type'] ?? '') !== 'league'): ?>
    <section class="panel-card mb-4">
        <div class="panel-card-header mb-3">
            <div>
                <p class="eyebrow mb-1">Group standings</p>
                <h3 class="h5 mb-0"><?php echo e($selectedCompetition['name']); ?> groups</h3>
            </div>
        </div>
        <?php if ($groupRows === []): ?>
            <p class="text-muted mb-0">Group standings will appear after verified group-stage results are recorded.</p>
        <?php else: ?>
            <div class="row g-4">
                <?php foreach ($groupRows as $groupLabel => $rows): ?>
                    <div class="col-12 col-xl-6">
                        <article class="panel-card h-100">
                            <div class="panel-card-header mb-3">
                                <div>
                                    <p class="eyebrow mb-1">Group stage</p>
                                    <h4 class="h6 mb-0"><?php echo e($groupLabel); ?></h4>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table align-middle mb-0">
                                    <thead>
                                        <tr>
                                            <th>#</th>
                                            <th>Club</th>
                                            <th>P</th>
                                            <th>W</th>
                                            <th>D</th>
                                            <th>L</th>
                                            <th>GD</th>
                                            <th>Pts</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($rows as $row): ?>
                                            <tr>
                                                <td><?php echo e((string) $row['position']); ?></td>
                                                <td><?php echo e($row['club_name']); ?></td>
                                                <td><?php echo e((string) $row['played']); ?></td>
                                                <td><?php echo e((string) $row['won']); ?></td>
                                                <td><?php echo e((string) $row['drawn']); ?></td>
                                                <td><?php echo e((string) $row['lost']); ?></td>
                                                <td><?php echo e((string) $row['goal_difference']); ?></td>
                                                <td><strong><?php echo e((string) $row['points']); ?></strong></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </article>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
    <section class="panel-card">
        <div class="panel-card-header mb-3">
            <div>
                <p class="eyebrow mb-1">Knockout stage</p>
                <h3 class="h5 mb-0">Generated brackets</h3>
            </div>
        </div>
        <?php if ($knockoutRows === []): ?>
            <p class="text-muted mb-0">Knockout fixtures will appear automatically after all group-stage matches are verified.</p>
        <?php else: ?>
            <div class="row g-4">
                <?php foreach ($knockoutRows as $roundLabel => $fixtures): ?>
                    <div class="col-12 col-xl-6">
                        <article class="panel-card h-100">
                            <div class="panel-card-header mb-3">
                                <div>
                                    <p class="eyebrow mb-1">Knockout round</p>
                                    <h4 class="h6 mb-0"><?php echo e($roundLabel); ?></h4>
                                </div>
                            </div>
                            <div class="table-responsive">
                                <table class="table align-middle mb-0">
                                    <thead>
                                        <tr>
                                            <th>Fixture</th>
                                            <th>Result</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($fixtures as $fixture): ?>
                                            <tr>
                                                <td><?php echo e($fixture['home_club_name']); ?> vs <?php echo e($fixture['away_club_name']); ?></td>
                                                <td><?php echo ($fixture['home_score'] !== null && $fixture['away_score'] !== null) ? e((string) $fixture['home_score'] . ' - ' . (string) $fixture['away_score']) : 'Pending'; ?></td>
                                                <td><?php echo e(ucfirst((string) ($fixture['result_status'] ?? 'scheduled'))); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </article>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
<?php else: ?>
    <section class="panel-card">
        <div class="panel-card-header mb-3">
            <div>
                <p class="eyebrow mb-1">Standings</p>
                <h3 class="h5 mb-0"><?php echo e($selectedCompetition['name']); ?> table</h3>
            </div>
        </div>
        <?php if ($tableRows === []): ?>
            <p class="text-muted mb-0">No table rows exist for this competition yet. Verify at least one match result or run a recalculation after results are available.</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Club</th>
                            <th>P</th>
                            <th>W</th>
                            <th>D</th>
                            <th>L</th>
                            <th>GF</th>
                            <th>GA</th>
                            <th>GD</th>
                            <th>Pts</th>
                            <th>Form</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($tableRows as $row): ?>
                            <tr>
                                <td><?php echo e((string) $row['position']); ?></td>
                                <td>
                                    <strong><?php echo e($row['club_name']); ?></strong>
                                    <?php if ($row['club_short_name']): ?><div class="small text-muted"><?php echo e($row['club_short_name']); ?></div><?php endif; ?>
                                </td>
                                <td><?php echo e((string) $row['played']); ?></td>
                                <td><?php echo e((string) $row['won']); ?></td>
                                <td><?php echo e((string) $row['drawn']); ?></td>
                                <td><?php echo e((string) $row['lost']); ?></td>
                                <td><?php echo e((string) $row['goals_for']); ?></td>
                                <td><?php echo e((string) $row['goals_against']); ?></td>
                                <td><?php echo e((string) $row['goal_difference']); ?></td>
                                <td><strong><?php echo e((string) $row['points']); ?></strong></td>
                                <td>
                                    <?php if (!empty($row['form'])): ?>
                                        <div class="d-flex gap-1 flex-wrap">
                                            <?php foreach (str_split((string) $row['form']) as $symbol): ?>
                                                <span class="badge <?php echo e(table_form_badge_class($symbol)); ?>"><?php echo e($symbol); ?></span>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php else: ?>
                                        <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </section>
<?php endif; ?>
<?php require dirname(__DIR__, 2) . '/includes/footer.php'; ?>