<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

reports_module_boot();

$pageTitle = 'Reports';
$filters = reports_filters_from_request($_GET);
$filterLabels = report_filter_labels($filters);
$summary = reports_summary_cards($filters);
$standingsRows = standings_report_rows($filters);
$financeRows = finance_report_rows($filters);
$disciplineRows = discipline_report_rows($filters);
$protestRows = protests_report_rows($filters);
$pausedSeasonRows = paused_season_report_rows();
$postponedFixtureRows = postponed_fixture_report_rows();

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>
            <h2 class="h4 mb-0">Reports and exports</h2>
            <div class="small text-muted mt-1">Season: <?php echo e($filterLabels['season']); ?> · Competition: <?php echo e($filterLabels['competition']); ?></div>
        </div>
    </div>
    <form class="row g-3" method="get" action="<?php echo e(base_url('app/modules/reports/index.php')); ?>">
        <div class="col-md-4">
            <label class="form-label" for="season_id">Season</label>
            <select class="form-select" id="season_id" name="season_id">
                <option value="0">All seasons</option>
                <?php foreach (report_season_options() as $season): ?>
                    <option value="<?php echo e((string) $season['id']); ?>" <?php echo (int) $filters['season_id'] === (int) $season['id'] ? 'selected' : ''; ?>><?php echo e($season['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-4">
            <label class="form-label" for="competition_id">Competition</label>
            <select class="form-select" id="competition_id" name="competition_id">
                <option value="0">All competitions</option>
                <?php foreach (report_competition_options() as $competition): ?>
                    <option value="<?php echo e((string) $competition['id']); ?>" <?php echo (int) $filters['competition_id'] === (int) $competition['id'] ? 'selected' : ''; ?>><?php echo e($competition['name']); ?> (<?php echo e($competition['season_name']); ?>)</option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-4 d-flex align-items-end gap-2">
            <button class="btn btn-jlfc" type="submit">Apply filters</button>
            <a class="btn btn-outline-jlfc" href="<?php echo e(base_url('app/modules/reports/index.php')); ?>">Reset</a>
        </div>
    </form>
</section>

<section class="row g-3 mb-4">
    <div class="col-md-3">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-table"></i></div><span class="metric-label">Table rows</span><strong class="metric-value"><?php echo e((string) $summary['table_rows']); ?></strong><small class="text-muted">Standings entries</small>
        </article>
    </div>
    <div class="col-md-3">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-cash-coin"></i></div><span class="metric-label">Outstanding</span><strong class="metric-value"><?php echo e(number_format((float) $summary['outstanding_balance'], 2)); ?></strong><small class="text-muted">Unsettled finance</small>
        </article>
    </div>
    <div class="col-md-3">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-shield-exclamation"></i></div><span class="metric-label">Discipline cases</span><strong class="metric-value"><?php echo e((string) $summary['open_cases']); ?></strong><small class="text-muted">Cases in scope</small>
        </article>
    </div>
    <div class="col-md-3">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-megaphone-fill"></i></div><span class="metric-label">Open protests</span><strong class="metric-value"><?php echo e((string) $summary['open_protests']); ?></strong><small class="text-muted">Submitted or under review</small>
        </article>
    </div>
    <div class="col-md-3">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-pause-circle"></i></div><span class="metric-label">Paused seasons</span><strong class="metric-value"><?php echo e((string) $summary['paused_seasons']); ?></strong><small class="text-muted">Current seasonal holds</small>
        </article>
    </div>
    <div class="col-md-3">
        <article class="metric-card h-100">
            <div class="metric-icon"><i class="bi bi-calendar-x"></i></div><span class="metric-label">Postponed fixtures</span><strong class="metric-value"><?php echo e((string) $summary['postponed_fixtures']); ?></strong><small class="text-muted">Matches awaiting new dates</small>
        </article>
    </div>
</section>

<section class="row g-4 mb-4">
    <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">Operations</p>
                    <h3 class="h5 mb-0">Paused seasons</h3>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Season</th>
                            <th>Dates</th>
                            <th>Paused at</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($pausedSeasonRows === []): ?><tr>
                                <td colspan="3" class="text-center text-muted py-4">No paused seasons right now.</td>
                            </tr><?php endif; ?>
                        <?php foreach ($pausedSeasonRows as $row): ?>
                            <tr>
                                <td><?php echo e($row['name']); ?><div class="small text-muted"><?php echo e((string) $row['competition_count']); ?> competitions</div>
                                </td>
                                <td><?php echo e($row['start_date']); ?><div class="small text-muted">to <?php echo e($row['end_date']); ?></div>
                                </td>
                                <td><?php echo e((string) ($row['paused_at'] ?: 'Pending timestamp')); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </article>
    </div>
    <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">Operations</p>
                    <h3 class="h5 mb-0">Postponed fixtures</h3>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Fixture</th>
                            <th>Competition</th>
                            <th>Scheduled</th>
                            <th>Reason</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($postponedFixtureRows === []): ?><tr>
                                <td colspan="4" class="text-center text-muted py-4">No postponed fixtures right now.</td>
                            </tr><?php endif; ?>
                        <?php foreach ($postponedFixtureRows as $row): ?>
                            <tr>
                                <td><?php echo e($row['home_club_name']); ?> vs <?php echo e($row['away_club_name']); ?><div class="small text-muted">Matchday <?php echo e((string) $row['matchday']); ?></div>
                                </td>
                                <td><?php echo e($row['competition_name']); ?><div class="small text-muted"><?php echo e($row['season_name']); ?></div>
                                </td>
                                <td><?php echo e((string) ($row['match_date'] ?: 'TBD')); ?><div class="small text-muted"><?php echo e(format_time_12h($row['match_time'] ?? null, 'Time pending')); ?></div>
                                </td>
                                <td><?php echo e((string) ($row['postponement_reason'] ?: 'No reason saved')); ?><div class="small text-muted"><?php echo e((string) ($row['postponed_at'] ?: '')); ?></div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </article>
    </div>
</section>

<?php $filterQuery = http_build_query(['season_id' => $filters['season_id'], 'competition_id' => $filters['competition_id']]); ?>

<section class="panel-card mb-4">
    <div class="panel-card-header mb-3">
        <div>
            <p class="eyebrow mb-1">Standings</p>
            <h3 class="h5 mb-0">League table snapshot</h3>
        </div>
        <?php if (can_export_reports_module()): ?>
            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/modules/reports/export.php?report=standings&' . $filterQuery)); ?>">Export CSV</a>
        <?php endif; ?>
    </div>
    <div class="table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>Competition</th>
                    <th>Club</th>
                    <th>Pos</th>
                    <th>P</th>
                    <th>W</th>
                    <th>D</th>
                    <th>L</th>
                    <th>GD</th>
                    <th>Pts</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($standingsRows === []): ?><tr>
                        <td colspan="9" class="text-center text-muted py-4">No standings data found for the selected filters.</td>
                    </tr><?php endif; ?>
                <?php foreach ($standingsRows as $row): ?>
                    <tr>
                        <td><?php echo e($row['competition_name']); ?><div class="small text-muted"><?php echo e($row['season_name']); ?></div>
                        </td>
                        <td><?php echo e($row['club_name']); ?></td>
                        <td><?php echo e((string) $row['position']); ?></td>
                        <td><?php echo e((string) $row['played']); ?></td>
                        <td><?php echo e((string) $row['won']); ?></td>
                        <td><?php echo e((string) $row['drawn']); ?></td>
                        <td><?php echo e((string) $row['lost']); ?></td>
                        <td><?php echo e((string) $row['goal_difference']); ?></td>
                        <td><strong><?php echo e((string) $row['points']); ?></strong></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="panel-card mb-4">
    <div class="panel-card-header mb-3">
        <div>
            <p class="eyebrow mb-1">Finance</p>
            <h3 class="h5 mb-0">Collections and outstanding balances</h3>
        </div>
        <?php if (can_export_reports_module()): ?>
            <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/modules/reports/export.php?report=finance&' . $filterQuery)); ?>">Export CSV</a>
        <?php endif; ?>
    </div>
    <div class="table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>Club</th>
                    <th>Season</th>
                    <th>Type</th>
                    <th>Reference</th>
                    <th>Status</th>
                    <th>Outstanding</th>
                </tr>
            </thead>
            <tbody>
                <?php if ($financeRows === []): ?><tr>
                        <td colspan="6" class="text-center text-muted py-4">No finance records found for the selected filters.</td>
                    </tr><?php endif; ?>
                <?php foreach ($financeRows as $row): ?>
                    <tr>
                        <td><?php echo e($row['club_name']); ?></td>
                        <td><?php echo e($row['season_name']); ?></td>
                        <td><?php echo e(ucwords(str_replace('_', ' ', (string) $row['payment_type']))); ?></td>
                        <td><?php echo e($row['payment_reference']); ?></td>
                        <td><?php echo e(ucfirst((string) $row['payment_status'])); ?></td>
                        <td><?php echo e(number_format((float) $row['outstanding_amount'], 2)); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>

<section class="row g-4">
    <div class="col-12 col-xl-6">
        <article class="panel-card h-100">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Discipline</p>
                    <h3 class="h5 mb-0">Case review summary</h3>
                </div>
                <?php if (can_export_reports_module()): ?>
                    <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/modules/reports/export.php?report=discipline&' . $filterQuery)); ?>">Export CSV</a>
                <?php endif; ?>
            </div>
            <div class="table-responsive">
                <table class="table align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Case</th>
                            <th>Club/Player</th>
                            <th>Status</th>
                            <th>Fine</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($disciplineRows === []): ?><tr>
                                <td colspan="4" class="text-center text-muted py-4">No discipline records found.</td>
                            </tr><?php endif; ?>
                        <?php foreach ($disciplineRows as $row): ?>
                            <?php $playerName = trim((string) (($row['first_name'] ?? '') . ' ' . ($row['middle_name'] ?? '') . ' ' . ($row['last_name'] ?? ''))); ?>
                            <tr>
                                <td><?php echo e($row['case_type']); ?><div class="small text-muted"><?php echo e($row['competition_name'] ?: 'General'); ?></div>
                                </td>
                                <td><?php echo e($playerName !== '' ? $playerName : ($row['club_name'] ?: 'Unassigned')); ?></td>
                                <td><?php echo e(ucfirst((string) $row['status'])); ?></td>
                                <td><?php echo e(number_format((float) $row['fine_amount'], 2)); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </article>
    </div>
    <div class="col-12 col-xl-6">
        <article class="panel-card h-100">
            <div class="panel-card-header mb-3">
                <div>
                    <p class="eyebrow mb-1">Protests</p>
                    <h3 class="h5 mb-0">Governance case summary</h3>
                </div>
                <?php if (can_export_reports_module()): ?>
                    <a class="btn btn-outline-jlfc btn-sm" href="<?php echo e(base_url('app/modules/reports/export.php?report=protests&' . $filterQuery)); ?>">Export CSV</a>
                <?php endif; ?>
            </div>
            <div class="table-responsive">
                <table class="table align-middle mb-0">
                    <thead>
                        <tr>
                            <th>Title</th>
                            <th>Fixture pairing</th>
                            <th>Status</th>
                            <th>Resolved</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($protestRows === []): ?><tr>
                                <td colspan="4" class="text-center text-muted py-4">No protest records found.</td>
                            </tr><?php endif; ?>
                        <?php foreach ($protestRows as $row): ?>
                            <tr>
                                <td><?php echo e($row['title']); ?><div class="small text-muted"><?php echo e($row['competition_name']); ?></div>
                                </td>
                                <td><?php echo e($row['protesting_club_name']); ?> vs <?php echo e($row['against_club_name']); ?></td>
                                <td><?php echo e(ucwords(str_replace('_', ' ', (string) $row['status']))); ?></td>
                                <td><?php echo e((string) ($row['resolved_at'] ?: 'Open')); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </article>
    </div>
</section>
<?php require dirname(__DIR__, 2) . '/includes/footer.php'; ?>