<?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: /smart_football/app/training_attendance.php');
    exit();
}

$session_id = filter_input(INPUT_POST, 'session_id', FILTER_VALIDATE_INT);
$session_date = $_POST['session_date'] ?? null;
$attendance_data = $_POST['attendance'] ?? [];

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

// --- Security Check (ensure manager owns this session) ---
$teamModel = new Team();
$trainingModel = new Training();
$team = $teamModel->getTeamByManagerId($_SESSION['user_id']);
if (!$team || !$trainingModel->checkSessionBelongsToManager($session_id, $team->id)) {
    header('Location: /smart_football/app/training_attendance.php?error=access_denied');
    exit();
}

// --- Save to Database ---
if ($trainingModel->updateAttendance($session_id, $session_date, $attendance_data)) {
    header('Location: /smart_football/app/training_session_detail.php?id=' . $session_id . '&status=updated');
} else {
    header('Location: /smart_football/app/edit_attendance.php?id=' . $session_id . '&error=db_error');
}
exit();
?>