<?php
header('Content-Type: application/json; charset=utf-8');
class Standings
{
    private $conn;

    public function __construct($conn)
    {
        $this->conn = $conn;
    }

    public function calculate($tournamentCode)
    {
        $standings = $this->initializeStandings($tournamentCode);
        $games = $this->getGames($tournamentCode);
        foreach ($games as $game) {
            $this->processGame($standings, $game);
        }

        $this->saveStandings($tournamentCode, $standings);

        return ['status' => 'success', 'standings' => $standings];
    }

    private function initializeStandings($tournamentCode)
    {
        $sql = "SELECT code, `group` FROM team WHERE tournament = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $tournamentCode);
        $stmt->execute();
        $result = $stmt->get_result();

        $standings = [];
        while ($team = $result->fetch_assoc()) {
            $standings[$team['code']] = [
                'group' => $team['group'],
                'matches_played' => 0,
                'wins' => 0,
                'losses' => 0,
                'draws' => 0,
                'points' => 0,
                'sets_won' => 0,
                'sets_lost' => 0
            ];
        }
        return $standings;
    }

    private function getGames($tournamentCode)
    {
        $sql = "SELECT t1, t2, s1t1, s2t1, s3t1, s1t2, s2t2, s3t2 
            FROM game 
            WHERE tournament = ? 
            AND NOW() >= date 
            AND `groups` REGEXP '^[0-9]+$';";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('s', $tournamentCode);
        $stmt->execute();
        return $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    }

    private function processGame(&$standings, $game)
    {
        $team1 = $game['t1'];
        $team2 = $game['t2'];
        if (empty($team1) || empty($team2)) return;

        $setsTeam1 = [$game['s1t1'], $game['s2t1'], $game['s3t1']];
        $setsTeam2 = [$game['s1t2'], $game['s2t2'], $game['s3t2']];
        $winsTeam1 = $winsTeam2 = 0;

        for ($i = 0; $i < 3; $i++) {
            if (!empty($setsTeam1[$i]) || !empty($setsTeam2[$i])) {
                if ($setsTeam1[$i] > $setsTeam2[$i]) {
                    $winsTeam1++;
                } elseif ($setsTeam2[$i] > $setsTeam1[$i]) {
                    $winsTeam2++;
                } elseif ($setsTeam1[$i] > 0 && $setsTeam2[$i] == 0) {
                    $winsTeam1++;
                } elseif ($setsTeam2[$i] > 0 && $setsTeam1[$i] == 0) {
                    $winsTeam2++;
                }
            }
        }

        if ($winsTeam1 > $winsTeam2) {
            $this->updateStandings($standings, $team1, 'win', $winsTeam1, $winsTeam2);
            $this->updateStandings($standings, $team2, 'lose', $winsTeam2, $winsTeam1);
        } elseif ($winsTeam2 > $winsTeam1) {
            $this->updateStandings($standings, $team2, 'win', $winsTeam2, $winsTeam1);
            $this->updateStandings($standings, $team1, 'lose', $winsTeam1, $winsTeam2);
        } else {
            $this->updateStandings($standings, $team1, 'draw', $winsTeam1, $winsTeam2);
            $this->updateStandings($standings, $team2, 'draw', $winsTeam2, $winsTeam1);
        }
    }

    private function updateStandings(&$standings, $team, $result, $setsWon, $setsLost)
    {
        $standings[$team]['matches_played']++;
        $standings[$team]['sets_won'] += $setsWon;
        $standings[$team]['sets_lost'] += $setsLost;

        if ($result == 'win') {
            $standings[$team]['wins']++;
            $standings[$team]['points'] += 3;
        } elseif ($result == 'lose') {
            $standings[$team]['losses']++;
        } elseif ($result == 'draw') {
            $standings[$team]['draws']++;
            $standings[$team]['points']++;
        }
    }

    private function saveStandings($tournamentCode, $standings)
    {
        foreach ($standings as $teamCode => $data) {
            $goalDifference = $data['sets_won'] - $data['sets_lost'];
            $sql = "INSERT INTO standings (tournament, team, `group`, matches_played, wins, losses, draws, points, sets_won, sets_lost, goal_difference) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE 
        `group` = VALUES(`group`), 
        matches_played = VALUES(matches_played), 
        wins = VALUES(wins), 
        losses = VALUES(losses), 
        draws = VALUES(draws), 
        points = VALUES(points), 
        sets_won = VALUES(sets_won), 
        sets_lost = VALUES(sets_lost), 
        goal_difference = VALUES(goal_difference)";
            $stmt = $this->conn->prepare($sql);
            $stmt->bind_param(
                'ssiiiiiiiii',
                $tournamentCode,
                $teamCode,
                $data['group'],
                $data['matches_played'],
                $data['wins'],
                $data['losses'],
                $data['draws'],
                $data['points'],
                $data['sets_won'],
                $data['sets_lost'],
                $goalDifference
            );
            $stmt->execute();
        }
    }
}
