<?php
if (!defined('ABSPATH')) exit;

$base = rtrim((string)($ctx['base_url'] ?? ''), '/') . '/';

$past_months = max(1, (int) apply_filters('blr_ba_calendar_past_months', 12));
$future_months = max(1, (int) apply_filters('blr_ba_calendar_future_months', 24));
$calendar_timezone = wp_timezone();
$calendar_now = new DateTimeImmutable('now', $calendar_timezone);
$range_start = $calendar_now->modify('-' . $past_months . ' months')->modify('first day of this month')->setTime(0, 0, 0)->format('Y-m-d H:i:s');
$range_end = $calendar_now->modify('+' . $future_months . ' months')->modify('last day of this month')->setTime(23, 59, 59)->format('Y-m-d H:i:s');
$cache_version = \BLR\Backline\Modules\Events\Module::calendar_cache_version();
$cache_key = 'blr_ba_calendar_events_' . md5($cache_version . '|' . $range_start . '|' . $range_end);
$events = get_transient($cache_key);

if (!is_array($events)) {
  $q = new WP_Query([
    'post_type' => 'blr_event',
    'post_status' => ['publish'],
    'posts_per_page' => -1,
    'meta_key' => 'blr_event_start',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'meta_query' => [[
      'key' => 'blr_event_start',
      'value' => [$range_start, $range_end],
      'compare' => 'BETWEEN',
      'type' => 'CHAR',
    ]],
    'no_found_rows' => true,
  ]); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query

  $events = [];
  foreach ($q->posts as $p) {
    $start = (string)get_post_meta($p->ID, 'blr_event_start', true);
    if (!$start) continue;
    $events[] = [
      'id' => (int)$p->ID,
      'title' => (string)get_the_title($p),
      'start' => $start,
      'url' => $base . 'events/view/' . (int)$p->ID . '/',
    ];
  }
  wp_reset_postdata();
  set_transient($cache_key, $events, 5 * MINUTE_IN_SECONDS);
}

wp_add_inline_script(
  'blr-ba-plugin',
  'window.BLR_BA_CAL_EVENTS = ' . wp_json_encode($events, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) . ';',
  'before'
);
?>

<div class="container-fluid p-0">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <div>
      <h1 class="h3 mb-0"><?php echo esc_html__('Calendar', 'blr-backline'); ?></h1>
      <div class="text-muted small"><?php
        /* translators: 1: start date, 2: end date. */
        printf(esc_html__('Showing events from %1$s through %2$s.', 'blr-backline'), esc_html(date_i18n('M j, Y', strtotime($range_start))), esc_html(date_i18n('M j, Y', strtotime($range_end))));
      ?></div>
    </div>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-secondary" href="<?php echo esc_url($base . 'events/'); ?>"><?php echo esc_html__('Events', 'blr-backline'); ?></a>
      <a class="btn btn-primary" href="<?php echo esc_url($base . 'events/new/'); ?>"><?php echo esc_html__('New Event', 'blr-backline'); ?></a>
    </div>
  </div>

  <div class="card">
    <div class="card-body">
      <div class="d-flex align-items-center justify-content-between mb-3">
        <div class="d-flex gap-2">
          <a href="#" id="blr-ba-cal-prev" class="btn btn-sm btn-outline-secondary" aria-label="<?php echo esc_attr__('Previous month', 'blr-backline'); ?>"><i data-feather="chevron-left"></i></a>
          <a href="#" id="blr-ba-cal-next" class="btn btn-sm btn-outline-secondary" aria-label="<?php echo esc_attr__('Next month', 'blr-backline'); ?>"><i data-feather="chevron-right"></i></a>
          <a href="#" id="blr-ba-cal-today" class="btn btn-sm btn-outline-secondary"><?php echo esc_html__('Today', 'blr-backline'); ?></a>
        </div>
        <div class="h5 mb-0" id="blr-ba-cal-label">—</div>
      </div>

      <div id="blr-ba-calendar" class="blr-ba-calendar"></div>

      <?php if (empty($events)): ?>
        <div class="text-muted mt-3"><?php echo esc_html__('No events with a start date in the current calendar window yet.', 'blr-backline'); ?></div>
      <?php endif; ?>
    </div>
  </div>
</div>
