<?php

class Training {
    private $db;

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

    /**
     * Get all training sessions for a specific team, ordered by most recent.
     * @param int $team_id The ID of the team.
     * @return array An array of session objects.
     */
    public function getSessionsByTeamId($team_id) {
        $this->db->query('
            SELECT 
                ts.id, 
                ts.session_date,
                (SELECT COUNT(*) FROM training_attendance WHERE session_id = ts.id AND status = "Present") as present_count,
                (SELECT COUNT(*) FROM training_attendance WHERE session_id = ts.id) as total_count
            FROM training_sessions ts
            WHERE ts.team_id = :team_id
            ORDER BY ts.session_date DESC
        ');
        $this->db->bind(':team_id', $team_id);
        return $this->db->resultSet();
    }

    /**
     * Records attendance for a new training session.
     * Uses a transaction to ensure all or nothing is saved.
     * @param int $team_id The ID of the team.
     * @param string $session_date The date of the session.
     * @param array $attendance_data An associative array of [player_id => status].
     * @return bool True on success, false on failure.
     */
    public function recordAttendance($team_id, $session_date, $attendance_data) {
        $this->db->beginTransaction();

        try {
            // 1. Create the training session record
            $this->db->query('INSERT INTO training_sessions (team_id, session_date) VALUES (:team_id, :session_date)');
            $this->db->bind(':team_id', $team_id);
            $this->db->bind(':session_date', $session_date);
            $this->db->execute();
            $session_id = $this->db->lastInsertId();

            // 2. Insert each player's attendance status
            $this->db->query('INSERT INTO training_attendance (session_id, player_id, status) VALUES (:session_id, :player_id, :status)');
            foreach ($attendance_data as $player_id => $status) {
                // Ensure status is one of the allowed enum values
                if (!in_array($status, ['Present', 'Absent', 'Excused'])) {
                    $status = 'Absent'; // Default to absent if invalid data is passed
                }
                $this->db->bind(':session_id', $session_id);
                $this->db->bind(':player_id', $player_id);
                $this->db->bind(':status', $status);
                $this->db->execute();
            }

            // If we get here, everything was successful
            return $this->db->commit();

        } catch (Exception $e) {
            // Something went wrong, roll back the changes
            $this->db->rollBack();
            // Optionally log the error: error_log($e->getMessage());
            return false;
        }
    }

    /**
     * Get the details for a single training session, including all player attendance.
     * @param int $session_id The ID of the training session.
     * @return object|null An object containing session details and an array of attendees.
     */
    public function getSessionDetailsById($session_id) {
        // First, get the session info
        $this->db->query('SELECT * FROM training_sessions WHERE id = :session_id');
        $this->db->bind(':session_id', $session_id);
        $session = $this->db->single();

        if (!$session) {
            return null;
        }

        // Then, get the attendance details for that session
        $this->db->query('
            SELECT
                ta.status,
                u.id as player_id,
                u.first_name,
                u.last_name,
                p.squad_number
            FROM training_attendance ta
            JOIN users u ON ta.player_id = u.id
            JOIN players p ON u.id = p.user_id
            WHERE ta.session_id = :session_id
            ORDER BY u.last_name ASC, u.first_name ASC
        ');
        $this->db->bind(':session_id', $session_id);
        $session->attendees = $this->db->resultSet();

        return $session;
    }

    /**
     * Security check to verify a session belongs to a manager's team.
     * @param int $session_id The ID of the session.
     * @param int $team_id The ID of the manager's team.
     * @return bool True if the session belongs to the team, false otherwise.
     */
    public function checkSessionBelongsToManager($session_id, $team_id) {
        $this->db->query('SELECT COUNT(*) as count FROM training_sessions WHERE id = :session_id AND team_id = :team_id');
        $this->db->bind(':session_id', $session_id);
        $this->db->bind(':team_id', $team_id);
        return $this->db->single()->count > 0;
    }

    /**
     * Updates the attendance records for an existing training session.
     * @param int $session_id The ID of the session to update.
     * @param string $session_date The new date for the session.
     * @param array $attendance_data An associative array of [player_id => status].
     * @return bool True on success, false on failure.
     */
    public function updateAttendance($session_id, $session_date, $attendance_data) {
        $this->db->beginTransaction();

        try {
            // 1. Update the session date
            $this->db->query('UPDATE training_sessions SET session_date = :session_date WHERE id = :session_id');
            $this->db->bind(':session_date', $session_date);
            $this->db->bind(':session_id', $session_id);
            $this->db->execute();

            // 2. Delete old attendance records for this session
            $this->db->query('DELETE FROM training_attendance WHERE session_id = :session_id');
            $this->db->bind(':session_id', $session_id);
            $this->db->execute();

            // 3. Insert the new attendance records
            $this->db->query('INSERT INTO training_attendance (session_id, player_id, status) VALUES (:session_id, :player_id, :status)');
            foreach ($attendance_data as $player_id => $status) {
                $this->db->bind(':session_id', $session_id);
                $this->db->bind(':player_id', $player_id);
                $this->db->bind(':status', $status);
                $this->db->execute();
            }

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