
<?php
class Klasemen {
    private $clubs;
    private $points;

    // Constructor to initialize clubs
    public function __construct($clubList) {
        $this->clubs = $clubList;
        $this->points = array_fill(0, count($clubList), 0);
    }

    // Method to record match results
    public function catatPertandingan($homeClub, $awayClub, $score) {
        // Find indices of the clubs
        $homeIndex = array_search($homeClub, $this->clubs);
        $awayIndex = array_search($awayClub, $this->clubs);

        // Validate clubs exist
        if ($homeIndex === false || $awayIndex === false) {
            throw new Exception("Club not found in the league");
        }

        // Parse scores
        list($homeScore, $awayScore) = explode(':', $score);

        // Determine points allocation
        if ($homeScore > $awayScore) {
            // Home team wins
            $this->points[$homeIndex] += 3;
        } elseif ($homeScore < $awayScore) {
            // Away team wins
            $this->points[$awayIndex] += 3;
        } else {
            // Draw
            $this->points[$homeIndex] += 1;
            $this->points[$awayIndex] += 1;
        }
    }

    // Method to print current league standings
    public function cetakKlasemen() {
        // Create an array of club-point pairs for sorting
        $standings = array_map(null, $this->clubs, $this->points);
        
        // Sort standings by points in descending order
        usort($standings, function($a, $b) {
            return $b[1] - $a[1];
        });

        // Print or return standings
        $result = [];
        foreach ($standings as $standing) {
            $result[$standing[0]] = $standing[1];
        }
        return $result;
    }

    // Method to get club ranking by position
    public function ambilPeringkat($position) {
        $standings = $this->cetakKlasemen();
        $ranks = array_keys($standings);
        
        // Check if position is valid
        if ($position < 1 || $position > count($ranks)) {
            throw new Exception("Invalid ranking position");
        }
        
        return $ranks[$position - 1];
    }
}

// Example usage
$klasemen = new Klasemen(['Liverpool', 'Chelsea', 'Arsenal']);
$klasemen->catatPertandingan('Arsenal', 'Liverpool', '2:1');
$klasemen->catatPertandingan('Arsenal', 'Chelsea', '1:1');
$klasemen->catatPertandingan('Chelsea', 'Arsenal', '0:3');
$klasemen->catatPertandingan('Chelsea', 'Liverpool', '3:2');
$klasemen->catatPertandingan('Liverpool', 'Arsenal', '2:2');
$klasemen->catatPertandingan('Liverpool', 'Chelsea', '0:0');

// Print standings
print_r($klasemen->cetakKlasemen());

// Get club at specific ranking
echo $klasemen->ambilPeringkat(2);
?>
