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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: training_attendance.php');
    exit();
}

$manager_id = $_SESSION['user_id'];
$session_date = $_POST['session_date'] ?? null;
$attendance_data = $_POST['attendance'] ?? [];

// --- Validation ---
if (empty($session_date) || empty($attendance_data)) {
    header('Location: record_attendance.php?error=missing_data');
    exit();
}

// --- Get Team ID ---
$teamModel = new Team();
$team = $teamModel->getTeamByManagerId($manager_id);
if (!$team) {
    header('Location: my_team.php?error=no_team');
    exit();
}

// --- Save to Database ---
$trainingModel = new Training();
if ($trainingModel->recordAttendance($team->id, $session_date, $attendance_data)) {
    header('Location: /smart_football/app/training_attendance.php?status=success');
} else {
    header('Location: /smart_football/app/record_attendance.php?error=db_error');
}
exit();
?>