<?php
require_once __DIR__ . '/config.php';

$slug = $_GET['slug'] ?? '';
if (!$slug) {
    http_response_code(404);
    echo "<h1>404 Not Found</h1>";
    exit;
}

// Fetch tags and their colours from DB into an associative array
try {
    $stmtTags = $pdo->query("SELECT name, color FROM tags");
    $tagColors = [];

    while ($row = $stmtTags->fetch(PDO::FETCH_ASSOC)) {
        $tagColors[strtolower(trim($row['name']))] = $row['color'];
    }
} catch (PDOException $e) {
    $tagColors = [];
}

$stmt = $pdo->prepare("SELECT * FROM parks WHERE slug = ?");
$stmt->execute([$slug]);
$park = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$park) {
    http_response_code(404);
    echo "<h1>Park not found</h1>";
    exit;
}

$parkId = (int)$park['id'];
$heroImage = !empty($park['hero_image']) ? '/' . ltrim($park['hero_image'], '/') : '/assets/hero.jpg';

$parkLogo = !empty($park['image_path'])
    ? '/' . ltrim($park['image_path'], '/')
    : '/assets/default.jpg';

function getRideImage($ride, $parkLogo) {
    if (!empty($ride['image_path'])) {
        return '/' . ltrim($ride['image_path'], '/');
    }

    return $parkLogo;
}

function getQueueTimesForPark($queueTimesParkId) {
    if (empty($queueTimesParkId)) {
        return [];
    }

    $cacheDir = __DIR__ . '/cache';
    $cacheFile = $cacheDir . '/queue-times-' . (int)$queueTimesParkId . '.json';
    $cacheTime = 300; // 5 minutes
    $json = '';

    if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {
        $json = file_get_contents($cacheFile);
    } else {
        $url = 'https://queue-times.com/parks/' . (int)$queueTimesParkId . '/queue_times.json';
        $json = @file_get_contents($url);

        if ($json) {
            if (!is_dir($cacheDir)) {
                mkdir($cacheDir, 0755, true);
            }

            file_put_contents($cacheFile, $json);
        }
    }

    if (empty($json)) {
        return [];
    }

    $data = json_decode($json, true);

    if (!$data) {
        return [];
    }

    $queueData = [];

    if (!empty($data['lands'])) {
        foreach ($data['lands'] as $land) {
            if (!empty($land['rides'])) {
                foreach ($land['rides'] as $queueRide) {
                    $queueData[(int)$queueRide['id']] = $queueRide;
                }
            }
        }
    }

    if (!empty($data['rides'])) {
        foreach ($data['rides'] as $queueRide) {
            $queueData[(int)$queueRide['id']] = $queueRide;
        }
    }

    return $queueData;
}

function getParkBusyness($queueData) {
    if (empty($queueData)) {
        return [
            'label' => 'No live data',
            'class' => 'unknown',
            'average' => null
        ];
    }

    $openRides = array_filter($queueData, function ($ride) {
        return !empty($ride['is_open']);
    });

    if (empty($openRides)) {
        return [
            'label' => 'Closed',
            'class' => 'closed',
            'average' => null
        ];
    }

    $totalWait = array_sum(array_column($openRides, 'wait_time'));
    $average = round($totalWait / count($openRides));

    if ($average <= 20) {
        return [
            'label' => 'Quiet',
            'class' => 'quiet',
            'average' => $average
        ];
    }

    if ($average <= 45) {
        return [
            'label' => 'Moderate',
            'class' => 'moderate',
            'average' => $average
        ];
    }

    return [
        'label' => 'Busy',
        'class' => 'busy',
        'average' => $average
    ];
}

function getRideWaitInfo($ride, $queueData) {
    $queueRide = null;

    if (!empty($ride['queue_times_ride_id'])) {
        $queueRide = $queueData[(int)$ride['queue_times_ride_id']] ?? null;
    }

    $waitText = 'No live data';
    $waitClass = 'unknown';

    if ($queueRide) {
        if (!empty($queueRide['is_open'])) {
            $waitText = (int)$queueRide['wait_time'] . ' min wait';
            $waitClass = 'open';
        } else {
            $waitText = 'Closed';
            $waitClass = 'closed';
        }
    }

    return [
        'text' => $waitText,
        'class' => $waitClass,
        'ride' => $queueRide
    ];
}

$queueData = getQueueTimesForPark($park['queue_times_park_id'] ?? null);
$busyness = getParkBusyness($queueData);

$stmtHours = $pdo->prepare("
    SELECT *
    FROM park_opening_hours
    WHERE park_id = ?
    AND opening_date = CURDATE()
    LIMIT 1
");
$stmtHours->execute([$parkId]);
$todaysHours = $stmtHours->fetch(PDO::FETCH_ASSOC);

$openingHoursText = '';
$openingHoursClass = 'hidden';

if ($todaysHours) {
    if ($todaysHours['status'] === 'closed') {
        $openingHoursText = 'Closed today';
        $openingHoursClass = 'closed';
    } else {
        $openingHoursText =
            date('g:ia', strtotime($todaysHours['opens_at'])) .
            ' - ' .
            date('g:ia', strtotime($todaysHours['closes_at']));
        $openingHoursClass = 'open';
    }
}

// Fetch areas and rides
$stmt = $pdo->prepare("SELECT * FROM park_areas WHERE park_id = ? ORDER BY name ASC");
$stmt->execute([$parkId]);
$areas = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmt = $pdo->prepare("SELECT * FROM rides WHERE park_id = ? ORDER BY name ASC");
$stmt->execute([$parkId]);
$rides = $stmt->fetchAll(PDO::FETCH_ASSOC);

$stmtFeatured = $pdo->prepare("SELECT * FROM rides WHERE park_id = ? AND featured = 1 ORDER BY name ASC");
$stmtFeatured->execute([$parkId]);
$featuredRides = $stmtFeatured->fetchAll(PDO::FETCH_ASSOC);

$ridesByArea = [];
foreach ($rides as $ride) {
    $areaId = $ride['area_id'] ?? 0;
    $ridesByArea[$areaId][] = $ride;
}

// Keep articles lighter on park pages.
$stmt = $pdo->prepare("
    SELECT *
    FROM posts
    WHERE FIND_IN_SET(?, tags)
    ORDER BY created_at DESC
    LIMIT 3
");
$stmt->execute([$park['name']]);
$guidePosts = $stmt->fetchAll(PDO::FETCH_ASSOC);

function getTagColorStyle($tag, $tagColors) {
    $key = strtolower(trim($tag));

    if (isset($tagColors[$key]) && preg_match('/^#?[0-9A-Fa-f]{6}$/', $tagColors[$key])) {
        $color = $tagColors[$key];

        if ($color[0] !== '#') {
            $color = '#' . $color;
        }

        return "background-color: $color;";
    }

    return "background-color: #0d6efd;";
}

function formatDate($date) {
    return date('F j, Y', strtotime($date));
}

$extra_head = '<link rel="stylesheet" href="/styles/park.css">';
require_once __DIR__ . '/includes/header.php';
?>

<main>
<section class="hero position-relative park-hero">
  <img src="<?= htmlspecialchars($heroImage) ?>" class="hero-bg" alt="<?= htmlspecialchars($park['name']) ?>">
  <div class="gradient-overlay"></div>

  <div class="hero-content position-absolute top-50 start-50 translate-middle text-center text-white park-hero-content">
    <?php if (!empty($park['image_path'])): ?>
      <img src="/<?= ltrim($park['image_path'], '/') ?>"
           alt="<?= htmlspecialchars($park['name']) ?> Logo"
           class="mb-3 park-hero-logo"
           style="max-width:150px; max-height:150px; object-fit:contain;">
    <?php endif; ?>

    <h1 class="display-4 fw-bold"><?= htmlspecialchars($park['name']) ?></h1>

    <?php if (!empty($park['location'])): ?>
      <p class="park-hero-location text-white">
        <?= htmlspecialchars($park['location']) ?>
      </p>
    <?php endif; ?>

    <?php if ($openingHoursClass !== 'hidden'): ?>
      <div class="hero-opening-card <?= htmlspecialchars($openingHoursClass) ?>">
        <span class="material-icons">schedule</span>

        <div>
          <span class="hero-opening-label">Today&apos;s Opening Hours</span>
          <strong><?= htmlspecialchars($openingHoursText) ?></strong>
        </div>
      </div>
    <?php endif; ?>
  </div>
</section>

<section class="py-4 park-facts-section">
  <div class="container">
    <h2 class="mb-4">Quick Park Facts</h2>

    <div class="row g-3 text-center park-facts-grid">
      <div class="col-6 col-md-3">
        <div class="park-fact-card">
          <span class="material-icons">place</span>
          <strong>Location</strong>
          <span><?= htmlspecialchars($park['location'] ?? 'Unknown') ?></span>
        </div>
      </div>

      <div class="col-6 col-md-3">
        <div class="park-fact-card">
          <span class="material-icons">roller_skating</span>
          <strong>Total Rides</strong>
          <span><?= count($rides) ?></span>
        </div>
      </div>

      <div class="col-6 col-md-3">
        <button type="button"
                class="park-fact-card park-fact-card-button"
                id="busynessScrollButton"
                aria-label="Jump to all rides">
          <span class="material-icons">speed</span>
          <strong>Park Busyness</strong>

          <span class="busyness-pill <?= htmlspecialchars($busyness['class']) ?>" style="color:#FFF!important">
            <span class="live-dot"></span>
            <?= htmlspecialchars($busyness['label']) ?>
          </span>

          <?php if ($busyness['average'] !== null): ?>
            <small>Avg wait: <?= (int)$busyness['average'] ?> mins</small>
          <?php else: ?>
            <small>View ride status</small>
          <?php endif; ?>
        </button>
      </div>

      <div class="col-6 col-md-3">
        <div class="park-fact-card">
          <span class="material-icons">family_restroom</span>
          <strong>Family Friendly</strong>
          <span><?= !empty($park['is_family_friendly']) ? 'Yes' : 'No' ?></span>
        </div>
      </div>
    </div>
  </div>
</section>

<section class="bg-light py-5 featured-rides-section">
  <div class="container">
    <div class="section-heading-row">
      <h2 class="mb-0">Featured Rides</h2>
    </div>

    <div class="row g-4 featured-rides-row">
      <?php foreach (array_slice($featuredRides, 0, 4) as $ride): ?>
        <?php
          $rideImage = getRideImage($ride, $parkLogo);
          $waitInfo = getRideWaitInfo($ride, $queueData);
        ?>

        <div class="col-md-3 featured-ride-col">
          <div class="card h-100 shadow-sm position-relative overflow-hidden ride-card"
               data-bs-toggle="modal"
               data-bs-target="#rideModal"
               data-name="<?= htmlspecialchars($ride['name'] ?? '') ?>"
               data-description="<?= htmlspecialchars($ride['description'] ?? '') ?>"
               data-rating="<?= htmlspecialchars($ride['rating'] ?? '') ?>"
               data-duration="<?= htmlspecialchars($ride['duration_minutes'] ?? '—') ?>"
               data-thrill="<?= htmlspecialchars($ride['thrill_level'] ?? '') ?>"
               data-height="<?= htmlspecialchars($ride['min_height_cm'] ?? '') ?>"
               data-image="<?= htmlspecialchars($rideImage) ?>"
               data-wait="<?= htmlspecialchars($waitInfo['text']) ?>"
               data-wait-class="<?= htmlspecialchars($waitInfo['class']) ?>">

            <?php if (!empty($ride['queue_times_ride_id'])): ?>
              <div class="wait-time-badge <?= htmlspecialchars($waitInfo['class']) ?>">
                <span class="live-dot"></span>
                <?= htmlspecialchars($waitInfo['text']) ?>
              </div>
            <?php endif; ?>

            <img src="<?= htmlspecialchars($rideImage) ?>" class="card-img-top" alt="<?= htmlspecialchars($ride['name']) ?>">

            <div class="card-body">
              <h5 class="card-title text-alt"><?= htmlspecialchars($ride['name']) ?></h5>
              <p class="card-text text-alt"><?= htmlspecialchars(substr($ride['description'] ?? '', 0, 60)) ?>...</p>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
    </div>

    <?php if (!empty($queueData)): ?>
      <p class="small text-muted mt-3 mb-0">
        Live queue data powered by
        <a href="https://queue-times.com/" target="_blank" rel="noopener">Queue-Times.com</a>.
      </p>
    <?php endif; ?>
  </div>
</section>

<section class="container py-4 park-articles-section">
  <h2 class="mb-3">Latest from <?= htmlspecialchars($park['name']) ?></h2>

  <?php if (empty($guidePosts)): ?>
    <p>No articles found.</p>
  <?php else: ?>
    <div class="row g-3 park-articles-row">
      <?php foreach ($guidePosts as $post): ?>
        <div class="col-md-4 park-article-col">
          <a href="/<?= htmlspecialchars($post['post_location']) ?>/<?= urlencode($post['slug']) ?>" class="text-decoration-none text-dark">
            <div class="card h-100 shadow-sm park-article-card">
              <img src="/<?= htmlspecialchars(ltrim($post['image_path'] ?? 'assets/default.jpg', '/')) ?>" class="card-img-top" alt="<?= htmlspecialchars($post['title']) ?>">

              <div class="card-body">
                <p class="text-muted"><?= formatDate($post['created_at']) ?></p>
                <h5 class="card-title text-alt"><?= htmlspecialchars($post['title']) ?></h5>
                <p class="park-article-tagline"><?= htmlspecialchars($post['tagline'] ?? '') ?></p>

                <?php if (!empty($post['tags'])): ?>
                  <div class="mt-2 park-article-tags">
                    <?php foreach (explode(',', $post['tags']) as $tag): ?>
                      <span class="badge rounded-pill text-white" style="<?= getTagColorStyle($tag, $tagColors) ?>">
                        <?= htmlspecialchars(trim($tag)) ?>
                      </span>
                    <?php endforeach; ?>
                  </div>
                <?php endif; ?>
              </div>
            </div>
          </a>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>
</section>

<section class="container py-5 all-rides-section" id="allRidesSection">
  <div class="all-rides-header">
    <div>
      <h2 class="mb-1">All Rides</h2>
      <p class="text-muted mb-0">Search, filter and check live ride status where available.</p>
    </div>

    <?php if (!empty($queueData)): ?>
      <span class="live-data-pill">
        <span class="live-dot"></span>
        Live data
      </span>
    <?php endif; ?>
  </div>

  <div class="ride-tools">
    <div class="ride-search-wrap">
      <span class="material-icons">search</span>

      <input
        type="text"
        id="rideSearchInput"
        class="ride-search-input"
        placeholder="Search rides..."
        autocomplete="off"
      >
    </div>

    <div class="ride-filter-scroll" aria-label="Ride area filters">
      <button class="btn btn-outline-primary active" data-filter="all">All</button>

      <?php foreach ($areas as $area): ?>
        <button class="btn btn-outline-primary" data-filter="area-<?= (int)$area['id'] ?>">
          <?= htmlspecialchars($area['name']) ?>
        </button>
      <?php endforeach; ?>
    </div>
  </div>

  <?php foreach ($areas as $area): ?>
    <div class="area-section" data-area="area-<?= (int)$area['id'] ?>">
      <h3 class="snazzy-title"><?= htmlspecialchars($area['name']) ?></h3>

      <div class="row g-4 mb-4 ride-grid">
        <?php if (isset($ridesByArea[$area['id']]) && is_array($ridesByArea[$area['id']])): ?>
          <?php foreach ($ridesByArea[$area['id']] as $ride): ?>
            <?php if (is_array($ride)): ?>
              <?php
                $rideImage = getRideImage($ride, $parkLogo);
                $waitInfo = getRideWaitInfo($ride, $queueData);
              ?>

              <div class="col-md-3 ride-card-wrap" data-ride-name="<?= htmlspecialchars(strtolower($ride['name'] ?? '')) ?>">
                <div class="card h-100 shadow-sm position-relative overflow-hidden ride-card"
                     data-bs-toggle="modal"
                     data-bs-target="#rideModal"
                     data-name="<?= htmlspecialchars($ride['name'] ?? '') ?>"
                     data-description="<?= htmlspecialchars($ride['description'] ?? '') ?>"
                     data-rating="<?= htmlspecialchars($ride['rating'] ?? '') ?>"
                     data-duration="<?= htmlspecialchars($ride['duration_minutes'] ?? '') ?>"
                     data-thrill="<?= htmlspecialchars($ride['thrill_level'] ?? '') ?>"
                     data-height="<?= htmlspecialchars($ride['min_height_cm'] ?? '') ?>"
                     data-image="<?= htmlspecialchars($rideImage) ?>"
                     data-wait="<?= htmlspecialchars($waitInfo['text']) ?>"
                     data-wait-class="<?= htmlspecialchars($waitInfo['class']) ?>">

                  <?php if (!empty($ride['queue_times_ride_id'])): ?>
                    <div class="wait-time-badge <?= htmlspecialchars($waitInfo['class']) ?>">
                      <span class="live-dot"></span>
                      <?= htmlspecialchars($waitInfo['text']) ?>
                    </div>
                  <?php endif; ?>

                  <img src="<?= htmlspecialchars($rideImage) ?>" class="card-img-top" alt="<?= htmlspecialchars($ride['name']) ?>">

                  <div class="card-title-overlay position-absolute w-100 text-white px-2 py-1">
                    <h6 class="m-0 text-white"><?= htmlspecialchars($ride['name']) ?></h6>
                  </div>
                </div>
              </div>
            <?php endif; ?>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>
  <?php endforeach; ?>

  <p id="noRideResults" class="text-muted mt-3" style="display:none;">
    No rides found matching your search.
  </p>

  <?php if (!empty($queueData)): ?>
    <p class="small text-muted mt-3">
      Live queue data powered by
      <a href="https://queue-times.com/" target="_blank" rel="noopener">Queue-Times.com</a>.
    </p>
  <?php endif; ?>
</section>

</main>

<script>
document.addEventListener('DOMContentLoaded', () => {
  const buttons = document.querySelectorAll('button[data-filter]');
  const sections = document.querySelectorAll('.area-section');
  const searchInput = document.getElementById('rideSearchInput');
  const noRideResults = document.getElementById('noRideResults');
  const busynessScrollButton = document.getElementById('busynessScrollButton');
  const allRidesSection = document.getElementById('allRidesSection');

  let activeFilter = 'all';

  function filterRides() {
    const searchTerm = searchInput ? searchInput.value.toLowerCase().trim() : '';
    let totalVisibleCards = 0;

    sections.forEach(section => {
      const sectionMatchesFilter =
        activeFilter === 'all' ||
        section.getAttribute('data-area') === activeFilter;

      let visibleCards = 0;
      const cards = section.querySelectorAll('.ride-card-wrap');

      cards.forEach(card => {
        const rideName = card.getAttribute('data-ride-name') || '';
        const matchesSearch = rideName.includes(searchTerm);
        const shouldShow = sectionMatchesFilter && matchesSearch;

        card.style.display = shouldShow ? 'block' : 'none';

        if (shouldShow) {
          visibleCards++;
          totalVisibleCards++;
        }
      });

      section.style.display = visibleCards > 0 ? 'block' : 'none';
    });

    if (noRideResults) {
      noRideResults.style.display = totalVisibleCards === 0 ? 'block' : 'none';
    }
  }

  buttons.forEach(button => {
    button.addEventListener('click', () => {
      buttons.forEach(btn => btn.classList.remove('active'));
      button.classList.add('active');
      activeFilter = button.getAttribute('data-filter');
      filterRides();
    });
  });

  if (searchInput) {
    searchInput.addEventListener('input', filterRides);
  }

  if (busynessScrollButton && allRidesSection) {
    busynessScrollButton.addEventListener('click', () => {
      allRidesSection.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      });
    });
  }

  filterRides();
});

document.addEventListener('DOMContentLoaded', function () {
  const rideCards = document.querySelectorAll('.ride-card');

  rideCards.forEach(card => {
    card.addEventListener('click', () => {
      document.getElementById('rideModalName').textContent = card.dataset.name || '';
      document.getElementById('rideModalDescription').textContent = card.dataset.description || '';
      document.getElementById('rideModalRating').textContent = card.dataset.rating || 'N/A';
      document.getElementById('rideModalThrill').textContent = card.dataset.thrill || 'Unknown';
      document.getElementById('rideModalDuration').textContent = card.dataset.duration || 'N/A';
      document.getElementById('rideModalHeight').textContent = card.dataset.height || 'N/A';
      document.getElementById('rideModalWait').textContent = card.dataset.wait || 'No live data';
      document.getElementById('rideModalImage').src = card.dataset.image || '';
      document.getElementById('rideModalImage').alt = card.dataset.name || '';
    });
  });
});
</script>

<div class="modal fade" id="rideModal" tabindex="-1" aria-labelledby="rideModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content">

      <div class="modal-header flex-column align-items-start">
        <div class="d-flex w-100 justify-content-between align-items-start">
          <h5 class="modal-title mb-1" id="rideModalName"></h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>

        <div class="d-flex flex-wrap gap-3 text-muted small align-items-center">
          <div class="d-flex align-items-center">
            <span class="material-icons me-1" style="font-size: 18px;">star_rate</span>
            <strong class="me-1">Rating:</strong>
            <span id="rideModalRating">N/A</span>/5
          </div>

          <div class="d-flex align-items-center">
            <span class="material-icons me-1" style="font-size: 18px;">bolt</span>
            <strong class="me-1">Thrill:</strong>
            <span id="rideModalThrill">—</span>
          </div>

          <div class="d-flex align-items-center">
            <span class="material-icons me-1" style="font-size: 18px;">schedule</span>
            <strong class="me-1">Duration:</strong>
            <span id="rideModalDuration">—</span> min
          </div>

          <div class="d-flex align-items-center">
            <span class="material-icons me-1" style="font-size: 18px;">height</span>
            <strong class="me-1">Min Height:</strong>
            <span id="rideModalHeight">—</span> cm
          </div>

          <div class="d-flex align-items-center">
            <span class="material-icons me-1" style="font-size: 18px;">timer</span>
            <strong class="me-1">Wait:</strong>
            <span id="rideModalWait">No live data</span>
          </div>
        </div>
      </div>

      <div class="modal-body d-flex flex-column flex-md-row">
        <img id="rideModalImage"
             src=""
             alt=""
             class="img-fluid mb-3 mb-md-0 me-md-4 rounded"
             style="max-width: 300px;">

        <div>
          <p id="rideModalDescription"></p>

          <?php if (!empty($queueData)): ?>
            <p class="small text-muted mb-0">
              Live queue data powered by
              <a href="https://queue-times.com/" target="_blank" rel="noopener">Queue-Times.com</a>.
            </p>
          <?php endif; ?>
        </div>
      </div>

    </div>
  </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
