<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

$competitionModuleBoot = 'competition_module_boot';
$validateCompetitionPayload = 'validate_competition_payload';
$findCompetitionOrAbort = 'find_competition_or_abort';
$competitionHasFixtures = 'competition_has_fixtures';

$competitionModuleBoot();

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

require_valid_csrf();

$action = (string) ($_POST['action'] ?? '');

if ($action === 'create') {
    remember_old_input($_POST);

    $errors = [];
    $payload = $validateCompetitionPayload($_POST, $errors, null);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the competition form errors.']);
        redirect('app/modules/competitions/create.php');
    }

    db_query(
        'INSERT INTO competitions (season_id, name, sequence_order, type, number_of_teams, group_count, qualifiers_per_group, points_win, points_draw, points_loss, tie_breaker_type, status, created_at)
         VALUES (:season_id, :name, :sequence_order, :type, :number_of_teams, :group_count, :qualifiers_per_group, :points_win, :points_draw, :points_loss, :tie_breaker_type, :status, NOW())',
        $payload + ['status' => 'draft']
    );

    $competitionId = (int) db()->lastInsertId();

    if ($payload['status'] !== 'draft') {
        competition_set_status($competitionId, $payload['status']);
    }

    audit_log('create_competition', 'competitions', $competitionId, null, $payload);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Competition created successfully.']);
    redirect('app/modules/competitions/view.php?id=' . $competitionId);
}

if ($action === 'update') {
    $competitionId = (int) ($_POST['id'] ?? 0);
    $existingCompetition = $findCompetitionOrAbort($competitionId);
    remember_old_input($_POST);

    $errors = [];
    $payload = $validateCompetitionPayload($_POST, $errors, $competitionId);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the competition form errors.']);
        redirect('app/modules/competitions/edit.php?id=' . $competitionId);
    }

    db_query(
        'UPDATE competitions
         SET season_id = :season_id,
             name = :name,
             sequence_order = :sequence_order,
             type = :type,
             number_of_teams = :number_of_teams,
             group_count = :group_count,
             qualifiers_per_group = :qualifiers_per_group,
             points_win = :points_win,
             points_draw = :points_draw,
             points_loss = :points_loss,
             tie_breaker_type = :tie_breaker_type
         WHERE id = :id',
        [
            'season_id' => $payload['season_id'],
            'name' => $payload['name'],
            'sequence_order' => $payload['sequence_order'],
            'type' => $payload['type'],
            'number_of_teams' => $payload['number_of_teams'],
            'group_count' => $payload['group_count'],
            'qualifiers_per_group' => $payload['qualifiers_per_group'],
            'points_win' => $payload['points_win'],
            'points_draw' => $payload['points_draw'],
            'points_loss' => $payload['points_loss'],
            'tie_breaker_type' => $payload['tie_breaker_type'],
            'id' => $competitionId,
        ]
    );

    if ($payload['status'] !== $existingCompetition['status']) {
        competition_set_status($competitionId, $payload['status']);
    }

    audit_log('update_competition', 'competitions', $competitionId, $existingCompetition, $payload);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Competition updated successfully.']);
    redirect('app/modules/competitions/view.php?id=' . $competitionId);
}

if ($action === 'set_status') {
    $competitionId = (int) ($_POST['id'] ?? 0);
    $status = (string) ($_POST['status'] ?? '');

    try {
        competition_set_status($competitionId, $status);
    } catch (RuntimeException $exception) {
        flash('error', ['type' => 'danger', 'message' => $exception->getMessage()]);
        redirect('app/modules/competitions/index.php');
    }

    flash('success', ['type' => 'success', 'message' => 'Competition status updated successfully.']);
    redirect('app/modules/competitions/index.php');
}

if ($action === 'delete') {
    $competitionId = (int) ($_POST['id'] ?? 0);
    $existingCompetition = $findCompetitionOrAbort($competitionId);

    if ($competitionHasFixtures($competitionId)) {
        flash('error', ['type' => 'danger', 'message' => 'This competition cannot be deleted while fixtures still exist under it.']);
        redirect('app/modules/competitions/delete.php?id=' . $competitionId);
    }

    db_query('DELETE FROM competitions WHERE id = :id', ['id' => $competitionId]);
    audit_log('delete_competition', 'competitions', $competitionId, $existingCompetition, null);
    flash('success', ['type' => 'success', 'message' => 'Competition deleted successfully.']);
    redirect('app/modules/competitions/index.php');
}

redirect('app/modules/competitions/index.php');
