<?php

class Lineup {
    private $db;

    public function __construct() {
        $this->db = new Database;
    }

    /**
     * Saves a lineup for a specific fixture and team.
     * This is a transactional operation that first deletes any existing lineup.
     * @param int $fixture_id The ID of the fixture.
     * @param int $team_id The ID of the team.
     * @param array $starting_players An associative array of [player_id => played_position].
     * @param array $substitutes An array of player IDs for the substitutes.
     * @param string $formation The formation string (e.g., '4-4-2').
     * @return bool True on success, false on failure.
     */
    public function saveLineup($fixture_id, $team_id, $starting_players, $substitutes, $formation) {
        $this->db->beginTransaction();

        try {
            // 1. Delete any existing lineup for this team and fixture
            $this->db->query('DELETE FROM fixture_lineups WHERE fixture_id = :fixture_id AND team_id = :team_id');
            $this->db->bind(':fixture_id', $fixture_id);
            $this->db->bind(':team_id', $team_id);
            $this->db->execute();

            // 2. Insert starting players
            $this->db->query('INSERT INTO fixture_lineups (fixture_id, team_id, player_id, lineup_status, formation, played_position) VALUES (:fixture_id, :team_id, :player_id, "Starting", :formation, :played_position)');
            foreach ($starting_players as $player_id => $played_position) {
                $this->db->bind(':fixture_id', $fixture_id);
                $this->db->bind(':team_id', $team_id);
                $this->db->bind(':player_id', $player_id);
                $this->db->bind(':formation', $formation);
                $this->db->bind(':played_position', $played_position);
                $this->db->execute();
            }

            // 3. Insert substitutes
            $this->db->query('INSERT INTO fixture_lineups (fixture_id, team_id, player_id, lineup_status, formation) VALUES (:fixture_id, :team_id, :player_id, "Substitute", :formation)');
            foreach ($substitutes as $player_id) {
                $this->db->bind(':fixture_id', $fixture_id);
                $this->db->bind(':team_id', $team_id);
                $this->db->bind(':player_id', $player_id);
                $this->db->bind(':formation', $formation);
                $this->db->execute();
            }

            return $this->db->commit();
        } catch (Exception $e) {
            $this->db->rollBack();
            return false;
        }
    }

    /**
     * Checks if a lineup has already been submitted for a given fixture and team.
     * @param int $fixture_id The ID of the fixture.
     * @param int $team_id The ID of the team.
     * @return bool True if a lineup exists, false otherwise.
     */
    public function hasLineupBeenSubmitted($fixture_id, $team_id) {
        $this->db->query('SELECT COUNT(*) as count FROM fixture_lineups WHERE fixture_id = :fixture_id AND team_id = :team_id');
        $this->db->bind(':fixture_id', $fixture_id);
        $this->db->bind(':team_id', $team_id);
        $row = $this->db->single();
        return $row && $row->count > 0;
    }

    /**
     * Gets the saved lineup for a specific fixture and team.
     * @param int $fixture_id The ID of the fixture.
     * @param int $team_id The ID of the team.
     * @return object|null An object with 'starters' and 'substitutes' arrays.
     */
    public function getLineupForFixture($fixture_id, $team_id) {
        $this->db->query('SELECT player_id, lineup_status, formation, played_position FROM fixture_lineups WHERE fixture_id = :fixture_id AND team_id = :team_id');
        $this->db->bind(':fixture_id', $fixture_id);
        $this->db->bind(':team_id', $team_id);
        $results = $this->db->resultSet();

        $lineup = ['starters' => [], 'substitutes' => [], 'formation' => null];
        foreach ($results as $row) {
            if (!$lineup['formation']) $lineup['formation'] = $row->formation;

            if ($row->lineup_status === 'Starting') {
                // Store as player_id => played_position
                $lineup['starters'][$row->player_id] = $row->played_position;
            } else {
                $lineup['substitutes'][] = $row->player_id;
            }
        }
        return (object) $lineup;
    }
}