<?php
 date_default_timezone_set('Europe/Rome');
 
 $sourceUrl = 'http://103.240.150.111:2222/eventi-1';
 
 function fetchHtml(string $url): string
 {
     $ch = curl_init($url);
     curl_setopt_array($ch, [
         CURLOPT_RETURNTRANSFER => true,
         CURLOPT_FOLLOWLOCATION => true,
         CURLOPT_CONNECTTIMEOUT => 10,
         CURLOPT_TIMEOUT => 20,
         CURLOPT_USERAGENT => 'Mozilla/5.0',
         CURLOPT_ENCODING => '',
     ]);
 
     $html = curl_exec($ch);
     $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
     $error = curl_error($ch);
     curl_close($ch);
 
     if ($html === false || $httpCode >= 400 || trim($html) === '') {
         throw new RuntimeException("Errore lettura sorgente. HTTP $httpCode - $error");
     }
 
     return $html;
 }
 
 function parseTodayEvents(string $html): array
 {
     libxml_use_internal_errors(true);
 
     $dom = new DOMDocument();
     $dom->loadHTML('<?xml encoding="utf-8" ?>' . $html);
     $xpath = new DOMXPath($dom);
 
     $rows = $xpath->query('//table//tr');
     $events = [];
     $today = date('Y-m-d');
 
     foreach ($rows as $row) {
         $cells = $xpath->query('./th|./td', $row);
         if ($cells->length < 4) continue;
 
         $title = trim(preg_replace('/\s+/', ' ', $cells->item(0)->textContent ?? ''));
         $start = trim(preg_replace('/\s+/', ' ', $cells->item(1)->textContent ?? ''));
         $idRaw = trim(preg_replace('/\s+/', ' ', $cells->item(3)->textContent ?? ''));
 
         if ($title === '' || stripos($title, 'Title') !== false || stripos($start, 'Start Date') !== false) {
             continue;
         }
 
         $dt = DateTime::createFromFormat('Y-m-d H:i:s', $start, new DateTimeZone('Europe/Rome'));
         if (!$dt || $dt->format('Y-m-d') !== $today) continue;
 
         preg_match('/event(\d+)/i', $idRaw, $m);
         $channel = $m[1] ?? $idRaw;
 
         $events[] = [
             'title' => $title,
             'time' => $dt->format('H:i'),
             'date_line' => $dt->format('d-m-Y') . ' ore ' . $dt->format('G:i'),
             'channel' => $channel,
             'sort' => $dt->getTimestamp(),
         ];
     }
 
     usort($events, function ($a, $b) {
         return $a['sort'] <=> $b['sort'];
     });
 
     return $events;
 }
 
 $errorMessage = null;
 $events = [];
 
 try {
     $html = fetchHtml($sourceUrl);
     $events = parseTodayEvents($html);
 } catch (Throwable $e) {
     $errorMessage = $e->getMessage();
 }
 
 $todayTitle = date('d-m-Y');
 $rowsCount = max(count($events), 1);
 ?>
 <!DOCTYPE html>
 <html lang="it">
 <head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Calendario Eventi</title>
 <style>
 *{box-sizing:border-box}
 html,body{height:100%}
 body{
     margin:0;
     font-family:Arial, Helvetica, sans-serif;
     background:#0b0f14;
     color:#fff;
     overflow:hidden;
 }
 .wrap{
     height:100vh;
     max-width:1280px;
     margin:0 auto;
     padding:10px;
     display:flex;
     flex-direction:column;
     gap:8px;
 }
 .hero{
     background:linear-gradient(135deg,#111827,#1f2937);
     border:1px solid #243244;
     border-radius:14px;
     padding:10px 14px;
     flex:0 0 auto;
 }
 .hero h1{
     margin:0;
     color:#facc15;
     font-size:24px;
     line-height:1.1;
 }
 .toolbar{
     display:flex;
     justify-content:space-between;
     flex-wrap:wrap;
     gap:8px;
     flex:0 0 auto;
 }
 .badge{
     background:#facc15;
     color:#111;
     padding:8px 12px;
     border-radius:999px;
     font-weight:700;
     font-size:13px;
 }
 .badge-dark{
     background:#17202c;
     border:1px solid #2a3547;
     color:#fff;
     padding:8px 12px;
     border-radius:999px;
     font-weight:700;
     font-size:13px;
 }
 .list{
     flex:1 1 auto;
     display:flex;
     flex-direction:column;
     gap:6px;
     overflow:hidden;
     min-height:0;
 }
 .row{
     height:calc((100vh - 120px) / var(--rows));
     min-height:34px;
     display:grid;
     grid-template-columns:72px 1fr 110px;
     gap:10px;
     align-items:center;
     background:#111827;
     border:1px solid #243244;
     border-radius:12px;
     padding:6px 10px;
 }
 .time{
     font-size:clamp(13px, 1.9vh, 20px);
     font-weight:800;
     color:#facc15;
     text-align:center;
     line-height:1;
 }
 .info{
     display:flex;
     flex-direction:column;
     gap:2px;
     min-width:0;
 }
 .title{
     font-size:clamp(11px, 1.5vh, 15px);
     font-weight:700;
     line-height:1.1;
     white-space:nowrap;
     overflow:hidden;
     text-overflow:ellipsis;
 }
 .date{
     color:#cbd5e1;
     font-size:clamp(9px, 1.2vh, 12px);
     white-space:nowrap;
     overflow:hidden;
     text-overflow:ellipsis;
 }
 .channel{
     background:#facc15;
     color:#111;
     text-align:center;
     padding:6px 4px;
     border-radius:10px;
     font-weight:800;
     font-size:clamp(10px, 1.35vh, 14px);
     line-height:1.1;
 }
 .empty,.error{
     background:#111827;
     border:1px solid #243244;
     border-radius:12px;
     padding:16px;
 }
 .error{
     background:#2a1111;
     border-color:#7f1d1d;
     color:#fecaca;
 }
 @media(max-width:700px){
     .wrap{padding:8px}
     .hero h1{font-size:20px}
     .row{grid-template-columns:56px 1fr 88px; gap:8px; padding:5px 8px}
 }
 </style>
 </head>
 <body style="--rows: <?= $rowsCount ?>;">
 <div class="wrap">
     <div class="hero">
         <h1>Calendario Giornaliero Eventi</h1>
     </div>
 
     <div class="toolbar">
         <div class="badge">Oggi: <?= htmlspecialchars($todayTitle) ?></div>
         <div class="badge-dark">Eventi trovati: <?= count($events) ?></div>
     </div>
 
     <?php if ($errorMessage): ?>
         <div class="error"><strong>Errore:</strong> <?= htmlspecialchars($errorMessage) ?></div>
     <?php elseif (empty($events)): ?>
         <div class="empty">Nessun evento disponibile per oggi.</div>
     <?php else: ?>
         <div class="list">
             <?php foreach($events as $e): ?>
                 <div class="row">
                     <div class="time"><?= htmlspecialchars($e['time']) ?></div>
 
                     <div class="info">
                         <div class="title"><?= htmlspecialchars($e['title']) ?></div>
                         <div class="date"><?= htmlspecialchars($e['date_line']) ?></div>
                     </div>
 
                     <div class="channel">[EVENTI] <?= htmlspecialchars($e['channel']) ?></div>
                 </div>
             <?php endforeach; ?>
         </div>
     <?php endif; ?>
 </div>
 </body>
 </html>
