<?php
require_once '_auth.php';
adm_require_login();
require_once '_layout.php';

$filterCountry = $_GET['country'] ?? '';

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['_action'] ?? '') === 'delete') {
    $id = trim($_POST['id']);
    $pdo->prepare("DELETE FROM trips WHERE id = ?")->execute([$id]);
    $_SESSION['adm_toast'] = ['msg' => 'Paket trip berhasil dihapus.', 'type' => 'success'];
    header('Location: trips.php' . ($filterCountry ? '?country=' . urlencode($filterCountry) : ''));
    exit;
}

// Handle duplicate
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['_action'] ?? '') === 'duplicate') {
    $id = trim($_POST['id']);
    $stmtSrc = $pdo->prepare("SELECT * FROM trips WHERE id = ?");
    $stmtSrc->execute([$id]);
    $t = $stmtSrc->fetch();

    if ($t) {
        $baseSlug = preg_replace('/[^a-z0-9]+/i', '-', strtolower($t['name']));
        $newId = trim($baseSlug, '-') . '-copy-' . rand(100, 999);
        $finalName = $t['name'] . ' (Salinan)';
        $finalCode = $t['code'] . '-COPY';

        $stmtIns = $pdo->prepare("INSERT INTO trips 
            (id, country_id, code, name, duration, durationShort, dateRange, dateStart, dateEnd, minPax, dp_info, dp_label, price, includes, excludes, itinerary)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        
        $stmtIns->execute([
            $newId,
            $t['country_id'],
            $finalCode,
            $finalName,
            $t['duration'],
            $t['durationShort'],
            $t['dateRange'],
            $t['dateStart'],
            $t['dateEnd'],
            $t['minPax'],
            $t['dp_info'],
            $t['dp_label'],
            $t['price'],
            $t['includes'],
            $t['excludes'],
            $t['itinerary']
        ]);

        $_SESSION['adm_toast'] = ['msg' => 'Paket trip "' . htmlspecialchars($finalName) . '" berhasil diduplikasi!', 'type' => 'success'];
        header('Location: trips.php' . ($filterCountry ? '?country=' . urlencode($filterCountry) : ''));
        exit;
    }
}

// Fetch countries for filter
$countries = $pdo->query("SELECT id, name, flag, slug FROM countries ORDER BY name")->fetchAll();

// Fetch trips
$sql = "SELECT t.*, c.name AS country_name, c.flag, c.slug AS country_slug
        FROM trips t LEFT JOIN countries c ON t.country_id = c.id";
$params = [];
if ($filterCountry) {
    $sql .= " WHERE c.slug = ?";
    $params[] = $filterCountry;
}
$sql .= " ORDER BY c.name, t.dateStart";
$trips = $pdo->prepare($sql);
$trips->execute($params);
$trips = $trips->fetchAll();

adm_layout_start('trips', 'Step 2: Manajemen Paket Trip');
?>

<!-- Stepper Bar -->
<div class="adm-stepper">
  <a href="destinasi.php" class="adm-step-item">
    <span class="adm-step-num">1</span>
    <span>Destinasi (Negara)</span>
  </a>
  <span class="adm-step-arrow">→</span>
  <div class="adm-step-item active">
    <span class="adm-step-num">2</span>
    <span>Paket Trip</span>
  </div>
  <span class="adm-step-arrow">→</span>
  <a href="itinerary.php" class="adm-step-item">
    <span class="adm-step-num">3</span>
    <span>Detail &amp; Itinerary</span>
  </a>
</div>

<div class="adm-page-header">
  <div>
    <h1 class="adm-page-title">Step 2: Paket Trip (Jadwal Destinasi)</h1>
    <p class="adm-page-sub"><?= count($trips) ?> paket trip ditemukan. Atur daftar jadwal perjalanan untuk setiap destinasi.</p>
  </div>
  <div style="display:flex;gap:10px;">
    <a href="trip-form.php" class="btn btn-primary">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
      + Tambah Paket Trip
    </a>
    <a href="itinerary.php" class="btn btn-outline">
      Lanjut ke Step 3 (Detail &amp; Itinerary) →
    </a>
  </div>
</div>

<!-- Filter -->
<div class="adm-filters" style="margin-bottom:20px;">
  <div class="adm-search">
    <span class="adm-search-icon">
      <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
    </span>
    <input type="text" id="trip-search" placeholder="Cari trip..." oninput="filterTrips()" />
  </div>
  <form method="GET" style="display:flex;gap:8px;align-items:center;">
    <select name="country" class="adm-form-select" onchange="this.form.submit()" style="min-width:160px;">
      <option value="">Semua Destinasi</option>
      <?php foreach ($countries as $c): ?>
      <option value="<?= htmlspecialchars($c['slug']) ?>" <?= $filterCountry === $c['slug'] ? 'selected' : '' ?>>
        <?= htmlspecialchars($c['name']) ?>
      </option>
      <?php endforeach; ?>
    </select>
  </form>
</div>

<!-- Table -->
<div class="adm-card">
  <div class="adm-table-wrap">
    <table class="adm-table" id="trips-table">
      <thead>
        <tr>
          <th>Destinasi</th>
          <th>Nama Trip</th>
          <th>Kode</th>
          <th>Tanggal</th>
          <th>Durasi</th>
          <th>DP / Ketentuan</th>
          <th>Harga</th>
          <th>Step 3: Itinerary</th>
          <th>Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($trips as $t): ?>
        <tr class="trip-row">
          <td>
            <span style="margin-right:6px;"><?= render_flag($t['flag']) ?></span>
            <?= htmlspecialchars($t['country_name']) ?>
          </td>
          <td><strong><?= htmlspecialchars($t['name']) ?></strong></td>
          <td><span class="adm-badge adm-badge-blue"><?= htmlspecialchars($t['code']) ?></span></td>
          <td style="white-space:nowrap;"><?= htmlspecialchars($t['dateRange']) ?></td>
          <td><?= htmlspecialchars($t['duration']) ?></td>
          <td><span style="font-weight:600;color:#0284c7;"><?= htmlspecialchars($t['dp_info'] ?: ($t['minPax'] ? $t['minPax'] . ' pax' : '–')) ?></span></td>
          <td style="white-space:nowrap;">Rp <?= number_format($t['price'], 0, ',', '.') ?></td>
          <td>
            <a href="itinerary.php?trip_id=<?= urlencode($t['id']) ?>" class="btn btn-outline btn-sm" style="font-size:11.5px;padding:4px 10px;" title="Atur Includes, Excludes & Itinerary">
              🗓️ Atur Detail (Step 3)
            </a>
          </td>
          <td style="display:flex;gap:6px;align-items:center;white-space:nowrap;">
            <a href="trip-form.php?id=<?= urlencode($t['id']) ?>" class="btn-icon" title="Edit Info Dasar">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
            </a>
            <button type="button" class="btn-icon dup-trip-btn"
              data-id="<?= htmlspecialchars($t['id'], ENT_QUOTES) ?>"
              data-name="<?= htmlspecialchars($t['name'], ENT_QUOTES) ?>"
              title="Duplikat Trip">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
            </button>
            <a href="../detail-trip?trip=<?= urlencode($t['id']) ?>" target="_blank" class="btn-icon" title="Lihat di Website">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
            </a>
            <button type="button" class="btn-icon danger del-trip-btn"
              data-id="<?= htmlspecialchars($t['id'], ENT_QUOTES) ?>"
              data-name="<?= htmlspecialchars($t['name'], ENT_QUOTES) ?>"
              title="Hapus">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><path d="M10 11v6"/><path d="M14 11v6"/><path d="M9 6V4h6v2"/></svg>
            </button>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($trips)): ?>
        <tr><td colspan="8">
          <div class="adm-empty">
            <div class="adm-empty-icon">✈️</div>
            <h3>Belum ada paket trip</h3>
            <p>Klik "Tambah Trip" untuk membuat paket baru.</p>
          </div>
        </td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<script>
function filterTrips() {
  var q = document.getElementById('trip-search').value.toLowerCase();
  document.querySelectorAll('.trip-row').forEach(function(row) {
    row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
  });
}

document.addEventListener('DOMContentLoaded', function() {
  // Duplicate trip
  document.querySelectorAll('.dup-trip-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var id   = this.dataset.id;
      var name = this.dataset.name;
      if (confirm('Duplikat trip "' + name + '" beserta seluruh detail fasilitas & itinerary-nya?')) {
        var f = document.createElement('form');
        f.method = 'POST';
        f.innerHTML = '<input name="_action" value="duplicate"><input name="id" value="' + id + '">';
        document.body.appendChild(f);
        f.submit();
      }
    });
  });

  // Delete trip
  document.querySelectorAll('.del-trip-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var id   = this.dataset.id;
      var name = this.dataset.name;
      confirmDelete('Hapus trip "' + name + '"?', function() {
        var f = document.createElement('form');
        f.method = 'POST';
        f.innerHTML = '<input name="_action" value="delete"><input name="id" value="' + id + '">';
        document.body.appendChild(f);
        f.submit();
      });
    });
  });
});
</script>

<?php adm_layout_end(); ?>
