<?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 colors 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 = $park['id'];
$heroImage = !empty($park['hero_image']) ? '/' . $park['hero_image'] : '/assets/hero.jpg';

// 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;
}

$stmt = $pdo->prepare("SELECT * FROM posts WHERE FIND_IN_SET(?, tags) ORDER BY created_at DESC");
$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;"; // fallback: Bootstrap primary blue hex
}

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">
  <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">
  <?php if (!empty($park['image_path'])): ?>
    <img src="/<?= ltrim($park['image_path'], '/') ?>" 
         alt="<?= htmlspecialchars($park['name']) ?> Logo" 
         class="mb-3"
         style="max-width:150px; max-height:150px; object-fit:contain;">
  <?php endif; ?>

  <h1 class="display-4 fw-bold"><?= htmlspecialchars($park['name']) ?></h1>
  <p class="lead text-white"><?= htmlspecialchars($park['location'] ?? 'Unknown location') ?></p>
</div>

</section>

<section class="py-4">
  <div class="container">
    <h2 class="mb-4">Quick Park Facts</h2>
    <div class="row text-center">
      <div class="col-md-3">
        <p>
          <strong>
            <span class="material-icons" style="vertical-align: middle;">event</span>
            Opened:
          </strong><br>
          <?= htmlspecialchars($park['opened'] ?? 'Unknown') ?>
        </p>
      </div>
      <div class="col-md-3">
        <p>
          <strong>
            <span class="material-icons" style="vertical-align: middle;">place</span>
            Location:
          </strong><br>
          <?= htmlspecialchars($park['location'] ?? 'Unknown') ?>
        </p>
      </div>
      <div class="col-md-3">
        <p>
          <strong>
            <span class="material-icons" style="vertical-align: middle;">roller_skating</span>
            Total Rides:
          </strong><br>
          <?= count($rides) ?>
        </p>
      </div>
      <div class="col-md-3">
        <p>
          <strong>
            <span class="material-icons" style="vertical-align: middle;">family_restroom</span>
            Family Friendly:
          </strong><br>
          <?= $park['is_family_friendly'] ? 'Yes' : 'No' ?>
        </p>
      </div>
    </div>
  </div>
</section>


<section class="bg-light py-5">
  <div class="container">
    <h2 class="mb-4">Featured Rides</h2>
    <div class="row g-4">
<?php foreach (array_slice($featuredRides, 0, 4) as $ride): ?>
        <div class="col-md-3">
<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($ride['image_path']) ?>">

            <img src="/<?= htmlspecialchars($ride['image_path']) ?>" 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>
  </div>
</section>


<section class="container py-5">
  <h2 class="mb-4">Articles</h2>
  <?php if (empty($guidePosts)): ?>
    <p>No articles found.</p>
  <?php else: ?>
    <div class="row g-4">
      <?php foreach ($guidePosts as $post): ?>
        <div class="col-md-4">
          <a href="/<?= htmlspecialchars($post['post_location']) ?>/<?= urlencode($post['slug']) ?>" class="text-decoration-none text-dark">
            <div class="card h-100 shadow-sm">
              <img src="/<?= htmlspecialchars($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><?= htmlspecialchars($post['tagline'] ?? '') ?></p>
                <?php if (!empty($post['tags'])): ?>
                  <div class="mt-2">
<?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">
  <h2 class="mb-4">All Rides</h2>

  <div class="mb-4 d-flex flex-wrap gap-2">
    <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-<?= $area['id'] ?>">
        <?= htmlspecialchars($area['name']) ?>
      </button>
    <?php endforeach; ?>
  </div>

  <?php foreach ($areas as $area): ?>
    <div class="area-section" data-area="area-<?= $area['id'] ?>">
      <h3 class="snazzy-title"><?= htmlspecialchars($area['name']) ?></h3>
      <div class="row g-4 mb-4">
        <?php if (isset($ridesByArea[$area['id']]) && is_array($ridesByArea[$area['id']])): ?>
          <?php foreach ($ridesByArea[$area['id']] as $ride): ?>
            <?php if (is_array($ride)): ?>
              <div class="col-md-3">
                <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($ride['image_path']) ?>">

                  <img src="/<?= htmlspecialchars($ride['image_path']) ?>" 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; ?>
</section>

</main>
<script>
    document.addEventListener('DOMContentLoaded', () => {
  const buttons = document.querySelectorAll('button[data-filter]');
  const sections = document.querySelectorAll('.area-section');

  buttons.forEach(button => {
    button.addEventListener('click', () => {
      // Remove active class on all buttons, add on clicked
      buttons.forEach(btn => btn.classList.remove('active'));
      button.classList.add('active');

      const filter = button.getAttribute('data-filter');

      if (filter === 'all') {
        sections.forEach(section => section.style.display = 'block');
      } else {
        sections.forEach(section => {
          if (section.getAttribute('data-area') === filter) {
            section.style.display = 'block';
          } else {
            section.style.display = 'none';
          }
        });
      }
    });
  });
});

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

  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('rideModalImage').src = card.dataset.image || '';
    });
  });
});
</script>

<!-- Ride Detail Modal -->
<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>
</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>

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

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