<?php
$pageTitle = 'Pay Referees';
include_once 'includes/header.php';

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

$db = new Database();
$settingModel = new Setting();
$leagueModel = new League();
$fixtureModel = new Fixture();

// --- Auto-Migration for board_paid_referee column ---
try {
    $db->query("SELECT board_paid_referee FROM fixtures LIMIT 1");
    $db->execute();
} catch (Exception $e) {
    $db->query("ALTER TABLE fixtures ADD COLUMN board_paid_referee TINYINT(1) NOT NULL DEFAULT 0");
    $db->execute();
}

$settings = $settingModel->getAll();
$board_fee = (float)($settings['board_referee_fee'] ?? 0);
$currency_symbol = ($settings['system_currency'] ?? 'USD') === 'ZMW' ? 'K' : '$';

// Filters
$league_id = filter_input(INPUT_GET, 'league_id', FILTER_VALIDATE_INT);
$gameweek = filter_input(INPUT_GET, 'gameweek', FILTER_VALIDATE_INT);

$leagues = $leagueModel->getAll();
if (!$league_id && !empty($leagues)) {
    $league_id = $leagues[0]->id;
}

// Get Gameweeks
$gameweeks = [];
if ($league_id) {
    $db->query("SELECT DISTINCT gameweek FROM fixtures WHERE league_id = :lid ORDER BY gameweek DESC");
    $db->bind(':lid', $league_id);
    $gameweeks = $db->resultSet();
    if (!$gameweek && !empty($gameweeks)) {
        $gameweek = $gameweeks[0]->gameweek;
    }
}

// Fetch Fixtures
$fixtures = [];
if ($league_id && $gameweek) {
    $db->query("
        SELECT f.*, 
               t1.name as home_team, 
               t2.name as away_team,
               u.first_name as ref_first, u.last_name as ref_last, u.email as ref_email
        FROM fixtures f
        JOIN teams t1 ON f.home_team_id = t1.id
        JOIN teams t2 ON f.away_team_id = t2.id
        LEFT JOIN users u ON f.referee_id = u.id
        WHERE f.league_id = :lid AND f.gameweek = :gw AND f.status = 'finished'
        ORDER BY f.match_datetime ASC
    ");
    $db->bind(':lid', $league_id);
    $db->bind(':gw', $gameweek);
    $fixtures = $db->resultSet();
}

include_once 'includes/sidebar.php';
?>

<h1>Pay Referees</h1>
<p>Process Board payments for referees for completed matches.</p>

<?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 class="dashboard-section">
    <form method="GET" action="pay_referees.php" style="display: flex; gap: 15px; align-items: flex-end; margin-bottom: 20px;">
        <div class="form-group" style="margin-bottom: 0;">
            <label>League</label>
            <select name="league_id" onchange="this.form.submit()">
                <?php foreach ($leagues as $l): ?>
                    <option value="<?php echo $l->id; ?>" <?php echo $l->id == $league_id ? 'selected' : ''; ?>><?php echo htmlspecialchars($l->name); ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="form-group" style="margin-bottom: 0;">
            <label>Gameweek</label>
            <select name="gameweek" onchange="this.form.submit()">
                <?php foreach ($gameweeks as $gw): ?>
                    <option value="<?php echo $gw->gameweek; ?>" <?php echo $gw->gameweek == $gameweek ? 'selected' : ''; ?>>GW <?php echo $gw->gameweek; ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </form>

    <div class="info-box" style="background: #e8f4f8; padding: 15px; border-radius: 5px; margin-bottom: 20px; border-left: 4px solid #3498db;">
        <strong>Board Fee Setting:</strong> <?php echo $currency_symbol . number_format($board_fee, 2); ?> per match.
        <a href="settings.php" style="margin-left: 10px; font-size: 0.9rem;">Change in Settings</a>
    </div>

    <div class="table-wrapper">
        <table class="styled-table">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Match</th>
                    <th>Referee</th>
                    <th>Team Fees</th>
                    <th>Board Fee Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($fixtures)): ?>
                    <tr><td colspan="6">No finished matches found for this gameweek.</td></tr>
                <?php else: ?>
                    <?php foreach ($fixtures as $f): ?>
                        <tr>
                            <td><?php echo date('d M H:i', strtotime($f->match_datetime)); ?></td>
                            <td><?php echo htmlspecialchars($f->home_team . ' vs ' . $f->away_team); ?></td>
                            <td>
                                <?php if ($f->referee_id): ?>
                                    <?php echo htmlspecialchars($f->ref_first . ' ' . $f->ref_last); ?>
                                <?php else: ?>
                                    <span style="color: #999;">Not Assigned</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($f->home_team_paid_referee && $f->away_team_paid_referee): ?>
                                    <span class="badge status-paid">Both Paid</span>
                                <?php else: ?>
                                    <span class="badge status-pending">
                                        <?php 
                                        $paid = [];
                                        if ($f->home_team_paid_referee) $paid[] = 'Home';
                                        if ($f->away_team_paid_referee) $paid[] = 'Away';
                                        echo empty($paid) ? 'None Paid' : implode(', ', $paid) . ' Paid';
                                        ?>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($f->board_paid_referee): ?>
                                    <span class="badge status-paid">Paid</span>
                                <?php else: ?>
                                    <span class="badge status-pending">Pending</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if (!$f->board_paid_referee && $f->referee_id): ?>
                                    <form action="process_referee_payment.php" method="POST" onsubmit="return confirm('Pay <?php echo $currency_symbol . $board_fee; ?> to referee from Board Wallet?');">
                                        <input type="hidden" name="fixture_id" value="<?php echo $f->id; ?>">
                                        <input type="hidden" name="redirect_url" value="pay_referees.php?league_id=<?php echo $league_id; ?>&gameweek=<?php echo $gameweek; ?>">
                                        <button type="submit" class="btn-sm btn-primary">Pay Board Fee</button>
                                    </form>
                                <?php elseif ($f->board_paid_referee): ?>
                                    <button class="btn-sm" disabled style="opacity: 0.6; cursor: default;">Paid</button>
                                <?php else: ?>
                                    <span style="font-size: 0.8rem; color: #999;">No Referee</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<style>
.status-paid { background-color: #d4edda; color: #155724; }
.status-pending { background-color: #fff3cd; color: #856404; }
</style>

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