<?php
/**
 * Saints API — ESPN data proxy for New Orleans Saints
 * Team ID: 18
 */
require_once __DIR__ . '/../config/auth.php';
requireLogin();

$action = $_GET['action'] ?? 'all';
$cacheDir = __DIR__ . '/../uploads';

function espnFetch($url, $timeout = 10) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING => '',
        CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; CFD Portal/1.0)',
    ]);
    $res = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($code >= 200 && $code < 400) ? json_decode($res, true) : null;
}

function getCached($file, $ttl) {
    if (file_exists($file) && (time() - filemtime($file)) < $ttl) {
        return json_decode(file_get_contents($file), true);
    }
    return null;
}

function fetchAll() {
    global $cacheDir;
    $cacheFile = "$cacheDir/saints_cache.json";
    $cached = getCached($cacheFile, 1800); // 30 min
    if ($cached) { jsonResponse($cached); }

    $base = 'https://site.api.espn.com/apis/site/v2/sports/football/nfl';
    $teamId = 18;

    // Parallel-ish fetches
    $teamData = espnFetch("$base/teams/$teamId");
    $newsData = espnFetch("$base/news?team=$teamId&limit=10");
    $schedData = espnFetch("$base/teams/$teamId/schedule");
    $rosterData = espnFetch("$base/teams/$teamId/roster");

    // Team info
    $team = $teamData['team'] ?? [];
    $info = [
        'name' => $team['displayName'] ?? 'New Orleans Saints',
        'record' => $team['record']['items'][0]['summary'] ?? ($schedData['team']['recordSummary'] ?? ''),
        'standing' => $schedData['team']['standingSummary'] ?? '',
        'color' => '#' . ($team['color'] ?? 'd3bc8d'),
        'altColor' => '#' . ($team['alternateColor'] ?? '000000'),
        'logo' => $team['logos'][0]['href'] ?? '',
    ];

    // News with images
    $news = [];
    foreach (($newsData['articles'] ?? []) as $article) {
        $imgs = $article['images'] ?? [];
        $img = '';
        foreach ($imgs as $i) {
            if (!empty($i['url'])) { $img = $i['url']; break; }
        }
        $links = $article['links'] ?? [];
        $link = '';
        if (is_array($links) && isset($links['web']['href'])) {
            $link = $links['web']['href'];
        }
        $news[] = [
            'headline' => $article['headline'] ?? '',
            'description' => $article['description'] ?? '',
            'image' => $img,
            'date' => $article['published'] ?? '',
            'url' => $link,
            'type' => $article['type'] ?? '',
        ];
    }

    // Schedule / results
    $games = [];
    foreach (($schedData['events'] ?? []) as $ev) {
        $comp = $ev['competitions'][0] ?? [];
        $competitors = $comp['competitors'] ?? [];
        $home = null; $away = null;
        foreach ($competitors as $c) {
            if (($c['homeAway'] ?? '') === 'home') $home = $c;
            else $away = $c;
        }
        $saintsHome = ($home['team']['id'] ?? '') == '18';
        $saints = $saintsHome ? $home : $away;
        $opponent = $saintsHome ? $away : $home;
        $status = $comp['status']['type']['description'] ?? '';
        $saintsScore = $saints['score']['displayValue'] ?? null;
        $oppScore = $opponent['score']['displayValue'] ?? null;
        $won = ($saintsScore !== null && $oppScore !== null) ? ((int)$saintsScore > (int)$oppScore) : null;

        $games[] = [
            'date' => substr($ev['date'] ?? '', 0, 10),
            'name' => $ev['shortName'] ?? '',
            'opponent' => $opponent['team']['displayName'] ?? '',
            'opponentAbbr' => $opponent['team']['abbreviation'] ?? '',
            'opponentLogo' => $opponent['team']['logos'][0]['href'] ?? ($opponent['team']['logo'] ?? ''),
            'home' => $saintsHome,
            'saintsScore' => $saintsScore,
            'opponentScore' => $oppScore,
            'won' => $won,
            'status' => $status,
            'week' => $ev['week']['text'] ?? '',
        ];
    }

    // Roster - key players (top from each group)
    $roster = [];
    foreach (($rosterData['athletes'] ?? []) as $group) {
        $posGroup = $group['position'] ?? '';
        foreach (($group['items'] ?? []) as $player) {
            $roster[] = [
                'name' => $player['fullName'] ?? '',
                'jersey' => $player['jersey'] ?? '',
                'position' => $player['position']['abbreviation'] ?? '',
                'posGroup' => $posGroup,
                'headshot' => $player['headshot']['href'] ?? '',
                'age' => $player['age'] ?? '',
                'experience' => $player['experience']['years'] ?? 0,
            ];
        }
    }

    // Team stats
    $statsRaw = espnFetch("$base/teams/$teamId/statistics");
    $stats = [];
    foreach (($statsRaw['results']['stats']['categories'] ?? []) as $cat) {
        $catStats = [];
        foreach (($cat['stats'] ?? []) as $s) {
            $catStats[] = [
                'name' => $s['displayName'] ?? '',
                'value' => $s['displayValue'] ?? '',
            ];
        }
        $stats[$cat['displayName'] ?? ''] = array_slice($catStats, 0, 5);
    }

    $result = [
        'team' => $info,
        'news' => $news,
        'games' => $games,
        'roster' => $roster,
        'stats' => $stats,
        'cached_at' => date('c'),
    ];

    @file_put_contents($cacheFile, json_encode($result));
    jsonResponse($result);
}

fetchAll();
