<?php
$pageTitle = 'Record Attendance';
include 'includes/header.php';

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

// --- Instantiate Models and Fetch Data ---
$teamModel = new Team();
$playerModel = new Player();

$team = $teamModel->getTeamByManagerId($manager_id);
$team_players = $team ? $playerModel->getPlayersByTeamId($team->id) : [];

if (!$team) {
    header('Location: my_team.php');
    exit();
}
?>

<div class="page-content">
    <div class="matches-header">
        <h1>Record Training Attendance</h1>
    </div>

    <div class="form-container">
        <form action="/smart_football/app/record_attendance_process.php" method="POST" class="auth-form" style="max-width: 700px; margin: auto;">
            <div class="form-group">
                <label for="session_date">Session Date</label>
                <input type="date" id="session_date" name="session_date" value="<?php echo date('Y-m-d'); ?>" required>
            </div>

            <h3 style="margin-top: 2rem; margin-bottom: 1rem;">Player Attendance</h3>
            <div class="table-wrapper">
                <table class="styled-table">
                    <thead><tr><th>Player</th><th>Status</th></tr></thead>
                    <tbody>
                        <?php foreach ($team_players as $player): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($player->first_name . ' ' . $player->last_name); ?></td>
                                <td>
                                    <select name="attendance[<?php echo $player->id; ?>]" required>
                                        <option value="Present" selected>Present</option>
                                        <option value="Absent">Absent</option>
                                        <option value="Excused">Excused</option>
                                    </select>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <button type="submit" style="margin-top: 1.5rem;">Save Attendance</button>
        </form>
    </div>
</div>

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