<?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: injury_list.php');
    exit();
}

// --- Get and Sanitize Data ---
$data = [
    'injury_id' => filter_input(INPUT_POST, 'injury_id', FILTER_VALIDATE_INT),
    'injury_description' => trim(filter_input(INPUT_POST, 'injury_description', FILTER_SANITIZE_STRING)),
    'start_date' => $_POST['start_date'],
    'expected_return_date' => !empty($_POST['expected_return_date']) ? $_POST['expected_return_date'] : null,
    'status' => $_POST['status']
];

// --- Validation ---
if (empty($data['injury_id']) || empty($data['injury_description']) || empty($data['start_date']) || empty($data['status'])) {
    header('Location: /smart_football/app/edit_injury.php?id=' . $data['injury_id'] . '&error=missing_fields');
    exit();
}

// --- Save to Database ---
$playerModel = new Player();
// Fetch existing details for notification context
$injury = $playerModel->getInjuryById($data['injury_id']);

if ($playerModel->updateInjuryRecord($data)) {
    // Notify manager of updates
    $notificationModel = new Notification();
    $player_name = $injury->first_name . ' ' . $injury->last_name;

    if ($data['status'] === 'Fit' && $injury->status !== 'Fit') {
        $notificationModel->create($_SESSION['user_id'], 'injury_update', "Good news! {$player_name} has recovered and is marked as Fit.");
    } elseif (!empty($data['expected_return_date']) && $data['expected_return_date'] !== $injury->expected_return_date) {
        $notificationModel->create($_SESSION['user_id'], 'injury_update', "Update: {$player_name} is now expected to return on " . date('d M Y', strtotime($data['expected_return_date'])) . ".");
    }

    // Success! Redirect to the injury list page.
    header('Location: /smart_football/app/injury_list.php?status=updated');
    exit();
} else {
    // Handle database error
    header('Location: /smart_football/app/edit_injury.php?id=' . $data['injury_id'] . '&error=db_error');
    exit();
}
?>