<?php
require_once '../core/bootstrap.php';

// --- Authentication Check ---
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'referee') {
    header('Location: login.php');
    exit();
}

$referee_id = $_SESSION['user_id'];
$fixture_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
$db = new Database();
$msg = '';
$error = '';

// Verify Fixture Assignment
if ($fixture_id) {
    $db->query("SELECT f.*, t1.name as home_team, c1.logo as home_team_logo, t2.name as away_team, c2.logo as away_team_logo 
                FROM fixtures f 
                JOIN teams t1 ON f.home_team_id = t1.id 
                JOIN clubs c1 ON t1.club_id = c1.id
                JOIN teams t2 ON f.away_team_id = t2.id 
                JOIN clubs c2 ON t2.club_id = c2.id
                WHERE f.id = :id AND f.referee_id = :referee_id");
    $db->bind(':id', $fixture_id);
    $db->bind(':referee_id', $referee_id);
    $fixture = $db->single();

} else {
    header('Location: referee_matches.php');
    exit();
}

$pageTitle = 'Submit Referee Report';
include 'includes/header.php';

if (!$fixture) {
    echo "<div class='page-content'><p class='error-msg'>Match not found or you are not the assigned referee.</p></div>";
    include 'includes/footer.php';
    exit();
}

// Handle Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $incident_type = $_POST['incident_type'];
    $minute = !empty($_POST['minute']) ? (int)$_POST['minute'] : null;
    $description = trim($_POST['description']);

    if (empty($incident_type) || empty($description)) {
        $error = "Please fill in all required fields.";
    } else {
        $db->query("INSERT INTO referee_reports (fixture_id, referee_id, incident_type, minute, description) VALUES (:fid, :rid, :type, :min, :desc)");
        $db->bind(':fid', $fixture_id);
        $db->bind(':rid', $referee_id);
        $db->bind(':type', $incident_type);
        $db->bind(':min', $minute);
        $db->bind(':desc', $description);

        if ($db->execute()) {
            $msg = "Report submitted successfully.";
        } else {
            $error = "Failed to submit report.";
        }
    }
}

// Fetch Previous Reports for this Match
$db->query("SELECT * FROM referee_reports WHERE fixture_id = :fid ORDER BY created_at DESC");
$db->bind(':fid', $fixture_id);
$previous_reports = $db->resultSet();
?>

<div class="page-content">
    <div class="dashboard-section">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h2 class="dashboard-title" style="margin: 0;">Match Report</h2>
            <a href="referee_matches.php" class="btn-sm btn-secondary">Back to Matches</a>
        </div>
        
        <div class="match-summary-card">
            <div class="team-info">
                <span class="team-name"><?php echo htmlspecialchars($fixture->home_team); ?></span>
                <img src="<?php echo htmlspecialchars($fixture->home_team_logo); ?>" class="team-logo" alt="">
            </div>
            <div class="match-meta">
                <span class="vs">VS</span>
                <span class="date"><?php echo date('d M Y, H:i', strtotime($fixture->match_datetime)); ?></span>
            </div>
            <div class="team-info">
                <img src="<?php echo htmlspecialchars($fixture->away_team_logo); ?>" class="team-logo" alt="">
                <span class="team-name"><?php echo htmlspecialchars($fixture->away_team); ?></span>
            </div>
        </div>

        <?php if ($msg): ?><div class="alert alert-success" style="background: #d4edda; color: #155724; padding: 10px; border-radius: 5px; margin-bottom: 15px;"><?php echo $msg; ?></div><?php endif; ?>
        <?php if ($error): ?><div class="alert alert-danger" style="background: #f8d7da; color: #721c24; padding: 10px; border-radius: 5px; margin-bottom: 15px;"><?php echo $error; ?></div><?php endif; ?>

        <form action="submit_report.php?id=<?php echo $fixture_id; ?>" method="POST" class="styled-form">
            <div class="form-group">
                <label for="incident_type">Incident Type</label>
                <select name="incident_type" id="incident_type" required>
                    <option value="">-- Select Incident --</option>
                    <option value="Red Card">Red Card</option>
                    <option value="Yellow Card">Yellow Card</option>
                    <option value="Penalty">Penalty Call</option>
                    <option value="Goal Controversy">Controversial Goal</option>
                    <option value="Crowd Trouble">Crowd Trouble</option>
                    <option value="Player Conduct">Player Conduct</option>
                    <option value="Staff Conduct">Staff/Manager Conduct</option>
                    <option value="Other">Other</option>
                </select>
            </div>

            <div class="form-group">
                <label for="minute">Minute (Optional)</label>
                <input type="number" name="minute" id="minute" min="1" max="130" placeholder="e.g. 45">
            </div>

            <div class="form-group">
                <label for="description">Detailed Description</label>
                <textarea name="description" id="description" rows="5" required placeholder="Describe the incident, players involved, and justification for the call..."></textarea>
            </div>

            <button type="submit" class="btn">Submit Report</button>
        </form>
    </div>

    <?php if (!empty($previous_reports)): ?>
    <div class="dashboard-section">
        <h3 class="dashboard-title">Submitted Reports for this Match</h3>
        <div class="table-wrapper">
            <table class="styled-table">
                <thead>
                    <tr>
                        <th>Time</th>
                        <th>Type</th>
                        <th>Minute</th>
                        <th>Description</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($previous_reports as $report): ?>
                        <tr>
                            <td><?php echo date('H:i', strtotime($report->created_at)); ?></td>
                            <td><span class="badge" style="background: #eee; color: #333; padding: 2px 6px; border-radius: 4px;"><?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; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
</div>

<style>
.match-summary-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
    border: 1px solid #eee;
}
.match-summary-card .team-info {
    display: flex;
    align-items: center;
    gap: 15px;
    flex: 1;
    font-weight: bold;
    font-size: 1.1rem;
}
.match-summary-card .team-info:first-child {
    justify-content: flex-end;
    text-align: right;
}
.match-summary-card .team-logo {
    width: 50px;
    height: 50px;
    object-fit: contain;
}
.match-summary-card .match-meta {
    text-align: center;
    padding: 0 20px;
    min-width: 120px;
}
.match-summary-card .vs {
    display: block;
    font-weight: 900;
    color: #ccc;
    font-size: 1.2rem;
}
.match-summary-card .date {
    display: block;
    font-size: 0.85rem;
    color: #7f8c8d;
    margin-top: 5px;
}
</style>

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