<?php
/**
 * Events API — TicketMaster Discovery API for Cincinnati area events
 */
require_once __DIR__ . '/../config/auth.php';
requireLogin();

$cacheFile = __DIR__ . '/../uploads/events_cache.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 3600) {
    header('Content-Type: application/json');
    readfile($cacheFile);
    exit;
}

$apiKey = 'hBs3viDcJsoaf6TmwLJHRvGxC8jg37N4';
$today = date('Y-m-d\TH:i:s\Z');
$url = "https://app.ticketmaster.com/discovery/v2/events.json?apikey={$apiKey}&city=Cincinnati&stateCode=OH&startDateTime={$today}&size=15&sort=date,asc";

$ctx = stream_context_create(['http' => ['timeout' => 10, 'ignore_errors' => true]]);
$response = @file_get_contents($url, false, $ctx);

if ($response === false) {
    if (file_exists($cacheFile)) { header('Content-Type: application/json'); readfile($cacheFile); exit; }
    jsonResponse(['error' => 'Unable to fetch events'], 502);
}

$data = json_decode($response, true);
$events = [];

foreach (($data['_embedded']['events'] ?? []) as $evt) {
    $venue = $evt['_embedded']['venues'][0] ?? [];
    $img = '';
    foreach (($evt['images'] ?? []) as $i) {
        if (($i['width'] ?? 0) >= 200 && ($i['width'] ?? 0) <= 600) { $img = $i['url']; break; }
    }
    if (!$img && !empty($evt['images'])) $img = $evt['images'][0]['url'] ?? '';

    $events[] = [
        'name'  => $evt['name'] ?? '',
        'date'  => $evt['dates']['start']['localDate'] ?? '',
        'time'  => $evt['dates']['start']['localTime'] ?? '',
        'venue' => $venue['name'] ?? '',
        'image' => $img,
        'url'   => $evt['url'] ?? '',
        'type'  => $evt['classifications'][0]['segment']['name'] ?? '',
    ];
}

$result = ['events' => $events, 'cached_at' => date('c')];
@file_put_contents($cacheFile, json_encode($result));
jsonResponse($result);
