<?php

class PredictionService
{
    private $db;

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

    /**
     * Generates a match prediction based on team stats.
     * @param int $home_team_id
     * @param int $away_team_id
     * @param int $league_id
     * @return object An object containing the prediction and reasoning.
     */
    public function generatePrediction(int $home_team_id, int $away_team_id, int $league_id): object
    {
        $leagueModel = new League();
        $table = $leagueModel->getTable($league_id);

        $home_stats = null;
        $away_stats = null;

        foreach ($table as $team_row) {
            if ($team_row->team_id == $home_team_id) {
                $home_stats = $team_row;
            }
            if ($team_row->team_id == $away_team_id) {
                $away_stats = $team_row;
            }
        }

        if (!$home_stats || !$away_stats) {
            return (object) ['outcome' => 'Unavailable', 'reasoning' => 'Not enough data to generate a prediction.'];
        }

        $home_power = $this->calculatePowerScore($home_stats);
        $away_power = $this->calculatePowerScore($away_stats);

        // Calculate Confidence based on power score difference
        $power_diff = abs($home_power['total'] - $away_power['total']);
        $confidence = 'Low';
        if ($power_diff > 1.5) {
            $confidence = 'High';
        } elseif ($power_diff > 0.8) {
            $confidence = 'Medium';
        }

        // --- Score Prediction Logic ---
        // Calculate league average goals per game
        $total_goals = 0;
        $total_played = 0;
        foreach ($table as $team_row) {
            $total_goals += $team_row->goals_for;
            $total_played += $team_row->played;
        }
        $league_avg_goals = ($total_played > 0) ? $total_goals / count($table) : 1.2; // Avg goals per team per game

        // Home team's expected goals = (Home Attack Strength) * (Away Defense Weakness) * League Average
        $home_attack_strength = ($home_stats->played > 0) ? ($home_stats->goals_for / $home_stats->played) / $league_avg_goals : 1;
        $away_defense_strength = ($away_stats->played > 0) ? ($away_stats->goals_against / $away_stats->played) / $league_avg_goals : 1;
        $predicted_home_score = round($home_attack_strength * $away_defense_strength * $league_avg_goals);

        // Away team's expected goals
        $away_attack_strength = ($away_stats->played > 0) ? ($away_stats->goals_for / $away_stats->played) / $league_avg_goals : 1;
        $home_defense_strength = ($home_stats->played > 0) ? ($home_stats->goals_against / $home_stats->played) / $league_avg_goals : 1;
        $predicted_away_score = round($away_attack_strength * $home_defense_strength * $league_avg_goals);

        $outcome = "{$predicted_home_score} - {$predicted_away_score}";

        // --- Reasoning Logic ---
        $reasoning = "Prediction based on recent form and season statistics. ";
        if ($home_power['form'] > $away_power['form']) {
            $reasoning .= htmlspecialchars($home_stats->team_name) . " has a stronger recent form. ";
        } elseif ($away_power['form'] > $home_power['form']) {
            $reasoning .= htmlspecialchars($away_stats->team_name) . " appears to be in better form. ";
        }

        if ($home_power['attack'] > $away_power['attack']) {
            $reasoning .= htmlspecialchars($home_stats->team_name) . " has shown a better goal-scoring record. ";
        } elseif ($away_power['attack'] > $home_power['attack']) {
            $reasoning .= htmlspecialchars($away_stats->team_name) . " has been more prolific in front of goal. ";
        }

        return (object) ['outcome' => $outcome, 'reasoning' => $reasoning, 'confidence' => $confidence];
    }

    /**
     * Calculates a power score for a team based on its stats.
     * @param object $stats The team's statistics object from the league table.
     * @return array An array of score components.
     */
    private function calculatePowerScore(object $stats): array
    {
        // 1. Form Score (last 5 games: W=3, D=1, L=0)
        $form_score = 0;
        $last_five = array_slice($stats->form, -5);
        foreach ($last_five as $result) {
            if ($result === 'W') $form_score += 3;
            if ($result === 'D') $form_score += 1;
        }

        // 2. Attack Score (goals per game)
        $attack_score = ($stats->played > 0) ? ($stats->goals_for / $stats->played) * 3 : 0;

        // 3. Defense Score (goals conceded per game, inverted)
        $defense_score = ($stats->played > 0) ? (2 - ($stats->goals_against / $stats->played)) * 2 : 0;

        // 4. Discipline Score (negative points for cards)
        // We don't have card data in the table, so we'll use a placeholder.
        // In a real scenario, you'd fetch this from a stats model.
        $discipline_score = 0; // Placeholder

        $total_score = ($form_score * 0.4) + ($attack_score * 0.3) + ($defense_score * 0.2) + ($discipline_score * 0.1);

        return [
            'form' => $form_score,
            'attack' => $attack_score,
            'defense' => $defense_score,
            'total' => $total_score
        ];
    }
}