<?php
$activePage = 'destinasi';
require_once 'config.php';

$q = trim($_GET['q'] ?? '');
$isJson = isset($_GET['json']) && $_GET['json'] === '1';

// ── JSON (autocomplete) response ──────────────────────────────
if ($isJson) {
    header('Content-Type: application/json; charset=utf-8');
    $results = [];
    if ($q !== '') {
        $like = '%' . $q . '%';
        try {
            // Search trips
            $stmt = $pdo->prepare("
                SELECT t.id, t.name, t.code, t.duration, t.price,
                       c.name AS country_name, c.slug AS country_slug
                FROM trips t
                LEFT JOIN countries c ON c.id = t.country_id
                WHERE t.name LIKE ? OR t.code LIKE ? OR c.name LIKE ?
                ORDER BY c.name ASC, t.name ASC
                LIMIT 8
            ");
            $stmt->execute([$like, $like, $like]);
            $trips = $stmt->fetchAll();
            foreach ($trips as $trip) {
                $results[] = [
                    'type' => 'trip',
                    'name' => $trip['name'],
                    'sub'  => ($trip['country_name'] ? $trip['country_name'] . ' · ' : '') . $trip['duration'],
                    'url'  => 'detail-trip?trip=' . urlencode($trip['id']),
                ];
            }
            // Search countries (if trips results < 5)
            if (count($results) < 5) {
                $stmtC = $pdo->prepare("SELECT slug, name FROM countries WHERE name LIKE ? LIMIT 4");
                $stmtC->execute([$like]);
                foreach ($stmtC->fetchAll() as $c) {
                    $results[] = [
                        'type' => 'country',
                        'name' => $c['name'],
                        'sub'  => 'Lihat semua trip ke ' . $c['name'],
                        'url'  => 'negara?country=' . urlencode($c['slug']),
                    ];
                }
            }
        } catch (Exception $e) {}
    }
    echo json_encode(array_slice($results, 0, 8));
    exit;
}

// ── Full search results page ──────────────────────────────────
$trips    = [];
$countries = [];

if ($q !== '') {
    $like = '%' . $q . '%';
    try {
        $stmt = $pdo->prepare("
            SELECT t.*, c.name AS country_name, c.flag AS country_flag,
                   c.slug AS country_slug, c.heroImg AS country_img
            FROM trips t
            LEFT JOIN countries c ON c.id = t.country_id
            WHERE t.name LIKE ? OR t.code LIKE ? OR c.name LIKE ? OR t.duration LIKE ?
            ORDER BY c.name ASC, t.name ASC
        ");
        $stmt->execute([$like, $like, $like, $like]);
        $trips = $stmt->fetchAll();
    } catch (Exception $e) { $trips = []; }

    try {
        $stmtC = $pdo->prepare("SELECT * FROM countries WHERE name LIKE ? OR slug LIKE ?");
        $stmtC->execute([$like, $like]);
        $countries = $stmtC->fetchAll();
    } catch (Exception $e) { $countries = []; }
}

$pageTitle = $q ? "Hasil Pencarian: \"" . htmlspecialchars($q) . "\" — Travelica" : "Cari Trip — Travelica";
$extraCSS = '<link rel="stylesheet" href="assets/css/search.css" />';
include 'includes/header.php';
?>

<!-- Search Hero -->
<section class="search-hero">
  <div class="search-hero-bg">
    <img src="<?= htmlspecialchars(get_setting('hero_image', 'assets/images/hero_bg.webp')) ?>"
         alt="Search Background" class="search-hero-img" />
    <div class="search-hero-overlay"></div>
  </div>
  <div class="search-hero-content">
    <p class="search-eyebrow">🔍 Cari Destinasi Impian Anda</p>
    <h1 class="search-title">Temukan Trip Yang Tepat</h1>
    <form class="search-form" action="search" method="GET" id="searchForm">
      <div class="search-bar-wrap">
        <span class="search-bar-icon">
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#9ca3af" stroke-width="2.2">
            <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
          </svg>
        </span>
        <input type="text" name="q" id="srp-input" class="search-bar-input"
               placeholder="Ketik nama negara, paket trip, atau destinasi..."
               value="<?= htmlspecialchars($q) ?>" autocomplete="off" />
        <button type="submit" class="search-bar-btn">Cari Sekarang</button>
      </div>
    </form>
  </div>
</section>

<!-- Results -->
<main class="search-main">
  <div class="main-container">

    <?php if ($q === ''): ?>
    <!-- Empty state - no query -->
    <div class="search-empty">
      <div class="search-empty-icon">✈️</div>
      <h2 class="search-empty-title">Mau liburan ke mana?</h2>
      <p class="search-empty-sub">Ketik nama negara, kota, atau paket trip di kolom pencarian di atas.</p>
      <div class="search-popular">
        <p class="search-popular-label">Destinasi Populer:</p>
        <div class="search-popular-tags">
          <?php
          try {
            $popStmt = $pdo->query("SELECT name, slug FROM countries ORDER BY show_on_home DESC LIMIT 8");
            foreach ($popStmt->fetchAll() as $c):
          ?>
          <a href="negara?country=<?= htmlspecialchars($c['slug']) ?>" class="search-tag">
            <?= htmlspecialchars($c['name']) ?>
          </a>
          <?php endforeach; } catch(Exception $e){} ?>
        </div>
      </div>
    </div>

    <?php elseif (empty($trips) && empty($countries)): ?>
    <!-- No results -->
    <div class="search-empty">
      <div class="search-empty-icon">😔</div>
      <h2 class="search-empty-title">Tidak Ada Hasil untuk "<?= htmlspecialchars($q) ?>"</h2>
      <p class="search-empty-sub">Coba gunakan kata kunci lain atau lihat semua destinasi kami.</p>
      <a href="destinasi" class="search-all-btn">Lihat Semua Destinasi</a>
    </div>

    <?php else: ?>
    <!-- Results found -->
    <div class="search-results-header">
      <p class="search-results-count">
        Ditemukan <strong><?= count($trips) + count($countries) ?> hasil</strong>
        untuk "<em><?= htmlspecialchars($q) ?></em>"
      </p>
    </div>

    <?php if (!empty($trips)): ?>
    <section class="search-section">
      <h2 class="search-section-title">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
        </svg>
        Paket Trip (<?= count($trips) ?>)
      </h2>
      <div class="search-trips-grid">
        <?php foreach ($trips as $trip): ?>
        <a href="detail-trip?trip=<?= urlencode($trip['id']) ?>" class="search-trip-card">
          <div class="stc-img-wrap">
            <?php if (!empty($trip['country_img'])): ?>
            <img src="<?= htmlspecialchars($trip['country_img']) ?>"
                 alt="<?= htmlspecialchars($trip['name']) ?>" class="stc-img" loading="lazy"
                 onerror="this.src='assets/images/hero_bg.webp'" />
            <?php else: ?>
            <div class="stc-img-placeholder">✈</div>
            <?php endif; ?>
            <div class="stc-overlay">
              <span class="stc-code"><?= htmlspecialchars($trip['code']) ?></span>
            </div>
          </div>
          <div class="stc-body">
            <div class="stc-country">
              <?php if (!empty($trip['country_flag'])): ?>
              <?= render_flag($trip['country_flag']) ?>
              <?php endif; ?>
              <span><?= htmlspecialchars($trip['country_name'] ?? '') ?></span>
            </div>
            <h3 class="stc-name"><?= htmlspecialchars($trip['name']) ?></h3>
            <div class="stc-meta">
              <span class="stc-meta-item">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                <?= htmlspecialchars($trip['duration']) ?>
              </span>
              <span class="stc-meta-item">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="4" width="18" height="18" rx="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>
                <?= htmlspecialchars($trip['dateRange'] ?? $trip['dateStart'] ?? '–') ?>
              </span>
            </div>
            <div class="stc-footer">
              <span class="stc-price">Rp <?= number_format($trip['price'], 0, ',', '.') ?><span class="stc-price-per">/pax</span></span>
              <span class="stc-cta">Lihat Detail →</span>
            </div>
          </div>
        </a>
        <?php endforeach; ?>
      </div>
    </section>
    <?php endif; ?>

    <?php if (!empty($countries)): ?>
    <section class="search-section">
      <h2 class="search-section-title">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/>
          <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
        </svg>
        Destinasi (<?= count($countries) ?>)
      </h2>
      <div class="search-countries-grid">
        <?php foreach ($countries as $c): ?>
        <a href="negara?country=<?= urlencode($c['slug']) ?>" class="search-country-card">
          <div class="scc-img-wrap">
            <img src="<?= htmlspecialchars($c['heroImg']) ?>" alt="<?= htmlspecialchars($c['name']) ?>"
                 class="scc-img" loading="lazy" onerror="this.src='assets/images/hero_bg.webp'" />
            <div class="scc-overlay"></div>
          </div>
          <div class="scc-info">
            <span class="scc-flag"><?= render_flag($c['flag']) ?></span>
            <span class="scc-name"><?= htmlspecialchars($c['name']) ?></span>
          </div>
        </a>
        <?php endforeach; ?>
      </div>
    </section>
    <?php endif; ?>

    <?php endif; ?>

  </div>
</main>

<script src="assets/js/main.js"></script>
<?php include 'includes/footer.php'; ?>
