<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

$tableModuleBoot = 'table_module_boot';
$tableValidateCompetition = 'table_validate_competition';
$recalculateLeagueTable = 'recalculate_league_table';

$tableModuleBoot();

if (!is_post()) {
    redirect('app/modules/table/index.php');
}

require_valid_csrf();

if ((string) ($_POST['action'] ?? '') !== 'recalculate') {
    redirect('app/modules/table/index.php');
}

if (!can_recalculate_table()) {
    abort_request(403, 'Access denied', 'You do not have permission to recalculate the league table.');
}

$competitionId = (int) ($_POST['competition_id'] ?? 0);
$errors = [];
$competition = $tableValidateCompetition($competitionId, $errors);

if ($errors !== [] || $competition === null) {
    flash('error', ['type' => 'danger', 'message' => $errors['competition_id'] ?? 'The selected competition is invalid.']);
    redirect('app/modules/table/index.php' . ($competitionId > 0 ? '?competition_id=' . $competitionId : ''));
}

$rowCount = $recalculateLeagueTable($competitionId);
audit_log('recalculate_league_table', 'league_table', $competitionId, null, ['competition_id' => $competitionId, 'row_count' => $rowCount]);
flash('success', ['type' => 'success', 'message' => sprintf('League table recalculated successfully for %d clubs.', $rowCount)]);
redirect('app/modules/table/index.php?competition_id=' . $competitionId);
