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

// --- Authentication and Role Check ---
$admin_roles = ['super_admin', 'admin', 'league_manager'];
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], $admin_roles, true)) {
    header('Location: /smart_football/app/login.php');
    exit();
}

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

$team_id = filter_input(INPUT_POST, 'team_id', FILTER_VALIDATE_INT);
$action = $_POST['action'] ?? '';

if (!$team_id || !in_array($action, ['approve', 'reject'])) {
    header('Location: manage_rosters.php?error=invalid_action');
    exit();
}

$teamModel = new Team();
$notificationModel = new Notification();

// Get team details to notify the manager
$team = $teamModel->findById($team_id); // Using findById which exists in Team model

$new_status = ($action === 'approve') ? 'approved' : 'draft'; // Rejecting sends it back to draft
$rejection_reason = trim($_POST['rejection_reason'] ?? '');

if ($teamModel->updateRosterStatus($team_id, $new_status)) {
    if ($team && $team->manager_id) {
        $msg_status = ($action === 'approve') ? 'approved' : 'rejected';
        $message = "Your roster for {$team->name} has been {$msg_status}.";
        if ($action === 'reject' && !empty($rejection_reason)) {
            $message .= " Reason: " . $rejection_reason;
        }
        $notificationModel->create($team->manager_id, 'roster_update', $message);
    }
    header('Location: manage_rosters.php?status=success');
} else {
    header('Location: manage_rosters.php?error=update_failed');
}
exit();
?>