<?php
$pageTitle = 'Training Session Details';
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'];

$session_id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$session_id) {
    header('Location: /smart_football/app/training_attendance.php?error=invalid_id');
    exit();
}

// --- Instantiate Models and Fetch Data ---
$trainingModel = new Training();
$teamModel = new Team();

// Get manager's team for security check
$team = $teamModel->getTeamByManagerId($manager_id);
if (!$team || !$trainingModel->checkSessionBelongsToManager($session_id, $team->id)) {
    header('Location: /smart_football/app/training_attendance.php?error=access_denied');
    exit();
}

$session = $trainingModel->getSessionDetailsById($session_id);
if (!$session) {
    header('Location: /smart_football/app/training_attendance.php?error=not_found');
    exit();
}

?>

<div class="page-content">
    <div class="matches-header">
        <h1>Attendance for <?php echo date('l, F j, Y', strtotime($session->session_date)); ?></h1>
        <a href="/smart_football/app/edit_attendance.php?id=<?php echo $session->id; ?>" class="btn">Edit Attendance</a>
    </div>

    <div class="dashboard-section">
        <?php if (!empty($session->attendees)): ?>
            <div class="table-wrapper">
                <table class="styled-table">
                    <thead><tr><th>Player</th><th>Status</th></tr></thead>
                    <tbody>
                        <?php foreach ($session->attendees as $attendee): ?>
                            <tr>
                                <td><?php echo htmlspecialchars($attendee->first_name . ' ' . $attendee->last_name); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo strtolower($attendee->status); ?>">
                                        <?php echo htmlspecialchars($attendee->status); ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <p class="no-data-msg">No attendance records were found for this session.</p>
        <?php endif; ?>
    </div>
</div>

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