<?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') {
    // Redirect if accessed directly
    header('Location: add_injury.php');
    exit();
}

// --- Get and Sanitize Data ---
$data = [
    'player_id' => filter_input(INPUT_POST, 'player_id', FILTER_VALIDATE_INT),
    'injury_description' => trim(filter_input(INPUT_POST, 'injury_description', FILTER_SANITIZE_STRING)),
    'start_date' => $_POST['start_date'], // Basic validation, more can be added
    'expected_return_date' => !empty($_POST['expected_return_date']) ? $_POST['expected_return_date'] : null
];

// --- Validation ---
if (empty($data['player_id']) || empty($data['injury_description']) || empty($data['start_date'])) {
    // Handle error - missing required fields
    header('Location: add_injury.php?error=missing_fields');
    exit();
}

// --- Save to Database ---
$playerModel = new Player();
if ($playerModel->addInjuryRecord($data)) {
    // Notify manager if a return date is set
    if (!empty($data['expected_return_date'])) {
        $player = $playerModel->getPlayerDetailsById($data['player_id']);
        $notificationModel = new Notification();
        $msg = "Injury Report: {$player->first_name} {$player->last_name} is expected to return on " . date('d M Y', strtotime($data['expected_return_date'])) . ".";
        $notificationModel->create($_SESSION['user_id'], 'injury_update', $msg);
    }

    // Success! Redirect to the injury list page.
    header('Location: /smart_football/app/injury_list.php?status=added');
    exit();
} else {
    // Handle database error
    header('Location: /smart_football/app/add_injury.php?error=db_error');
    exit();
}
?>