<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

season_module_boot();

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

require_valid_csrf();

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

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

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

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

    db_query(
        'INSERT INTO seasons (name, start_date, end_date, status, created_at)
         VALUES (:name, :start_date, :end_date, :status, NOW())',
        $payload
    );

    $seasonId = (int) db()->lastInsertId();
    audit_log('create_season', 'seasons', $seasonId, null, $payload);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Season created successfully.']);
    redirect('app/modules/seasons/view.php?id=' . $seasonId);
}

if ($action === 'update') {
    $seasonId = (int) ($_POST['id'] ?? 0);
    $existingSeason = find_season_or_abort($seasonId);
    remember_old_input($_POST);

    $errors = [];
    $payload = validate_season_payload($_POST, $errors, $seasonId);

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

    db_query(
        'UPDATE seasons
         SET name = :name,
             start_date = :start_date,
             end_date = :end_date
         WHERE id = :id',
        [
            'name' => $payload['name'],
            'start_date' => $payload['start_date'],
            'end_date' => $payload['end_date'],
            'id' => $seasonId,
        ]
    );

    if ($payload['status'] !== $existingSeason['status']) {
        season_set_status($seasonId, $payload['status']);
    }

    audit_log('update_season', 'seasons', $seasonId, $existingSeason, $payload);

    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Season updated successfully.']);
    redirect('app/modules/seasons/view.php?id=' . $seasonId);
}

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

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

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

if ($action === 'delete') {
    $seasonId = (int) ($_POST['id'] ?? 0);
    $existingSeason = find_season_or_abort($seasonId);

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

    db_query('DELETE FROM seasons WHERE id = :id', ['id' => $seasonId]);
    audit_log('delete_season', 'seasons', $seasonId, $existingSeason, null);
    flash('success', ['type' => 'success', 'message' => 'Season deleted successfully.']);
    redirect('app/modules/seasons/index.php');
}

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