<?php
$pageTitle = 'Manage Fixtures';
include_once 'includes/header.php';

// --- Auth Check ---
$allowed_roles = ['admin', 'super_admin', 'fixtures_manager', 'league_manager', 'finance_manager'];
if (!in_array($_SESSION['admin_user_role'] ?? '', $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$fixtureModel = new Fixture();
$all_fixtures = $fixtureModel->getAllFixturesWithDetails();

// Get all unique gameweeks for the filter dropdown
$available_gameweeks = [];
foreach ($all_fixtures as $f) {
    if ($f->gameweek) {
        $available_gameweeks[$f->gameweek] = true;
    }
}
ksort($available_gameweeks);
$available_gameweeks = array_keys($available_gameweeks);

// Filter Logic
$selected_gameweek = $_GET['gameweek'] ?? 'all';

// Group fixtures by gameweek
$fixtures_by_gameweek = [];
foreach ($all_fixtures as $fixture) {
    $gw = $fixture->gameweek ?? 'Unscheduled';
    
    // Apply Filter
    if ($selected_gameweek !== 'all' && (string)$gw !== (string)$selected_gameweek) {
        continue;
    }

    $fixtures_by_gameweek[$gw][] = $fixture;
}
ksort($fixtures_by_gameweek);

include_once 'includes/sidebar.php';
?>

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 10px;">
    <h1>Manage Fixtures</h1>
    <div style="display: flex; gap: 10px; align-items: center;">
        <form method="GET" action="manage_fixtures.php" style="margin: 0;">
            <select name="gameweek" onchange="this.form.submit()" style="padding: 8px; border-radius: 4px; border: 1px solid #ddd;">
                <option value="all" <?php echo $selected_gameweek === 'all' ? 'selected' : ''; ?>>All Gameweeks</option>
                <?php foreach ($available_gameweeks as $gw): ?>
                    <option value="<?php echo $gw; ?>" <?php echo (string)$selected_gameweek === (string)$gw ? 'selected' : ''; ?>>Gameweek <?php echo $gw; ?></option>
                <?php endforeach; ?>
            </select>
        </form>
        <button id="export-pdf-btn" class="btn btn-secondary" style="background-color: #e74c3c; border-color: #c0392b; color: white;"><i class="fa-solid fa-file-pdf"></i> Export PDF</button>
        <a href="add_fixture.php" class="btn btn-primary">Add Fixture</a>
        <a href="generate_fixtures.php" class="btn btn-secondary">Generate Fixtures</a>
    </div>
</div>

<?php if (isset($_SESSION['flash_message'])): ?>
    <div class="message success"><?php echo $_SESSION['flash_message']; unset($_SESSION['flash_message']); ?></div>
<?php endif; ?>
<?php if (isset($_SESSION['flash_error'])): ?>
    <div class="message error"><?php echo $_SESSION['flash_error']; unset($_SESSION['flash_error']); ?></div>
<?php endif; ?>

<div id="fixtures-content">
<?php if (empty($fixtures_by_gameweek)): ?>
    <div class="dashboard-section">
        <p class="no-data-msg">No fixtures found.</p>
    </div>
<?php else: ?>
    <?php foreach ($fixtures_by_gameweek as $gw => $fixtures): ?>
        <div class="dashboard-section">
            <h2 class="dashboard-title">Gameweek <?php echo htmlspecialchars($gw); ?></h2>
            <div class="table-wrapper">
                <table class="styled-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>League</th>
                            <th>Match</th>
                            <th>Status</th>
                            <th>Ref Fee</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($fixtures as $fixture): ?>
                            <tr>
                                <td><?php echo date('d M Y H:i', strtotime($fixture->match_datetime)); ?></td>
                                <td><?php echo htmlspecialchars($fixture->league_name); ?></td>
                                <td><?php echo htmlspecialchars($fixture->home_team_name . ' vs ' . $fixture->away_team_name); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo strtolower($fixture->status); ?>">
                                        <?php echo ucfirst($fixture->status); ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="status-badge status-<?php echo strtolower($fixture->referee_payment_status); ?>">
                                        <?php echo ucfirst($fixture->referee_payment_status); ?>
                                    </span>
                                </td>
                                <td>
                                    <div style="display: flex; gap: 5px;">
                                        <a href="edit_fixture.php?id=<?php echo $fixture->id; ?>" class="btn-sm btn-edit">Edit</a>
                                        
                                        <?php if ($fixture->status === 'scheduled'): ?>
                                            <form action="postpone_fixture.php" method="POST" onsubmit="return confirm('Are you sure you want to postpone this match?');">
                                                <input type="hidden" name="fixture_id" value="<?php echo $fixture->id; ?>">
                                                <button type="submit" class="btn-sm" style="background-color: #6c757d; color: white; border: none; cursor: pointer;" title="Postpone Match"><i class="fa-solid fa-clock"></i> Postpone</button>
                                            </form>
                                        <?php endif; ?>

                                        <?php if ($fixture->referee_payment_status === 'pending'): ?>
                                            <form action="manual_finance_process.php" method="POST" onsubmit="return confirm('Mark referee fee as paid for this match?');">
                                                <input type="hidden" name="action" value="mark_ref_fee_paid">
                                                <input type="hidden" name="fixture_id" value="<?php echo $fixture->id; ?>">
                                                <button type="submit" class="btn-sm btn-success" title="Mark Fee Paid"><i class="fa-solid fa-check"></i> Pay Fee</button>
                                            </form>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endforeach; ?>
<?php endif; ?>
</div>

<style>
.status-badge { padding: 4px 10px; border-radius: 12px; font-size: 0.75rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px; }
.status-paid { background-color: #d4edda; color: #155724; }
.status-pending { background-color: #fff3cd; color: #856404; }
.status-scheduled { background-color: #e2e3e5; color: #383d41; }
.status-live { background-color: #f8d7da; color: #721c24; }
.status-finished { background-color: #d1e7dd; color: #0f5132; }
.status-postponed { background-color: #6c757d; color: white; }
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script>
document.getElementById('export-pdf-btn').addEventListener('click', function() {
    const element = document.getElementById('fixtures-content');
    const opt = {
        margin: 5,
        filename: 'Fixtures_Report_<?php echo $selected_gameweek; ?>.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2 },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'landscape' }
    };
    html2pdf().set(opt).from(element).save();
});
</script>

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