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

// --- Get Data ---
$fixture_id = filter_input(INPUT_POST, 'fixture_id', FILTER_VALIDATE_INT);
$starting_players_with_pos = $_POST['starters'] ?? [];
$substitutes = $_POST['substitutes'] ?? [];
$formation = $_POST['formation'] ?? '4-4-2';
$manager_id = $_SESSION['user_id'];

// --- Validation ---
if (empty($fixture_id) || count($starting_players_with_pos) !== 11) {
    header('Location: /smart_football/app/submit_lineup.php?fixture_id=' . $fixture_id . '&error=invalid_starters');
    exit();
}

// Ensure a player isn't both a starter and a sub
$intersection = array_intersect(array_keys($starting_players_with_pos), $substitutes);
if (!empty($intersection)) {
    header('Location: /smart_football/app/submit_lineup.php?fixture_id=' . $fixture_id . '&error=player_conflict');
    exit();
}

// --- Security Check (ensure manager owns this team) ---
$teamModel = new Team();
$team = $teamModel->getTeamByManagerId($manager_id);
if (!$team) {
    header('Location: /smart_football/app/my_team.php?error=no_team');
    exit();
}

// --- Save to Database ---
$lineupModel = new Lineup();
if ($lineupModel->saveLineup($fixture_id, $team->id, $starting_players_with_pos, $substitutes, $formation)) {
    
    // --- Notifications ---
    $notificationModel = new Notification();
    $fixtureModel = new Fixture();
    $fixture = $fixtureModel->findById($fixture_id);
    
    if ($fixture) {
        $match_date = date('D, d M H:i', strtotime($fixture->match_datetime));
        $opponent_name = ($fixture->home_team_id == $team->id) ? $fixture->away_team_name : $fixture->home_team_name;

        // 1. Notify Starters
        foreach (array_keys($starting_players_with_pos) as $player_id) {
            $notificationModel->create($player_id, 'lineup_selection', "You have been selected in the starting XI for the match against {$opponent_name} on {$match_date}.");
        }

        // 2. Notify Substitutes
        foreach ($substitutes as $player_id) {
            $notificationModel->create($player_id, 'lineup_selection', "You have been selected as a substitute for the match against {$opponent_name} on {$match_date}.");
        }

        // 3. Notify Club Members (Upcoming Game)
        if (!empty($team->club_id)) {
            $team_name = $team->name ?? 'Team';
            $link = "/smart_football/app/feed_post.php?type=lineups_announced&id={$fixture_id}";
            $message = "Upcoming Match: " . htmlspecialchars($team_name) . " vs " . htmlspecialchars($opponent_name) . " on {$match_date}. The team lineup has been announced. <a href='{$link}' style='text-decoration: underline; font-weight: bold;'>View Preview</a>";
            
            $db = new Database();
            $db->query("SELECT user_id FROM memberships WHERE club_id = :club_id AND expiry_date >= CURDATE()");
            $db->bind(':club_id', $team->club_id);
            $members = $db->resultSet();

            foreach ($members as $member) {
                $notificationModel->create($member->user_id, 'upcoming_match', $message);
            }
        }
    }

    // Success! Redirect back to the lineup page to show the confirmation.
    header('Location: /smart_football/app/submit_lineup.php?fixture_id=' . $fixture_id . '&status=lineup_submitted');
    exit();
} else {
    // Handle database error
    header('Location: /smart_football/app/submit_lineup.php?fixture_id=' . $fixture_id . '&error=db_error');
    exit();
}
?>