<?php

class Stats {
    private $db;

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

    /**
     * Get player statistics for a given league.
     * This is a placeholder for complex SQL queries.
     * @param int $league_id The ID of the league.
     * @param string $stat_type The type of stat (e.g., 'goals', 'assists').
     * @return array An array of player stats.
     */
    public function getPlayerStats($league_id, $stat_type) {
        // TODO: Implement complex SQL queries to calculate player stats from game_events table.
        // Example: SELECT player_id, COUNT(*) as total FROM game_events WHERE event_type = :stat_type GROUP BY player_id ORDER BY total DESC
        return []; // Return empty array for now
    }

    /**
     * Get team statistics for a given league.
     * This is a placeholder for complex SQL queries.
     * @param int $league_id The ID of the league.
     * @param string $stat_type The type of stat (e.g., 'corners', 'fouls').
     * @return array An array of team stats.
     */
    public function getTeamStats($league_id, $stat_type) {
        // For now, we'll handle goals scored/conceded as they can be derived from fixtures.
        // Other stats like corners/fouls would require a game_events table.
        if ($stat_type === 'goals_scored' || $stat_type === 'goals_conceded') {
            $this->db->query("
                SELECT 
                    t.id as team_id,
                    c.name as team_name,
                    c.logo as team_logo,
                    (SELECT SUM(home_team_score) FROM fixtures WHERE home_team_id = t.id AND status = 'finished') as home_goals_for,
                    (SELECT SUM(away_team_score) FROM fixtures WHERE away_team_id = t.id AND status = 'finished') as away_goals_for,
                    (SELECT SUM(away_team_score) FROM fixtures WHERE home_team_id = t.id AND status = 'finished') as home_goals_against,
                    (SELECT SUM(home_team_score) FROM fixtures WHERE away_team_id = t.id AND status = 'finished') as away_goals_against
                FROM teams t
                JOIN clubs c ON t.club_id = c.id
                WHERE c.league_id = :league_id
            ");
            $this->db->bind(':league_id', $league_id);
            $results = $this->db->resultSet();

            foreach ($results as $row) {
                $row->total_goals_scored = ($row->home_goals_for ?? 0) + ($row->away_goals_for ?? 0);
                $row->total_goals_conceded = ($row->home_goals_against ?? 0) + ($row->away_goals_against ?? 0);
            }

            // Sort based on the requested stat
            if ($stat_type === 'goals_scored') {
                usort($results, fn($a, $b) => $b->total_goals_scored <=> $a->total_goals_scored);
            } else {
                usort($results, fn($a, $b) => $b->total_goals_conceded <=> $a->total_goals_conceded);
            }
            return $results;
        }
        return []; // Return empty for other stats for now
    }

    /**
     * Get aggregated statistics for a single fixture.
     * @param int $fixture_id The ID of the fixture.
     * @return object|null An object with home and away stats.
     */
    public function getStatsForFixture($fixture_id) {
        // First, get the fixture details to know home/away team IDs
        $fixtureModel = new Fixture();
        $fixture = $fixtureModel->findById($fixture_id);
        if (!$fixture) {
            return null;
        }

        // Then, get the event-based stats
        $eventModel = new MatchEvent();
        $event_stats = $eventModel->getStatsForFixture($fixture_id);

        $stats = [
            'home' => ['shots' => 0, 'shots_on_target' => 0, 'corners' => 0, 'fouls' => 0, 'yellow_cards' => 0, 'red_cards' => 0, 'offsides' => 0, 'possession' => 50],
            'away' => ['shots' => 0, 'shots_on_target' => 0, 'corners' => 0, 'fouls' => 0, 'yellow_cards' => 0, 'red_cards' => 0, 'offsides' => 0, 'possession' => 50]
        ];

        foreach ($event_stats as $stat_row) {
            $team_type = ($stat_row->team_id == $fixture->home_team_id) ? 'home' : 'away';

            $stats[$team_type]['shots'] = (int)($stat_row->shots_on_target ?? 0) + (int)($stat_row->shots_off_target ?? 0);
            $stats[$team_type]['shots_on_target'] = (int)($stat_row->shots_on_target ?? 0);
            $stats[$team_type]['corners'] = (int)($stat_row->corners ?? 0);
            $stats[$team_type]['fouls'] = (int)($stat_row->fouls ?? 0);
            $stats[$team_type]['yellow_cards'] = (int)($stat_row->yellow_cards ?? 0);
            $stats[$team_type]['red_cards'] = (int)($stat_row->red_cards ?? 0);
            $stats[$team_type]['offsides'] = (int)($stat_row->offsides ?? 0);
        }

        // --- AI Powered Possession Calculation ---
        // Calculate possession based on activity pressure
        // Activity Weights: Shots(2), Corners(1.5), Offsides(1), Fouls(-0.5), Yellows(-1), Reds(-5)
        $calc_score = function($s) {
            return 100 + ($s['shots'] * 2) + ($s['corners'] * 1.5) + ($s['offsides'] * 1) 
                   - ($s['fouls'] * 0.5) - ($s['yellow_cards'] * 1) - ($s['red_cards'] * 5);
        };

        $h_score = $calc_score($stats['home']);
        $a_score = $calc_score($stats['away']);
        $total_activity = $h_score + $a_score;

        if ($total_activity > 0) {
            $stats['home']['possession'] = round(($h_score / $total_activity) * 100);
            $stats['away']['possession'] = 100 - $stats['home']['possession'];
        }

        // Convert to object for consistency with other models
        $stats['home'] = (object)$stats['home'];
        $stats['away'] = (object)$stats['away'];

        return (object)$stats;
    }

    public function getPlayerOffsides($player_id) {
        $this->db->query("SELECT COUNT(*) as count FROM match_events WHERE player_id = :pid AND event_type = 'offside'");
        $this->db->bind(':pid', $player_id);
        return $this->db->single()->count ?? 0;
    }
}