<?php
$pageTitle = 'Referee Reports';
include_once 'includes/header.php';

// --- Auth Check ---
$allowed_roles = ['admin', 'super_admin', 'league_manager', 'fixtures_manager'];
$role = $_SESSION['admin_user_role'] ?? $_SESSION['user_role'] ?? '';

if (!in_array($role, $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$db = new Database();

// Fetch Reports
$db->query("
    SELECT 
        rr.*,
        f.match_datetime,
        t1.name as home_team,
        t2.name as away_team,
        u.first_name as ref_first_name,
        u.last_name as ref_last_name,
        l.name as league_name
    FROM referee_reports rr
    JOIN fixtures f ON rr.fixture_id = f.id
    JOIN teams t1 ON f.home_team_id = t1.id
    JOIN teams t2 ON f.away_team_id = t2.id
    JOIN users u ON rr.referee_id = u.id
    JOIN leagues l ON f.league_id = l.id
    ORDER BY rr.created_at DESC
");
$reports = $db->resultSet();

include_once 'includes/sidebar.php';
?>

<h1>Referee Reports</h1>

<div class="dashboard-section">
    <div class="table-wrapper">
        <table class="styled-table">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Match</th>
                    <th>League</th>
                    <th>Referee</th>
                    <th>Incident</th>
                    <th>Min</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($reports)): ?>
                    <tr><td colspan="7" class="no-data-msg">No reports found.</td></tr>
                <?php else: ?>
                    <?php foreach ($reports as $report): ?>
                        <tr>
                            <td><?php echo date('d M Y', strtotime($report->match_datetime)); ?></td>
                            <td><?php echo htmlspecialchars($report->home_team . ' vs ' . $report->away_team); ?></td>
                            <td><?php echo htmlspecialchars($report->league_name); ?></td>
                            <td><?php echo htmlspecialchars($report->ref_first_name . ' ' . $report->ref_last_name); ?></td>
                            <td><span class="badge" style="background: #eee; color: #333;"><?php echo htmlspecialchars($report->incident_type); ?></span></td>
                            <td><?php echo $report->minute ? $report->minute . "'" : '-'; ?></td>
                            <td><?php echo nl2br(htmlspecialchars($report->description)); ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include_once 'includes/footer.php'; ?>