/*
Theme Name: Fenix Child theme
Theme URI:
Template: fenix
Author: THBThemes by Evolve
Author URI: http://www.thbthemes.com
Description: A Multipurpose WordPress Theme
Version: 1.0.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: one-column, custom-menu, featured-images, post-formats, translation-ready
*/

<?php
// Shortcode: [next_departure calendar_url="..."]
function evr_next_departure_shortcode($atts) {
    $a = shortcode_atts([
        'calendar_url' => '',
    ], $atts, 'next_departure');

    if (empty($a['calendar_url'])) {
        return '<div class="next-train"><b>No calendar URL provided.</b></div>';
    }

    // Fetch calendar
    $resp = wp_remote_get($a['calendar_url']);
    if (is_wp_error($resp)) {
        return '<div class="next-train"><b>Calendar fetch error.</b></div>';
    }

    $ics = wp_remote_retrieve_body($resp);
    if (!$ics) return '<div class="next-train"><b>No data in feed.</b></div>';

    // Parse events (very minimal)
    $tz = new DateTimeZone('Europe/London');
    preg_match_all('/DTSTART.*:(\d+)/', $ics, $dtMatches);
    preg_match_all('/SUMMARY:(.*)/', $ics, $sumMatches);

    $events = [];
    foreach ($dtMatches[1] as $i => $raw) {
        $dt = DateTime::createFromFormat('Ymd\THis', $raw, $tz);
        if ($dt && isset($sumMatches[1][$i])) {
            $events[] = ['start' => $dt, 'summary' => trim($sumMatches[1][$i])];
        }
    }
    usort($events, fn($x,$y) => $x['start'] <=> $y['start']);

    $now = new DateTime('now', $tz);
    foreach ($events as $e) {
        if ($e['start'] >= $now) {
            $station = preg_replace('/ dep\.?$/i', '', $e['summary']);
            return '<div class="next-train"><b>the next train leaving '.$station.' is the '.$e['start']->format('H:i').'</b></div>';
        }
    }

    return '<div class="next-train"><b>No more departures today.</b></div>';
}
add_shortcode('next_departure', 'evr_next_departure_shortcode');






/* ================= EVR Next-Train Banner (Shortcode + REST) ================ */

add_action('rest_api_init', function () {
  register_rest_route('evr/v1', '/next', [
    'methods'  => 'GET',
    'callback' => 'evr_next_train_api',
    'permission_callback' => '__return_true',
  ]);
});

function evr_get_ics_url() {
  return 'YOUR_ICS_URL_HERE'; // public iCal URL
}

function evr_fetch_ics($max_age = 120) {
  $cache_key = 'evr_ics_cache';
  if ($c = get_transient($cache_key)) return $c;
  $res = wp_remote_get(evr_get_ics_url(), ['timeout' => 12]);
  if (is_wp_error($res)) return '';
  $body = wp_remote_retrieve_body($res);
  if (!$body) return '';
  set_transient($cache_key, $body, $max_age);
  return $body;
}

// Minimal ICS parser: DTSTART / DTEND / SUMMARY (with folded lines tolerance)
function evr_parse_ics_events($ics) {
  $ics = preg_replace("/\r\n[ \t]/", '', $ics); // unfold lines
  $lines = preg_split("/\r\n|\n|\r/", $ics);
  $events = []; $cur = null;

  foreach ($lines as $line_raw) {
    $line = trim($line_raw);
    if ($line === 'BEGIN:VEVENT') { $cur = []; continue; }
    if ($line === 'END:VEVENT')   { if ($cur) $events[] = $cur; $cur = null; continue; }
    if (!$cur) continue;

    if (preg_match('/^(DTSTART|DTEND)(;[^:]*)?:(.+)$/', $line, $m)) $cur[$m[1]] = $m[3];
    if (preg_match('/^SUMMARY:(.+)$/', $line, $m)) $cur['SUMMARY'] = $m[1];
  }

  $tz = new DateTimeZone('Europe/London');
  foreach ($events as &$e) {
    foreach (['DTSTART','DTEND'] as $k) {
      if (empty($e[$k])) continue;
      $v = $e[$k];

      if (preg_match('/^(\d{8}T\d{6})Z$/', $v)) { // UTC Z
        $dt = DateTimeImmutable::createFromFormat('Ymd\THis\Z', $v, new DateTimeZone('UTC'));
        $e[$k.'_DT'] = $dt?->setTimezone($tz);
      } elseif (preg_match('/^TZID=[^:]+:(\d{8}T\d{6})$/', $v, $m)) {
        $e[$k.'_DT'] = DateTimeImmutable::createFromFormat('Ymd\THis', $m[1], $tz);
      } elseif (preg_match('/^(\d{8}T\d{6})$/', $v, $m)) {
        $e[$k.'_DT'] = DateTimeImmutable::createFromFormat('Ymd\THis', $m[1], $tz);
      } elseif (preg_match('/^(\d{8})$/', $v, $m)) { // all-day
        $e[$k.'_DT'] = DateTimeImmutable::createFromFormat('Ymd', $m[1], $tz);
      }
    }
  }

  $events = array_values(array_filter($events, fn($e)=>isset($e['DTSTART_DT'],$e['DTEND_DT'],$e['SUMMARY'])));
  usort($events, fn($a,$b)=>$a['DTSTART_DT'] <=> $b['DTSTART_DT']);
  return $events;
}

function evr_format_service_name($summary, DateTimeImmutable $start) {
  // Canonical names by departure time; falls back to Calendar title if different
  return match ($start->format('H:i')) {
    '10:50' => 'EVR Morning Service (Wirksworth to Duffield)',
    '13:15' => 'EVR Midday Service (Wirksworth to Duffield)',
    '15:25' => 'EVR Afternoon Service (Wirksworth to Duffield)',
    default => $summary
  };
}

function evr_pick_trains($events) {
  $tz = new DateTimeZone('Europe/London');
  $now = new DateTimeImmutable('now', $tz);
  $cooldown = 15; // minutes after depart

  // Keep main route only (titles mention Wirksworth or Duffield)
  $events = array_values(array_filter($events, function($e){
    $s = strtolower($e['SUMMARY']);
    return str_contains($s,'wirksworth') || str_contains($s,'duffield');
  }));

  $current = $next = $after = null;
  foreach ($events as $e) {
    $st = $e['DTSTART_DT']; $en = $e['DTEND_DT'];
    if ($now >= $st && $now <= $en) { $current = $e; continue; }
    if ($now > $st && $now <= $st->modify("+{$cooldown} minutes")) { $current = $e; continue; }
    if ($now < $st) { if (!$next){ $next = $e; continue; } if (!$after){ $after = $e; break; } }
  }

  if (!$current && !$next) foreach ($events as $e) if ($e['DTSTART_DT'] > $now) { $next = $e; break; }
  if ($next && !$after) foreach ($events as $e) if ($e['DTSTART_DT'] > $next['DTSTART_DT']) { $after = $e; break; }

  return [$current,$next,$after,$now];
}

function evr_payload($e) {
  if (!$e) return null;
  $st=$e['DTSTART_DT']; $en=$e['DTEND_DT'];
  return [
    'summary'   => evr_format_service_name($e['SUMMARY'],$st),
    'raw'       => $e['SUMMARY'],
    'start_ts'  => $st->getTimestamp(),
    'end_ts'    => $en->getTimestamp(),
    'start_hm'  => $st->format('H:i'),
    'end_hm'    => $en->format('H:i'),
    'date_long' => $st->format('D j M Y'),
  ];
}

function evr_next_train_api(WP_REST_Request $r) {
  $ics = evr_fetch_ics();
  if (!$ics) return new WP_REST_Response(['error'=>'ICS fetch failed'], 500);

  $events = evr_parse_ics_events($ics);
  [$current,$next,$after,$now] = evr_pick_trains($events);

  return new WP_REST_Response([
    'now_ts'  => $now->getTimestamp(),
    'current' => evr_payload($current),
    'next'    => evr_payload($next),
    'after'   => evr_payload($after),
    'tz'      => 'Europe/London',
    'cooldown'=> 15,
    'message' => (!$current && !$next) ? 'No trains today' : null,
  ], 200);
}

add_shortcode('evr_next_train', function () {
  ob_start(); ?>
  <div id="evr-next-train" class="evr-banner" aria-live="polite">
    <div class="evr-inner">
      <div class="evr-line evr-status">Loading next train…</div>
      <div class="evr-line evr-detail"></div>
      <div class="evr-line evr-after"></div>
    </div>
  </div>
  <style>
    .evr-banner{width:100%;background:#0a4d97;color:#fff;padding:16px 20px}
    .evr-inner{max-width:1100px;margin:0 auto}
    .evr-line{font-size:18px;line-height:1.4}
    .evr-status{font-weight:700;font-size:22px}
    @media (max-width:640px){.evr-banner{padding:14px 16px}.evr-status{font-size:20px}.evr-line{font-size:16px}}
  </style>
  <script>
    (function(){
      const root = document.getElementById('evr-next-train');
      const s = root.querySelector('.evr-status');
      const d = root.querySelector('.evr-detail');
      const a = root.querySelector('.evr-after');

      function fmtMins(n){ return n===1?'1 min':n+' mins'; }
      function cd(to){ const m=Math.max(0,Math.round((to*1000-Date.now())/60000)); return m>0?`Departs in ${fmtMins(m)}`:'Departing now'; }
      function since(fr){ return `Departed ${fmtMins(Math.round((Date.now()-fr*1000)/60000))} ago`; }
      function hm(ts){ return new Date(ts*1000).toLocaleTimeString('en-GB',{hour:'2-digit',minute:'2-digit'}); }

      async function tick(){
        try{
          const res = await fetch('<?php echo esc_url( rest_url('evr/v1/next') ); ?>', {cache:'no-store'});
          const data = await res.json();

          if (data.error){ s.textContent = 'Unable to load next train'; d.textContent = ''; a.textContent=''; return; }

          if (data.current){
            const c = data.current;
            if (Date.now() < c.start_ts*1000){
              s.textContent = `${c.summary} — ${c.start_hm}–${c.end_hm} • ${cd(c.start_ts)}`;
              d.textContent = c.date_long;
            } else if (Date.now() < c.end_ts*1000){
              s.textContent = `${c.summary} — ${c.start_hm}–${c.end_hm} • In progress`;
              d.textContent = c.date_long;
            } else {
              s.textContent = `${c.summary} — ${c.start_hm}–${c.end_hm} • ${since(c.start_ts)}`;
              d.textContent = c.date_long;
            }
          } else if (data.next){
            const n = data.next;
            s.textContent = `${n.summary} — ${n.start_hm}–${n.end_hm} • ${cd(n.start_ts)}`;
            d.textContent = n.date_long;
          } else {
            s.textContent = data.message || 'No trains today';
            d.textContent = '';
          }

          if (data.after){
            const af = data.after;
            a.textContent = `Then: ${af.summary} at ${af.start_hm}`;
          } else { a.textContent = ''; }
        } catch(e){
          s.textContent = 'Unable to load next train';
          d.textContent = ''; a.textContent = '';
        }
      }
      tick(); setInterval(tick, 30000);
    })();
  </script>
  <?php return ob_get_clean();
});
/* ================= /EVR Next-Train Banner ================= */