<?php
require_once 'config.php';

$countrySlug = isset($_GET['country']) ? trim($_GET['country']) : '';
$country = null;
$trips = [];

if ($countrySlug) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM countries WHERE slug = ?");
        $stmt->execute([$countrySlug]);
        $country = $stmt->fetch();
        
        if ($country) {
            $stmtTrips = $pdo->prepare("SELECT * FROM trips WHERE country_id = ? ORDER BY id ASC");
            $stmtTrips->execute([$country['id']]);
            $trips = $stmtTrips->fetchAll();
        }
    } catch (Exception $e) {
        // Handle error silently
    }
}

// Month extraction helper
function get_month_info($dateStr) {
    $monthMap = [
        'januari' => ['01', 'Januari'], 'january' => ['01', 'Januari'], 'jan' => ['01', 'Januari'],
        'februari' => ['02', 'Februari'], 'february' => ['02', 'Februari'], 'feb' => ['02', 'Februari'],
        'maret' => ['03', 'Maret'], 'march' => ['03', 'Maret'], 'mar' => ['03', 'Maret'],
        'april' => ['04', 'April'], 'apr' => ['04', 'April'],
        'mei' => ['05', 'Mei'], 'may' => ['05', 'Mei'],
        'juni' => ['06', 'Juni'], 'june' => ['06', 'Juni'], 'jun' => ['06', 'Juni'],
        'juli' => ['07', 'Juli'], 'july' => ['07', 'Juli'], 'jul' => ['07', 'Juli'],
        'agustus' => ['08', 'Agustus'], 'august' => ['08', 'Agustus'], 'aug' => ['08', 'Agustus'], 'agu' => ['08', 'Agustus'], 'ags' => ['08', 'Agustus'],
        'september' => ['09', 'September'], 'sep' => ['09', 'September'], 'sept' => ['09', 'September'],
        'oktober' => ['10', 'Oktober'], 'october' => ['10', 'Oktober'], 'okt' => ['10', 'Oktober'], 'oct' => ['10', 'Oktober'],
        'november' => ['11', 'November'], 'nov' => ['11', 'November'],
        'desember' => ['12', 'Desember'], 'december' => ['12', 'Desember'], 'des' => ['12', 'Desember'], 'dec' => ['12', 'Desember'],
    ];

    $clean = strtolower(trim((string)$dateStr));
    $year = '';
    if (preg_match('/\b(20\d\d)\b/', $clean, $m)) {
        $year = $m[1];
    } else {
        $year = date('Y');
    }

    foreach ($monthMap as $mKey => $mVal) {
        if (preg_match('/\b' . preg_quote($mKey, '/') . '\b/i', $clean)) {
            return [
                'key'        => $year . '-' . $mVal[0],
                'month_num'  => $mVal[0],
                'month_name' => $mVal[1],
                'year'       => $year,
                'label'      => $mVal[1] . ' ' . $year
            ];
        }
    }

    return null;
}

// Compute available unique months from trips
$availableMonths = [];
foreach ($trips as $t) {
    $info = get_month_info($t['dateStart'] ?? '') ?: get_month_info($t['dateRange'] ?? '');
    if ($info) {
        $mKey = $info['key'];
        if (!isset($availableMonths[$mKey])) {
            $availableMonths[$mKey] = [
                'label' => $info['label'],
                'count' => 0,
                'key'   => $mKey
            ];
        }
        $availableMonths[$mKey]['count']++;
    }
}
ksort($availableMonths);

$pageTitle = $country ? "Travelica — " . $country['name'] . " Travel Packages" : "Destinasi Tidak Ditemukan";
$activePage = 'destinasi';
$extraCSS = '<link rel="stylesheet" href="assets/css/negara.css" /><style>.cn-hero { opacity: 1 !important; transform: none !important; }</style>';
include 'includes/header.php';
?>

  <!-- ── HERO ─────────────────────────────────────────────── -->
<?php if (!$country): ?>
  <main class="cn-main" style="padding: 100px 0; text-align: center;">
    <div class="cn-not-found" id="cnNotFound" style="display:flex;">
      <div class="cn-nf-icon">🗺️</div>
      <h3>Destinasi Tidak Ditemukan</h3>
      <p>Halaman yang Anda cari tidak tersedia. Kembali ke daftar destinasi.</p>
      <a href="destinasi" class="cn-goto-dest">Lihat Semua Destinasi</a>
    </div>
  </main>
<?php else: ?>
  <section class="cn-hero ready" id="cnHero">
    <div class="cn-hero-bg">
      <img src="<?= htmlspecialchars($country['heroImg']) ?>" alt="<?= htmlspecialchars($country['name']) ?>" class="cn-hero-img" id="cnHeroImg" onerror="this.src='assets/images/dest_japan.webp'" />
      <div class="cn-hero-overlay"></div>
    </div>

    <!-- Back button -->
    <a href="destinasi" class="cn-back-btn" id="cnBackBtn">
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
        <path d="M19 12H5M12 5l-7 7 7 7" />
      </svg>
      Semua Destinasi
    </a>

    <!-- Hero text -->
    <div class="cn-hero-content">
      <span class="cn-flag" id="cnFlag"></span>
      <span class="cn-eyebrow" id="cnTagline"><?= htmlspecialchars($country['tagline'] ?: "Explore " . $country['name']) ?></span>
      <h1 class="cn-title" id="cnTitle"><?= htmlspecialchars($country['name']) ?></h1>
      <p class="cn-desc" id="cnDesc"><?= htmlspecialchars($country['description']) ?></p>
    </div>
  </section>

  <!-- ── TRIP LIST ─────────────────────────────────────────── -->
  <main class="cn-main">
    <div class="cn-wrap">
      <div class="cn-list-header">
        <div>
          <h2 class="cn-list-heading" id="cnTripsHeading">Paket Trip ke <?= htmlspecialchars($country['name']) ?></h2>
          <p class="cn-list-sub">Pilih jadwal keberangkatan yang sesuai dengan rencana Anda</p>
        </div>
        <span class="cn-list-badge" id="cnListBadge"><?= count($trips) ?> Trip Tersedia</span>
      </div>

      <?php if (!empty($trips) && count($trips) > 0): ?>
      <!-- Month Filter & Search Bar -->
      <div class="cn-filter-bar">
        <div class="cn-filter-top">
          <!-- Month Pills (Scrollable on Mobile) -->
          <div class="cn-month-pills-wrap">
            <span class="cn-filter-label">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                <line x1="16" y1="2" x2="16" y2="6"></line>
                <line x1="8" y1="2" x2="8" y2="6"></line>
                <line x1="3" y1="10" x2="21" y2="10"></line>
              </svg>
              Bulan Berangkat:
            </span>
            <div class="cn-month-pills" id="cnMonthPills">
              <button type="button" class="cn-month-pill active" data-month="all">
                Semua Bulan
                <span class="cn-pill-count"><?= count($trips) ?></span>
              </button>
              <?php foreach ($availableMonths as $mKey => $mInfo): ?>
                <button type="button" class="cn-month-pill" data-month="<?= htmlspecialchars($mKey) ?>">
                  <?= htmlspecialchars($mInfo['label']) ?>
                  <span class="cn-pill-count"><?= $mInfo['count'] ?></span>
                </button>
              <?php endforeach; ?>
            </div>
          </div>

          <!-- Realtime Search Input -->
          <div class="cn-search-box">
            <svg class="cn-search-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2">
              <circle cx="11" cy="11" r="8"></circle>
              <path d="m21 21-4.35-4.35"></path>
            </svg>
            <input type="text" id="cnTripSearch" class="cn-search-input" placeholder="Cari bulan atau rute..." autocomplete="off" />
            <button type="button" id="cnClearSearch" class="cn-clear-btn" aria-label="Hapus pencarian" style="display:none;">&times;</button>
          </div>
        </div>

        <!-- Filter Active Feedback Message -->
        <div id="cnFilterStatus" class="cn-filter-status" style="display:none;">
          <span>Menampilkan hasil untuk: <strong id="cnActiveFilterText"></strong></span>
          <button type="button" id="cnResetAllFilters" class="cn-reset-link">Reset Semua</button>
        </div>
      </div>
      <?php endif; ?>

      <!-- Clean Ticket Cards Grid matching Gambar 2 -->
      <div class="cn-trip-grid" id="cnTripList">
        <?php if (empty($trips)): ?>
          <div class="cn-empty-trips">
            <div style="font-size:36px;margin-bottom:8px;">✈️</div>
            <h3 style="font-size:17px;font-weight:700;color:#0f172a;margin-bottom:6px;">Belum Ada Jadwal Trip</h3>
            <p style="color:#64748b;font-size:13.5px;margin:0;">Paket perjalanan untuk destinasi ini sedang disiapkan.</p>
          </div>
        <?php else: ?>
          <?php foreach ($trips as $trip): 
            $mInfo = get_month_info($trip['dateStart'] ?? '') ?: get_month_info($trip['dateRange'] ?? '');
            $tripMonthKey = $mInfo ? $mInfo['key'] : '';
            $tripMonthLabel = $mInfo ? $mInfo['label'] : '';
            $searchKeywords = strtolower($trip['name'] . ' ' . ($trip['code'] ?? '') . ' ' . $trip['dateRange'] . ' ' . ($trip['dateStart'] ?? '') . ' ' . $trip['duration'] . ' ' . $tripMonthLabel);
          ?>
          <div class="cn-ticket-card" 
               id="trip-card-<?= htmlspecialchars($trip['id']) ?>"
               data-month-key="<?= htmlspecialchars($tripMonthKey) ?>"
               data-month-name="<?= htmlspecialchars($tripMonthLabel) ?>"
               data-search-text="<?= htmlspecialchars($searchKeywords) ?>">
            <div>
              <!-- Header: Title & Code -->
              <div class="cn-ticket-header">
                <h3 class="cn-ticket-title"><?= htmlspecialchars($trip['name']) ?></h3>
                <?php if (!empty($trip['code'])): ?>
                <span class="cn-ticket-code"><?= htmlspecialchars($trip['code']) ?></span>
                <?php endif; ?>
              </div>

              <!-- Meta: Date & Duration -->
              <div class="cn-ticket-meta">
                <!-- Date with Calendar Icon -->
                <div class="cn-meta-item">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                    <line x1="16" y1="2" x2="16" y2="6"/>
                    <line x1="8" y1="2" x2="8" y2="6"/>
                    <line x1="3" y1="10" x2="21" y2="10"/>
                  </svg>
                  <span><?= htmlspecialchars($trip['dateRange']) ?></span>
                </div>

                <!-- Duration with Clock Icon -->
                <div class="cn-meta-item">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <circle cx="12" cy="12" r="10"/>
                    <polyline points="12 6 12 12 16 14"/>
                  </svg>
                  <span><?= htmlspecialchars($trip['duration']) ?></span>
                </div>
              </div>
            </div>

            <!-- Bottom: Price & VIEW TRIP Button -->
            <div class="cn-ticket-bottom">
              <div class="cn-ticket-price-wrap">
                <span class="cn-ticket-price">Rp<?= number_format($trip['price'], 0, ',', '.') ?></span>
                <span class="cn-ticket-pax">/pax</span>
              </div>
              <a href="detail-trip?trip=<?= urlencode($trip['id']) ?>" class="cn-ticket-btn">
                VIEW TRIP
              </a>
            </div>
          </div>
          <?php endforeach; ?>

          <!-- Empty filter result placeholder -->
          <div class="cn-empty-filter" id="cnEmptyFilter" style="display:none;">
            <div class="cn-empty-icon">🔍</div>
            <h3>Tidak Ada Jadwal Trip Ditemukan</h3>
            <p>Tidak ada paket trip yang cocok dengan bulan atau kata kunci pencarian Anda.</p>
            <button type="button" class="cn-reset-btn" id="cnResetFilterBtn">Tampilkan Semua Trip</button>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </main>

  <!-- Interactive Filter Script -->
  <script>
  document.addEventListener('DOMContentLoaded', function() {
    const pills = document.querySelectorAll('.cn-month-pill');
    const searchInput = document.getElementById('cnTripSearch');
    const clearBtn = document.getElementById('cnClearSearch');
    const cards = document.querySelectorAll('.cn-ticket-card');
    const badge = document.getElementById('cnListBadge');
    const emptyFilter = document.getElementById('cnEmptyFilter');
    const filterStatus = document.getElementById('cnFilterStatus');
    const activeFilterText = document.getElementById('cnActiveFilterText');
    const resetLink = document.getElementById('cnResetAllFilters');
    const resetBtn = document.getElementById('cnResetFilterBtn');
    const totalTrips = cards.length;

    let activeMonth = 'all';
    let searchQuery = '';

    function applyFilter() {
      let visibleCount = 0;
      const q = searchQuery.toLowerCase().trim();

      cards.forEach(card => {
        const cardMonth = card.getAttribute('data-month-key') || '';
        const cardSearch = (card.getAttribute('data-search-text') || '').toLowerCase();

        const matchesMonth = (activeMonth === 'all' || cardMonth === activeMonth);
        const matchesSearch = (!q || cardSearch.includes(q));

        if (matchesMonth && matchesSearch) {
          card.style.display = 'flex';
          visibleCount++;
        } else {
          card.style.display = 'none';
        }
      });

      // Update badge
      if (badge) {
        if (activeMonth === 'all' && !q) {
          badge.textContent = totalTrips + ' Trip Tersedia';
        } else {
          badge.textContent = visibleCount + ' Trip Ditemukan';
        }
      }

      // Toggle empty state
      if (emptyFilter) {
        emptyFilter.style.display = (visibleCount === 0 && totalTrips > 0) ? 'block' : 'none';
      }

      // Toggle clear search button
      if (clearBtn) {
        clearBtn.style.display = q ? 'flex' : 'none';
      }

      // Status bar feedback
      if (filterStatus) {
        const activePill = document.querySelector('.cn-month-pill.active');
        const activeLabel = activePill && activeMonth !== 'all' ? activePill.childNodes[0].textContent.trim() : '';

        let statusParts = [];
        if (activeLabel) statusParts.push('Bulan ' + activeLabel);
        if (q) statusParts.push('Kata kunci "' + q + '"');

        if (statusParts.length > 0) {
          activeFilterText.textContent = statusParts.join(' & ');
          filterStatus.style.display = 'flex';
        } else {
          filterStatus.style.display = 'none';
        }
      }
    }

    // Pill click handler
    pills.forEach(pill => {
      pill.addEventListener('click', function() {
        pills.forEach(p => p.classList.remove('active'));
        this.classList.add('active');
        activeMonth = this.getAttribute('data-month') || 'all';
        applyFilter();
      });
    });

    // Search input handler
    if (searchInput) {
      searchInput.addEventListener('input', function() {
        searchQuery = this.value;
        applyFilter();
      });
    }

    // Clear search input
    if (clearBtn) {
      clearBtn.addEventListener('click', function() {
        searchInput.value = '';
        searchQuery = '';
        applyFilter();
        searchInput.focus();
      });
    }

    // Reset all handler
    function resetAll() {
      activeMonth = 'all';
      searchQuery = '';
      if (searchInput) searchInput.value = '';
      pills.forEach(p => {
        if (p.getAttribute('data-month') === 'all') {
          p.classList.add('active');
        } else {
          p.classList.remove('active');
        }
      });
      applyFilter();
    }

    if (resetLink) resetLink.addEventListener('click', resetAll);
    if (resetBtn) resetBtn.addEventListener('click', resetAll);

    // Check URL query param for default month (e.g. ?bulan=2026-08 or ?bulan=aug)
    const urlParams = new URLSearchParams(window.location.search);
    const paramMonth = urlParams.get('bulan') || urlParams.get('month');
    if (paramMonth) {
      const matchingPill = Array.from(pills).find(p => {
        const dm = (p.getAttribute('data-month') || '').toLowerCase();
        const txt = p.textContent.toLowerCase();
        return dm.includes(paramMonth.toLowerCase()) || txt.includes(paramMonth.toLowerCase());
      });
      if (matchingPill) {
        matchingPill.click();
      }
    }
  });
  </script>
<?php endif; ?>

<?php include 'includes/footer.php'; ?>