<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

fixture_preparation_boot();

if (!is_post()) {
    redirect('app/modules/fixtures/preparation.php');
}

require_valid_csrf();

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

if ($action === 'confirm_kit') {
    if (!can_confirm_fixture_kits()) {
        abort_request(403, 'Access denied', 'You do not have permission to confirm matchday kits.');
    }

    $fixtureId = (int) ($_POST['fixture_id'] ?? 0);
    $confirmedClubId = (int) ($_POST['confirmed_club_id'] ?? 0);
    $fixture = find_fixture_preparation_or_abort_for_admin($fixtureId);

    if (!in_array($confirmedClubId, [(int) $fixture['home_club_id'], (int) $fixture['away_club_id']], true)) {
        flash('error', ['type' => 'danger', 'message' => 'The selected club is invalid for this fixture.']);
        redirect('app/modules/fixtures/preparation.php?id=' . $fixtureId);
    }

    confirm_fixture_kit($fixtureId, $confirmedClubId, (int) ($_SESSION['user_id'] ?? 0));
    $fixture = find_fixture_preparation_or_abort_for_admin($fixtureId);
    $newsPostId = upsert_fixture_kit_confirmation_news($fixture);

    audit_log('confirm_fixture_kit', 'fixtures', $fixtureId, null, [
        'club_id' => $confirmedClubId,
        'news_post_id' => $newsPostId,
    ]);

    flash('success', ['type' => 'success', 'message' => $newsPostId !== null
        ? 'Matchday kits confirmed and pre-match news published.'
        : 'Matchday kit confirmed for this club.']);
    redirect('app/modules/fixtures/preparation.php?id=' . $fixtureId);
}

if (!can_edit_fixture_preparation()) {
    abort_request(403, 'Read-only access', 'Super Admin can review match preparation but cannot submit formations.');
}

$clubId = (int) user_club_id();
$fixtureId = (int) ($_POST['fixture_id'] ?? 0);
$fixture = find_fixture_preparation_or_abort($fixtureId, $clubId);
$windowState = $fixture['window_state'] ?? ['available' => false, 'message' => 'Formation window is closed.'];

if (!($windowState['available'] ?? false)) {
    flash('error', ['type' => 'danger', 'message' => (string) ($windowState['message'] ?? 'Formation window is closed.')]);
    redirect('app/modules/fixtures/preparation.php?id=' . $fixtureId);
}

$errors = [];
$payload = validate_fixture_formation_payload($_POST, $errors);
$kitPayload = validate_fixture_kit_payload($_POST, $errors);

if ($errors !== []) {
    flash('errors', $errors);
    remember_old_input($_POST);
    redirect('app/modules/fixtures/preparation.php?id=' . $fixtureId);
}

save_fixture_formation($fixtureId, $clubId, (int) ($_SESSION['user_id'] ?? 0), $payload);
save_fixture_kit($fixtureId, $clubId, (int) ($_SESSION['user_id'] ?? 0), $kitPayload);
clear_old_input();

audit_log('save_fixture_formation', 'fixtures', $fixtureId, null, [
    'club_id' => $clubId,
    'formation' => $payload['formation'],
    'starter_count' => count($payload['starter_player_ids'] ?? []),
    'substitute_count' => count($payload['substitute_player_ids'] ?? []),
]);

audit_log('save_fixture_kit', 'fixtures', $fixtureId, null, [
    'club_id' => $clubId,
    'shirt_color' => $kitPayload['shirt_color'],
    'shorts_color' => $kitPayload['shorts_color'],
    'socks_color' => $kitPayload['socks_color'],
]);

flash('success', ['type' => 'success', 'message' => 'Formation, lineup, and matchday kit colors saved for this fixture.']);
redirect('app/modules/fixtures/preparation.php?id=' . $fixtureId);
