<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

match_module_boot();

$fixture = find_match_fixture_or_abort((int) ($_GET['fixture_id'] ?? 0));
$eventPlayers = event_players_for_fixture($fixture);
$events = match_events_for_fixture((int) $fixture['id']);
$pageTitle = 'Match Result';
$formErrors = flash('errors') ?? [];

require dirname(__DIR__, 2) . '/includes/header.php';
require dirname(__DIR__, 2) . '/includes/sidebar.php';
require dirname(__DIR__, 2) . '/includes/topbar.php';
require dirname(__DIR__, 2) . '/includes/flash.php';
?>
<section class="panel-card mb-4">
    <div class="panel-card-header mb-3">
        <div>
            <p class="eyebrow mb-1">Match result</p>
            <h2 class="h4 mb-0"><?php echo e($fixture['home_club_name']); ?> vs <?php echo e($fixture['away_club_name']); ?></h2>
        </div>
        <div class="d-flex gap-2">
            <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/fixtures/view.php?id=' . (int) $fixture['id'])); ?>">View fixture</a>
        </div>
    </div>
    <div class="row g-3">
        <div class="col-md-4">
            <div class="feature-tile"><i class="bi bi-trophy"></i>
                <div>
                    <h4>Competition</h4>
                    <p><?php echo e($fixture['competition_name']); ?> (<?php echo e($fixture['season_name']); ?>)</p>
                </div>
            </div>
        </div>
        <div class="col-md-2">
            <div class="feature-tile"><i class="bi bi-calendar-week"></i>
                <div>
                    <h4>Matchday</h4>
                    <p><?php echo e((string) $fixture['matchday']); ?></p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="feature-tile"><i class="bi bi-calendar-event"></i>
                <div>
                    <h4>Date</h4>
                    <p><?php echo e($fixture['match_date'] ?: 'TBD'); ?></p>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="feature-tile"><i class="bi bi-flag"></i>
                <div>
                    <h4>Status</h4>
                    <p><?php if ($fixture['result_status']): ?><span class="badge <?php echo e(match_result_status_badge_class((string) $fixture['result_status'])); ?>"><?php echo e(ucfirst((string) $fixture['result_status'])); ?></span><?php else: ?><span class="text-muted">No result</span><?php endif; ?></p>
                </div>
            </div>
        </div>
    </div>
</section>

<section class="row g-4">
    <div class="col-12 col-lg-6">
        <article class="panel-card h-100">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Current result</p>
                    <h3 class="h5 mb-0">Submitted scoreline</h3>
                </div>
            </div>
            <?php if ($fixture['result_id'] !== null): ?>
                <div class="feature-tile mb-3">
                    <i class="bi bi-stopwatch"></i>
                    <div>
                        <h4><?php echo e((string) $fixture['home_score']); ?> - <?php echo e((string) $fixture['away_score']); ?></h4>
                        <p><?php echo e(ucfirst((string) $fixture['result_status'])); ?> result on file.</p>
                    </div>
                </div>
                <div class="small text-muted">
                    Submitted by: <?php echo e($fixture['submitted_by_name'] ?: 'Unknown'); ?><?php echo $fixture['submitted_at'] ? ' on ' . e($fixture['submitted_at']) : ''; ?>
                </div>
                <div class="small text-muted">
                    Verified by: <?php echo e($fixture['verified_by_name'] ?: 'Not verified'); ?><?php echo $fixture['verified_at'] ? ' on ' . e($fixture['verified_at']) : ''; ?>
                </div>
            <?php else: ?>
                <p class="text-muted mb-0">No result has been submitted for this fixture yet.</p>
            <?php endif; ?>
        </article>
    </div>
    <div class="col-12 col-lg-6">
        <article class="panel-card h-100">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Teams</p>
                    <h3 class="h5 mb-0">Fixture pairing</h3>
                </div>
            </div>
            <div class="row g-3">
                <div class="col-md-6">
                    <div class="feature-tile"><i class="bi bi-house-door"></i>
                        <div>
                            <h4>Home club</h4>
                            <p><?php echo e($fixture['home_club_name']); ?></p>
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="feature-tile"><i class="bi bi-airplane"></i>
                        <div>
                            <h4>Away club</h4>
                            <p><?php echo e($fixture['away_club_name']); ?></p>
                        </div>
                    </div>
                </div>
            </div>
        </article>
    </div>
</section>

<?php if (can_submit_match_results() && (string) ($fixture['result_status'] ?? '') !== 'verified'): ?>
    <section class="panel-card mt-4">
        <div class="panel-card-header mb-3">
            <div>
                <p class="eyebrow mb-1">Submission</p>
                <h3 class="h5 mb-0">Submit or update result</h3>
            </div>
        </div>
        <form method="post" action="<?php echo e(base_url('app/modules/matches/actions.php')); ?>" novalidate>
            <?php echo csrf_input(); ?>
            <input type="hidden" name="action" value="submit_result">
            <input type="hidden" name="fixture_id" value="<?php echo e((string) $fixture['id']); ?>">
            <div class="row g-3 align-items-end">
                <div class="col-md-4">
                    <label class="form-label" for="home_score">Home score</label>
                    <input class="form-control <?php echo validation_error($formErrors, 'home_score') ? 'is-invalid' : ''; ?>" id="home_score" name="home_score" type="number" min="0" value="<?php echo e((string) old('home_score', (string) ($fixture['home_score'] ?? '0'))); ?>" required>
                    <?php if (validation_error($formErrors, 'home_score')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'home_score')); ?></div><?php endif; ?>
                </div>
                <div class="col-md-4">
                    <label class="form-label" for="away_score">Away score</label>
                    <input class="form-control <?php echo validation_error($formErrors, 'away_score') ? 'is-invalid' : ''; ?>" id="away_score" name="away_score" type="number" min="0" value="<?php echo e((string) old('away_score', (string) ($fixture['away_score'] ?? '0'))); ?>" required>
                    <?php if (validation_error($formErrors, 'away_score')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'away_score')); ?></div><?php endif; ?>
                </div>
                <div class="col-md-4">
                    <button class="btn btn-jlfc" type="submit">Submit result</button>
                </div>
            </div>
        </form>
    </section>
<?php endif; ?>

<?php if (can_verify_match_results() && $fixture['result_id'] !== null && (string) ($fixture['result_status'] ?? '') !== 'verified'): ?>
    <section class="panel-card mt-4">
        <div class="panel-card-header mb-3">
            <div>
                <p class="eyebrow mb-1">Verification</p>
                <h3 class="h5 mb-0">Approve submitted scoreline</h3>
            </div>
        </div>
        <p class="text-muted">Verification marks the result as official and recalculates the league table for league competitions.</p>
        <form method="post" action="<?php echo e(base_url('app/modules/matches/actions.php')); ?>">
            <?php echo csrf_input(); ?>
            <input type="hidden" name="action" value="verify_result">
            <input type="hidden" name="fixture_id" value="<?php echo e((string) $fixture['id']); ?>">
            <button class="btn btn-jlfc" type="submit">Verify result</button>
        </form>
    </section>
<?php endif; ?>

<?php if (can_manage_match_events()): ?>
    <section class="row g-4 mt-1">
        <div class="col-12 col-xl-7">
            <article class="panel-card h-100">
                <div class="panel-card-header mb-3">
                    <div>
                        <p class="eyebrow mb-1">Match events</p>
                        <h3 class="h5 mb-0">Timeline</h3>
                    </div>
                </div>
                <?php if ($events === []): ?>
                    <p class="text-muted mb-0">No match events have been recorded for this fixture yet.</p>
                <?php else: ?>
                    <div class="d-flex flex-column gap-3">
                        <?php foreach ($events as $event): ?>
                            <div class="d-flex justify-content-between gap-3 border rounded-3 p-3">
                                <div>
                                    <div class="d-flex gap-2 align-items-center mb-1">
                                        <span class="badge <?php echo e(match_event_badge_class($event['event_type'])); ?>"><?php echo e(ucwords(str_replace('_', ' ', $event['event_type']))); ?></span>
                                        <span class="small text-muted"><?php echo e((string) $event['minute']); ?><?php echo $event['extra_minute'] !== null ? '+' . e((string) $event['extra_minute']) : ''; ?>'</span>
                                    </div>
                                    <strong><?php echo e($event['player_first_name'] && $event['player_last_name'] ? trim($event['player_first_name'] . ' ' . $event['player_last_name']) : $event['club_name']); ?></strong>
                                    <div class="small text-muted"><?php echo e($event['club_name']); ?></div>
                                    <?php if ($event['related_first_name'] && $event['related_last_name']): ?>
                                        <div class="small text-muted">Related player: <?php echo e(trim($event['related_first_name'] . ' ' . $event['related_last_name'])); ?></div>
                                    <?php endif; ?>
                                    <?php if ($event['notes']): ?>
                                        <div class="small text-muted mt-1"><?php echo e($event['notes']); ?></div>
                                    <?php endif; ?>
                                </div>
                                <div>
                                    <form method="post" action="<?php echo e(base_url('app/modules/matches/actions.php')); ?>">
                                        <?php echo csrf_input(); ?>
                                        <input type="hidden" name="action" value="delete_event">
                                        <input type="hidden" name="event_id" value="<?php echo e((string) $event['id']); ?>">
                                        <button class="btn btn-outline-danger btn-sm" type="submit">Delete</button>
                                    </form>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </article>
        </div>
        <div class="col-12 col-xl-5">
            <article class="panel-card h-100">
                <div class="panel-card-header mb-3">
                    <div>
                        <p class="eyebrow mb-1">Event capture</p>
                        <h3 class="h5 mb-0">Add match event</h3>
                    </div>
                </div>
                <form method="post" action="<?php echo e(base_url('app/modules/matches/actions.php')); ?>" novalidate>
                    <?php echo csrf_input(); ?>
                    <input type="hidden" name="action" value="create_event">
                    <input type="hidden" name="fixture_id" value="<?php echo e((string) $fixture['id']); ?>">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label" for="club_id">Club</label>
                            <select class="form-select <?php echo validation_error($formErrors, 'club_id') ? 'is-invalid' : ''; ?>" id="club_id" name="club_id" required>
                                <option value="">Select club</option>
                                <option value="<?php echo e((string) $fixture['home_club_id']); ?>" <?php echo (int) old('club_id') === (int) $fixture['home_club_id'] ? 'selected' : ''; ?>><?php echo e($fixture['home_club_name']); ?></option>
                                <option value="<?php echo e((string) $fixture['away_club_id']); ?>" <?php echo (int) old('club_id') === (int) $fixture['away_club_id'] ? 'selected' : ''; ?>><?php echo e($fixture['away_club_name']); ?></option>
                            </select>
                            <?php if (validation_error($formErrors, 'club_id')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'club_id')); ?></div><?php endif; ?>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="event_type">Event type</label>
                            <select class="form-select <?php echo validation_error($formErrors, 'event_type') ? 'is-invalid' : ''; ?>" id="event_type" name="event_type" required>
                                <option value="">Select type</option>
                                <?php foreach (match_event_type_options() as $eventType): ?>
                                    <option value="<?php echo e($eventType); ?>" <?php echo old('event_type') === $eventType ? 'selected' : ''; ?>><?php echo e(ucwords(str_replace('_', ' ', $eventType))); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <?php if (validation_error($formErrors, 'event_type')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'event_type')); ?></div><?php endif; ?>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="player_id">Player</label>
                            <select class="form-select <?php echo validation_error($formErrors, 'player_id') ? 'is-invalid' : ''; ?>" id="player_id" name="player_id">
                                <option value="">Select player</option>
                                <?php foreach ($eventPlayers as $player): ?>
                                    <option value="<?php echo e((string) $player['id']); ?>" <?php echo (int) old('player_id') === (int) $player['id'] ? 'selected' : ''; ?>><?php echo e(trim($player['first_name'] . ' ' . $player['last_name'])); ?> - <?php echo e($player['club_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <?php if (validation_error($formErrors, 'player_id')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'player_id')); ?></div><?php endif; ?>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="related_player_id">Related player</label>
                            <select class="form-select <?php echo validation_error($formErrors, 'related_player_id') ? 'is-invalid' : ''; ?>" id="related_player_id" name="related_player_id">
                                <option value="">Optional</option>
                                <?php foreach ($eventPlayers as $player): ?>
                                    <option value="<?php echo e((string) $player['id']); ?>" <?php echo (int) old('related_player_id') === (int) $player['id'] ? 'selected' : ''; ?>><?php echo e(trim($player['first_name'] . ' ' . $player['last_name'])); ?> - <?php echo e($player['club_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <?php if (validation_error($formErrors, 'related_player_id')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'related_player_id')); ?></div><?php endif; ?>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="minute">Minute</label>
                            <input class="form-control <?php echo validation_error($formErrors, 'minute') ? 'is-invalid' : ''; ?>" id="minute" name="minute" type="number" min="0" value="<?php echo e((string) old('minute')); ?>" required>
                            <?php if (validation_error($formErrors, 'minute')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'minute')); ?></div><?php endif; ?>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="extra_minute">Additional minute</label>
                            <input class="form-control <?php echo validation_error($formErrors, 'extra_minute') ? 'is-invalid' : ''; ?>" id="extra_minute" name="extra_minute" type="number" min="0" value="<?php echo e((string) old('extra_minute')); ?>">
                            <?php if (validation_error($formErrors, 'extra_minute')): ?><div class="invalid-feedback"><?php echo e((string) validation_error($formErrors, 'extra_minute')); ?></div><?php endif; ?>
                        </div>
                        <div class="col-12">
                            <label class="form-label" for="notes">Notes</label>
                            <textarea class="form-control" id="notes" name="notes" rows="3"><?php echo e((string) old('notes')); ?></textarea>
                        </div>
                    </div>
                    <button class="btn btn-jlfc mt-4" type="submit">Add event</button>
                </form>
            </article>
        </div>
    </section>
<?php endif; ?>
<?php require dirname(__DIR__, 2) . '/includes/footer.php'; ?>