<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

$matchModuleBoot = 'match_module_boot';
$findMatchFixtureOrAbort = 'find_match_fixture_or_abort';
$validateMatchResultPayload = 'validate_match_result_payload';
$upsertMatchResult = 'upsert_match_result';
$verifyMatchResult = 'verify_match_result';
$canSubmitMatchResults = 'can_submit_match_results';
$canVerifyMatchResults = 'can_verify_match_results';
$canManageMatchEvents = 'can_manage_match_events';
$validateMatchEventPayload = 'validate_match_event_payload';
$refreshVerifiedFixtureSideEffects = 'refresh_verified_fixture_side_effects';
$findMatchEventOrAbort = 'find_match_event_or_abort';
$publishVerifiedMatchReport = 'publish_verified_match_report';
$upsertMatchUpdateDraft = 'upsert_match_update_draft';
$matchUpdateIsNotableEventType = 'match_update_is_notable_event_type';

$matchModuleBoot();

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

require_valid_csrf();

$action = (string) ($_POST['action'] ?? '');
$user = current_user();
$userId = (int) ($user['id'] ?? 0);

if ($action === 'submit_result') {
    if (!$canSubmitMatchResults()) {
        abort_request(403, 'Access denied', 'You do not have permission to submit match results.');
    }

    remember_old_input($_POST);
    $errors = [];
    $payload = $validateMatchResultPayload($_POST, $errors);
    $fixture = $findMatchFixtureOrAbort($payload['fixture_id']);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the result form errors.']);
        redirect('app/modules/matches/view.php?fixture_id=' . $payload['fixture_id']);
    }

    $resultId = $upsertMatchResult($fixture, $payload, $userId);
    db_query('UPDATE fixtures SET status = "completed", updated_at = NOW() WHERE id = :id', ['id' => (int) $fixture['id']]);
    $draftPostId = $upsertMatchUpdateDraft($findMatchFixtureOrAbort((int) $fixture['id']), 'Result submission updated');
    audit_log('submit_match_result', 'match_results', $resultId, null, $payload + ['fixture_id' => (int) $fixture['id']]);
    if ($draftPostId !== null) {
        audit_log('upsert_match_update_draft', 'news_posts', $draftPostId, null, ['fixture_id' => (int) $fixture['id'], 'trigger' => 'submit_result']);
    }
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Match result submitted successfully.']);
    redirect('app/modules/matches/view.php?fixture_id=' . (int) $fixture['id']);
}

if ($action === 'verify_result') {
    if (!$canVerifyMatchResults()) {
        abort_request(403, 'Access denied', 'You do not have permission to verify match results.');
    }

    $fixtureId = (int) ($_POST['fixture_id'] ?? 0);
    $fixture = $findMatchFixtureOrAbort($fixtureId);

    if (!isset($fixture['result_id']) || (int) $fixture['result_id'] <= 0) {
        flash('error', ['type' => 'danger', 'message' => 'A submitted result is required before verification.']);
        redirect('app/modules/matches/view.php?fixture_id=' . $fixtureId);
    }

    if (($fixture['result_status'] ?? '') === 'verified') {
        flash('error', ['type' => 'danger', 'message' => 'This result has already been verified.']);
        redirect('app/modules/matches/view.php?fixture_id=' . $fixtureId);
    }

    $before = [
        'result_status' => $fixture['result_status'],
        'verified_by' => $fixture['verified_by'],
        'verified_at' => $fixture['verified_at'],
    ];

    $verifyMatchResult($fixture, $userId);
    $verifiedFixture = $findMatchFixtureOrAbort($fixtureId);
    $refreshVerifiedFixtureSideEffects($verifiedFixture);
    $newsPostId = $publishVerifiedMatchReport($verifiedFixture);
    $reportMode = (string) site_setting('verified_match_report_mode', 'published');
    audit_log('verify_match_result', 'match_results', (int) $fixture['result_id'], $before, ['result_status' => 'verified', 'verified_by' => $userId]);
    audit_log('publish_match_report', 'news_posts', $newsPostId, null, ['fixture_id' => $fixtureId, 'result_id' => (int) $fixture['result_id']]);
    flash('success', ['type' => 'success', 'message' => $reportMode === 'draft'
        ? 'Match result verified, competition updates refreshed, and the match report was saved as a draft.'
        : 'Match result verified, competition updates refreshed, and the match report published successfully.']);
    redirect('app/modules/matches/view.php?fixture_id=' . $fixtureId);
}

if ($action === 'create_event') {
    if (!$canManageMatchEvents()) {
        abort_request(403, 'Access denied', 'You do not have permission to manage match events.');
    }

    remember_old_input($_POST);
    $errors = [];
    $payload = $validateMatchEventPayload($_POST, $errors);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the match event form errors.']);
        redirect('app/modules/matches/view.php?fixture_id=' . $payload['fixture_id']);
    }

    db_query(
        'INSERT INTO match_events (
            fixture_id, club_id, player_id, event_type, minute, extra_minute,
            related_player_id, notes, created_at
         ) VALUES (
            :fixture_id, :club_id, :player_id, :event_type, :minute, :extra_minute,
            :related_player_id, :notes, NOW()
         )',
        $payload
    );

    $eventId = (int) db()->lastInsertId();
    $fixture = $findMatchFixtureOrAbort((int) $payload['fixture_id']);
    $refreshVerifiedFixtureSideEffects($fixture);
    if ($matchUpdateIsNotableEventType($payload['event_type'])) {
        $draftPostId = $upsertMatchUpdateDraft($findMatchFixtureOrAbort((int) $payload['fixture_id']), 'Match event log updated');
        if ($draftPostId !== null) {
            audit_log('upsert_match_update_draft', 'news_posts', $draftPostId, null, ['fixture_id' => (int) $payload['fixture_id'], 'trigger' => 'create_event', 'event_id' => $eventId]);
        }
    }
    audit_log('create_match_event', 'match_events', $eventId, null, $payload);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Match event recorded successfully.']);
    redirect('app/modules/matches/view.php?fixture_id=' . (int) $payload['fixture_id']);
}

if ($action === 'delete_event') {
    if (!$canManageMatchEvents()) {
        abort_request(403, 'Access denied', 'You do not have permission to manage match events.');
    }

    $eventId = (int) ($_POST['event_id'] ?? 0);
    $event = $findMatchEventOrAbort($eventId);
    db_query('DELETE FROM match_events WHERE id = :id', ['id' => $eventId]);
    $fixture = $findMatchFixtureOrAbort((int) $event['fixture_id']);
    $refreshVerifiedFixtureSideEffects($fixture);
    if ($matchUpdateIsNotableEventType((string) ($event['event_type'] ?? ''))) {
        $draftPostId = $upsertMatchUpdateDraft($fixture, 'Match event log revised');
        if ($draftPostId !== null) {
            audit_log('upsert_match_update_draft', 'news_posts', $draftPostId, null, ['fixture_id' => (int) $event['fixture_id'], 'trigger' => 'delete_event', 'event_id' => $eventId]);
        }
    }
    audit_log('delete_match_event', 'match_events', $eventId, $event, null);
    flash('success', ['type' => 'success', 'message' => 'Match event deleted successfully.']);
    redirect('app/modules/matches/view.php?fixture_id=' . (int) $event['fixture_id']);
}

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