<?php
header('Content-Type: application/json');

/* ---------------- FETCH JSON ---------------- */

function fetchJSON($url){
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_FOLLOWLOCATION => true
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response ? json_decode($response,true) : [];
}

/* ---------------- NCAA RANKINGS ---------------- */

function getNCAARankings(){
    $data = fetchJSON("https://site.api.espn.com/apis/site/v2/sports/basketball/mens-college-basketball/rankings");
    $ranks = [];
    if(isset($data['rankings'][0]['ranks'])){
        foreach($data['rankings'][0]['ranks'] as $team){
            $ranks[$team['team']['abbreviation']] = $team['current'];
        }
    }
    return $ranks;
}

/* ---------------- BUILD GAMES ---------------- */

function buildGames($league,$url,$rankings=[]){

    $data = fetchJSON($url);
    $games = [];

    if(empty($data['events'])) return [];

    foreach($data['events'] as $event){

        $comp = $event['competitions'][0];
        $teams = $comp['competitors'];

        $away = $teams[0];
        $home = $teams[1];

        $awayAbbr = $away['team']['abbreviation'];
        $homeAbbr = $home['team']['abbreviation'];

        /* -------- Linescores (kept for future use) -------- */

        $awayLines = [];
        $homeLines = [];

        if(isset($away['linescores'])){
            foreach($away['linescores'] as $l){
                $awayLines[] = $l['value'];
            }
        }

        if(isset($home['linescores'])){
            foreach($home['linescores'] as $l){
                $homeLines[] = $l['value'];
            }
        }

        /* -------- Odds -------- */

        $awaySpread = "";
        $homeSpread = "";
        $overUnder = "";
        $moneyLine = "";

        if(isset($comp['odds'][0])){

            $odds = $comp['odds'][0];

            // Parse spread from details string (example: "ILL -9.5")
            if(isset($odds['details'])){
                if(preg_match('/([A-Z]+)\s*([\-+]?\d+\.?\d*)/', $odds['details'], $m)){
                    $fav = $m[1];
                    $num = floatval($m[2]);

                    if($fav === $awayAbbr){
                        $awaySpread = $num;
                        $homeSpread = "+" . abs($num);
                    } else {
                        $homeSpread = $num;
                        $awaySpread = "+" . abs($num);
                    }
                }
            }

            if(isset($odds['overUnder'])){
                $overUnder = "O/U " . $odds['overUnder'];
            }

            if(isset($odds['awayTeamOdds']['moneyLine'])){
                $moneyLine =
                    $awayAbbr . " " . $odds['awayTeamOdds']['moneyLine']
                    . " | " .
                    $homeAbbr . " " . $odds['homeTeamOdds']['moneyLine'];
            }
        }

        /* -------- Build Game -------- */

        $games[] = [
            "league"=>$league,
            "away"=>$awayAbbr,
            "home"=>$homeAbbr,
            "awayLogo"=>$away['team']['logo'],
            "homeLogo"=>$home['team']['logo'],
            "awayScore"=>$away['score'],
            "homeScore"=>$home['score'],
            "awayLines"=>$awayLines,
            "homeLines"=>$homeLines,
            "awayRank"=>$rankings[$awayAbbr] ?? null,
            "homeRank"=>$rankings[$homeAbbr] ?? null,
            "status"=>$comp['status']['type']['description'] ?? "",
            "period"=>$comp['status']['period'] ?? "",
            "clock"=>$comp['status']['displayClock'] ?? "",
            "dateISO"=>$event['date'],
            "awaySpread"=>$awaySpread,
            "homeSpread"=>$homeSpread,
            "overUnder"=>$overUnder,
            "moneyLine"=>$moneyLine
        ];
    }

    return $games;
}

/* ---------------- BUILD ALL LEAGUES ---------------- */

$ncaaRanks = getNCAARankings();

$games = array_merge(
    buildGames("MLB","https://site.api.espn.com/apis/site/v2/sports/baseball/mlb/scoreboard"),
    buildGames("NBA","https://site.api.espn.com/apis/site/v2/sports/basketball/nba/scoreboard"),
    buildGames("NHL","https://site.api.espn.com/apis/site/v2/sports/hockey/nhl/scoreboard"),
    buildGames("NCAAM","https://site.api.espn.com/apis/site/v2/sports/basketball/mens-college-basketball/scoreboard",$ncaaRanks)
);

echo json_encode(["games"=>$games]);
