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

$tripId = $_GET['trip_id'] ?? null;
$currentTrip = null;
$errors = [];

// Fetch all trips for selection/listing
$allTrips = $pdo->query(
    "SELECT t.*, c.name AS country_name, c.flag
     FROM trips t
     LEFT JOIN countries c ON t.country_id = c.id
     ORDER BY c.name ASC, t.price ASC"
)->fetchAll();

// If trip selected, load data
if ($tripId) {
    $stmt = $pdo->prepare(
        "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
         WHERE t.id = ?"
    );
    $stmt->execute([$tripId]);
    $currentTrip = $stmt->fetch();
}

/* ── HANDLE POST ──────────────────────────────────────────── */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postAction = $_POST['post_action'] ?? '';

    // ACTION 1: COPY ITINERARY & FACILITIES FROM ONE TRIP TO ANOTHER
    if ($postAction === 'copy_itinerary') {
        $sourceId = trim($_POST['source_trip_id'] ?? '');
        $targetId = trim($_POST['target_trip_id'] ?? '');
        $copyIncludes  = !empty($_POST['copy_includes']);
        $copyExcludes  = !empty($_POST['copy_excludes']);
        $copyItinerary = !empty($_POST['copy_itinerary']);
        $redirectTarget = !empty($_POST['redirect_target']);

        if (!$sourceId || !$targetId) {
            $_SESSION['adm_toast'] = ['msg' => 'Trip asal dan trip tujuan harus dipilih.', 'type' => 'error'];
            header('Location: itinerary.php');
            exit;
        }

        if ($sourceId === $targetId) {
            $_SESSION['adm_toast'] = ['msg' => 'Trip sumber dan trip tujuan tidak boleh sama.', 'type' => 'error'];
            header('Location: itinerary.php');
            exit;
        }

        // Fetch source trip
        $stmtSrc = $pdo->prepare("SELECT * FROM trips WHERE id = ?");
        $stmtSrc->execute([$sourceId]);
        $sourceTrip = $stmtSrc->fetch();

        // Fetch target trip
        $stmtTgt = $pdo->prepare("SELECT * FROM trips WHERE id = ?");
        $stmtTgt->execute([$targetId]);
        $targetTrip = $stmtTgt->fetch();

        if (!$sourceTrip || !$targetTrip) {
            $_SESSION['adm_toast'] = ['msg' => 'Paket trip tidak ditemukan.', 'type' => 'error'];
            header('Location: itinerary.php');
            exit;
        }

        $updateFields = [];
        $updateValues = [];

        if ($copyIncludes) {
            $updateFields[] = "includes = ?";
            $updateValues[] = $sourceTrip['includes'];
        }
        if ($copyExcludes) {
            $updateFields[] = "excludes = ?";
            $updateValues[] = $sourceTrip['excludes'];
        }
        if ($copyItinerary) {
            $updateFields[] = "itinerary = ?";
            $updateValues[] = $sourceTrip['itinerary'];
        }

        if (empty($updateFields)) {
            $_SESSION['adm_toast'] = ['msg' => 'Pilih minimal satu bagian yang ingin disalin (Includes, Excludes, atau Itinerary).', 'type' => 'error'];
            header('Location: itinerary.php');
            exit;
        }

        $updateValues[] = $targetId;
        $sql = "UPDATE trips SET " . implode(", ", $updateFields) . " WHERE id = ?";
        $pdo->prepare($sql)->execute($updateValues);

        $_SESSION['adm_toast'] = [
            'msg' => 'Berhasil menyalin data dari "' . htmlspecialchars($sourceTrip['name']) . '" ke "' . htmlspecialchars($targetTrip['name']) . '"!',
            'type' => 'success'
        ];

        if ($redirectTarget) {
            header('Location: itinerary.php?trip_id=' . urlencode($targetId));
        } else {
            header('Location: itinerary.php');
        }
        exit;
    }

    // ACTION 2: DUPLICATE FULL TRIP PACKAGE
    elseif ($postAction === 'duplicate_trip_full') {
        $sourceId = trim($_POST['source_trip_id'] ?? '');
        $newName  = trim($_POST['new_name'] ?? '');
        $newCode  = trim($_POST['new_code'] ?? '');

        $stmtSrc = $pdo->prepare("SELECT * FROM trips WHERE id = ?");
        $stmtSrc->execute([$sourceId]);
        $sourceTrip = $stmtSrc->fetch();

        if ($sourceTrip) {
            $baseSlug = preg_replace('/[^a-z0-9]+/i', '-', strtolower($newName ?: $sourceTrip['name']));
            $newId = trim($baseSlug, '-') . '-copy-' . rand(100, 999);
            $finalName = $newName ?: ($sourceTrip['name'] . ' (Salinan)');
            $finalCode = $newCode ?: ($sourceTrip['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,
                $sourceTrip['country_id'],
                $finalCode,
                $finalName,
                $sourceTrip['duration'],
                $sourceTrip['durationShort'],
                $sourceTrip['dateRange'],
                $sourceTrip['dateStart'],
                $sourceTrip['dateEnd'],
                $sourceTrip['minPax'],
                $sourceTrip['dp_info'],
                $sourceTrip['dp_label'],
                $sourceTrip['price'],
                $sourceTrip['includes'],
                $sourceTrip['excludes'],
                $sourceTrip['itinerary']
            ]);

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

    // ACTION 3: REGULAR SAVE CURRENT TRIP DETAIL & ITINERARY
    elseif ($currentTrip) {
        // Includes / Excludes
        $includes = array_values(array_filter(array_map('trim', $_POST['includes'] ?? []), fn($v) => $v !== ''));
        $excludes = array_values(array_filter(array_map('trim', $_POST['excludes'] ?? []), fn($v) => $v !== ''));

        // Itinerary (parallel arrays)
        $itin = [];
        $iDays    = $_POST['itin_day']   ?? [];
        $iTitles  = $_POST['itin_title'] ?? [];
        $iDescs   = $_POST['itin_desc']  ?? [];
        $iOldImgs = $_POST['itin_img_existing'] ?? [];

        foreach ($iDays as $idx => $day) {
            if (trim($iTitles[$idx] ?? '') !== '') {
                $imgUpload = adm_upload_image('itin_img_file_' . $idx, 'itinerary', $iOldImgs[$idx] ?? '');
                $itin[] = [
                    'day'   => (int)$day,
                    'title' => trim($iTitles[$idx]),
                    'desc'  => trim($iDescs[$idx] ?? ''),
                    'img'   => $imgUpload['path'] ?? '',
                ];
            }
        }

        if (empty($itin)) {
            $errors[] = 'Minimal harus ada 1 hari pada itinerary perjalanan.';
        }

        if (empty($errors)) {
            $includesJson  = json_encode($includes, JSON_UNESCAPED_UNICODE);
            $excludesJson  = json_encode($excludes, JSON_UNESCAPED_UNICODE);
            $itineraryJson = json_encode($itin,     JSON_UNESCAPED_UNICODE);

            $pdo->prepare("UPDATE trips SET includes = ?, excludes = ?, itinerary = ? WHERE id = ?")
                ->execute([$includesJson, $excludesJson, $itineraryJson, $tripId]);

            $_SESSION['adm_toast'] = [
                'msg' => 'Detail Fasilitas & Itinerary berhasil disimpan!',
                'type' => 'success'
            ];
            header('Location: itinerary.php?trip_id=' . urlencode($tripId));
            exit;
        }
    }
}

// Parse current trip data
$inclArr = json_decode($currentTrip['includes'] ?? '[]', true) ?: [];
$exclArr = json_decode($currentTrip['excludes'] ?? '[]', true) ?: [];
$itinArr = json_decode($currentTrip['itinerary'] ?? '[]', true) ?: [];
if (empty($itinArr)) $itinArr = [['day'=>1,'title'=>'','desc'=>'','img'=>'']];

adm_layout_start('itinerary', 'Step 3: Detail & Itinerary 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>
  <a href="trips.php" class="adm-step-item">
    <span class="adm-step-num">2</span>
    <span>Paket Trip</span>
  </a>
  <span class="adm-step-arrow">→</span>
  <div class="adm-step-item active">
    <span class="adm-step-num">3</span>
    <span>Detail &amp; Itinerary</span>
  </div>
</div>

<div class="adm-page-header">
  <div>
    <h1 class="adm-page-title">
      Step 3: Detail &amp; Itinerary Trip
    </h1>
    <p class="adm-page-sub">
      Atur rincian fasilitas (Termasuk &amp; Tidak Termasuk) serta jadwal kegiatan harian untuk halaman detail trip.
    </p>
  </div>
  <?php if ($currentTrip): ?>
  <div style="display:flex;gap:10px;">
    <a href="../detail-trip?trip=<?= urlencode($currentTrip['id']) ?>" target="_blank" class="btn btn-outline">
      🔗 Lihat di Website
    </a>
    <a href="itinerary.php" class="btn btn-outline">
      Ganti Trip
    </a>
  </div>
  <?php endif; ?>
</div>

<?php if (!$currentTrip): ?>
<!-- ── TRIP SELECTOR LIST ─────────────────────────────────── -->
<div class="adm-card">
  <div class="adm-card-header" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;">
    <span class="adm-card-title">Pilih Paket Trip yang Ingin Diatur Detail &amp; Itinerary-nya</span>
    <span style="font-size:12.5px;color:#64748b;">
      💡 Tip: Gunakan tombol <b>📋 Salin Itinerary</b> untuk menduplikasi fasilitas &amp; jadwal tanpa ketik ulang.
    </span>
  </div>
  <div class="adm-table-wrap">
    <table class="adm-table">
      <thead>
        <tr>
          <th>Destinasi</th>
          <th>Nama Paket</th>
          <th>Kode</th>
          <th>Durasi</th>
          <th>Total Hari Itinerary</th>
          <th style="min-width:260px;">Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($allTrips as $t): 
          $tItin = json_decode($t['itinerary'] ?? '[]', true) ?: [];
          $tIncl = json_decode($t['includes'] ?? '[]', true) ?: [];
          $tExcl = json_decode($t['excludes'] ?? '[]', true) ?: [];
        ?>
        <tr>
          <td>
            <span style="margin-right:6px;"><?= render_flag($t['flag']) ?></span>
            <strong><?= htmlspecialchars($t['country_name']) ?></strong>
          </td>
          <td><?= htmlspecialchars($t['name']) ?></td>
          <td><span class="adm-badge adm-badge-blue"><?= htmlspecialchars($t['code']) ?></span></td>
          <td><?= htmlspecialchars($t['duration']) ?></td>
          <td>
            <span class="adm-badge <?= count($tItin) > 0 ? 'adm-badge-green' : '' ?>">
              <?= count($tItin) ?> Hari
            </span>
          </td>
          <td>
            <div style="display:flex;gap:6px;align-items:center;flex-wrap:wrap;">
              <a href="itinerary.php?trip_id=<?= urlencode($t['id']) ?>" class="btn btn-primary btn-sm" style="display:inline-flex;align-items:center;gap:4px;">
                🗓️ Atur Detail
              </a>
              <button type="button" class="btn btn-outline btn-sm" 
                      style="display:inline-flex;align-items:center;gap:4px;color:#0284c7;border-color:#bae6fd;background:#f0f9ff;"
                      onclick="openCopyModal(<?= htmlspecialchars(json_encode([
                        'id' => $t['id'],
                        'name' => $t['name'],
                        'code' => $t['code'],
                        'country' => $t['country_name'],
                        'flag' => $t['flag'],
                        'itinCount' => count($tItin),
                        'inclCount' => count($tIncl),
                        'exclCount' => count($tExcl),
                      ])) ?>)"
                      title="Salin fasilitas & itinerary trip ini ke trip lain">
                📋 Salin Itinerary
              </button>
              <button type="button" class="btn btn-outline btn-sm" 
                      style="display:inline-flex;align-items:center;gap:4px;"
                      onclick="openCloneModal(<?= htmlspecialchars(json_encode([
                        'id' => $t['id'],
                        'name' => $t['name'],
                        'code' => $t['code']
                      ])) ?>)"
                      title="Duplikat paket trip ini menjadi trip baru">
                📑 Duplikat Trip
              </button>
            </div>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php if (empty($allTrips)): ?>
        <tr><td colspan="6" style="text-align:center;padding:32px;color:#94a3b8;">Belum ada trip. Buat trip di Step 2 terlebih dahulu.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- MODAL: Salin / Duplikat Itinerary ke Trip Lain -->
<div id="copyItineraryModal" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(15,23,42,0.6);backdrop-filter:blur(4px);z-index:9999;align-items:center;justify-content:center;padding:20px;overflow-y:auto;">
  <div style="background:#ffffff;border-radius:16px;max-width:540px;width:100%;box-shadow:0 24px 60px rgba(0,0,0,0.25);border:1px solid #e2e8f0;overflow:hidden;position:relative;">
    
    <div style="padding:18px 24px;border-bottom:1.5px solid #f1f5f9;display:flex;align-items:center;justify-content:space-between;">
      <h3 style="font-size:17px;font-weight:700;color:#0f172a;margin:0;display:flex;align-items:center;gap:8px;">
        <span>📋</span> Salin Fasilitas &amp; Itinerary Trip
      </h3>
      <button type="button" onclick="closeCopyModal()" style="background:none;border:none;font-size:22px;color:#94a3b8;cursor:pointer;line-height:1;">&times;</button>
    </div>

    <div style="padding:24px;">
      <form method="POST">
        <input type="hidden" name="post_action" value="copy_itinerary" />
        <input type="hidden" id="copy_source_id" name="source_trip_id" value="" />

        <!-- Source Trip Box -->
        <div style="background:#eff6ff;border:1.5px solid #bfdbfe;border-radius:10px;padding:14px 16px;margin-bottom:18px;">
          <div style="font-size:11.5px;font-weight:700;color:#1d4ed8;text-transform:uppercase;letter-spacing:0.5px;margin-bottom:3px;">
            Trip Sumber (Yang Disalin):
          </div>
          <div id="copy_source_name" style="font-size:15px;font-weight:800;color:#0f172a;"></div>
          <div id="copy_source_stats" style="font-size:12.5px;color:#475569;margin-top:4px;"></div>
        </div>

        <!-- Target Trip Select -->
        <div class="adm-form-group" style="margin-bottom:18px;">
          <label class="adm-form-label" for="copy_target_id">Pilih Trip Tujuan (Penerima Salinan) *</label>
          <select id="copy_target_id" name="target_trip_id" class="adm-form-select" required style="font-size:13.5px;padding:9px 12px;">
            <option value="">-- Pilih Trip Penerima Salinan --</option>
            <?php foreach ($allTrips as $tgt): ?>
              <?php 
                $tgtDays = count(json_decode($tgt['itinerary'] ?? '[]', true) ?: []);
              ?>
              <option value="<?= htmlspecialchars($tgt['id']) ?>" id="opt-target-<?= htmlspecialchars($tgt['id']) ?>">
                <?= htmlspecialchars($tgt['country_name']) ?> — <?= htmlspecialchars($tgt['name']) ?> (<?= htmlspecialchars($tgt['code']) ?>) [<?= $tgtDays ?> Hari]
              </option>
            <?php endforeach; ?>
          </select>
          <span class="adm-form-hint">Fasilitas dan itinerary pada trip tujuan akan diperbarui sesuai pilihan di bawah.</span>
        </div>

        <!-- Options Checkboxes -->
        <div class="adm-form-group" style="margin-bottom:20px;background:#f8fafc;padding:14px;border-radius:10px;border:1px solid #e2e8f0;">
          <div style="font-size:12.5px;font-weight:700;color:#334155;margin-bottom:10px;">Bagian yang Ingin Disalin:</div>
          <div style="display:flex;flex-direction:column;gap:8px;">
            <label style="display:flex;align-items:center;gap:10px;font-size:13px;color:#1e293b;cursor:pointer;">
              <input type="checkbox" name="copy_includes" value="1" checked style="width:16px;height:16px;accent-color:#1a73e8;" />
              <span>✓ <b>Fasilitas Termasuk</b> (Includes)</span>
            </label>
            <label style="display:flex;align-items:center;gap:10px;font-size:13px;color:#1e293b;cursor:pointer;">
              <input type="checkbox" name="copy_excludes" value="1" checked style="width:16px;height:16px;accent-color:#1a73e8;" />
              <span>✗ <b>Fasilitas Tidak Termasuk</b> (Excludes)</span>
            </label>
            <label style="display:flex;align-items:center;gap:10px;font-size:13px;color:#1e293b;cursor:pointer;">
              <input type="checkbox" name="copy_itinerary" value="1" checked style="width:16px;height:16px;accent-color:#1a73e8;" />
              <span>🗓️ <b>Jadwal Kegiatan Harian</b> (Itinerary Timeline &amp; Foto)</span>
            </label>
          </div>
        </div>

        <!-- Redirect Checkbox -->
        <div class="adm-form-group" style="margin-bottom:24px;">
          <label style="display:flex;align-items:center;gap:10px;font-size:13px;color:#1e293b;cursor:pointer;">
            <input type="checkbox" name="redirect_target" value="1" checked style="width:16px;height:16px;accent-color:#10b981;" />
            <span>Langsung buka halaman editor trip tujuan setelah berhasil disalin</span>
          </label>
        </div>

        <div style="display:flex;align-items:center;justify-content:flex-end;gap:10px;border-top:1.5px solid #f1f5f9;padding-top:16px;">
          <button type="button" class="btn btn-outline" onclick="closeCopyModal()">Batal</button>
          <button type="submit" class="btn btn-primary" style="display:inline-flex;align-items:center;gap:6px;">
            <span>📋</span> Salin Sekarang ➔
          </button>
        </div>

      </form>
    </div>

  </div>
</div>

<!-- MODAL: Duplikat Trip Menjadi Paket Baru -->
<div id="cloneTripModal" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(15,23,42,0.6);backdrop-filter:blur(4px);z-index:9999;align-items:center;justify-content:center;padding:20px;overflow-y:auto;">
  <div style="background:#ffffff;border-radius:16px;max-width:500px;width:100%;box-shadow:0 24px 60px rgba(0,0,0,0.25);border:1px solid #e2e8f0;overflow:hidden;position:relative;">
    
    <div style="padding:18px 24px;border-bottom:1.5px solid #f1f5f9;display:flex;align-items:center;justify-content:space-between;">
      <h3 style="font-size:17px;font-weight:700;color:#0f172a;margin:0;display:flex;align-items:center;gap:8px;">
        <span>📑</span> Duplikat Paket Trip
      </h3>
      <button type="button" onclick="closeCloneModal()" style="background:none;border:none;font-size:22px;color:#94a3b8;cursor:pointer;line-height:1;">&times;</button>
    </div>

    <div style="padding:24px;">
      <form method="POST">
        <input type="hidden" name="post_action" value="duplicate_trip_full" />
        <input type="hidden" id="clone_source_id" name="source_trip_id" value="" />

        <p style="font-size:13.5px;color:#475569;margin-bottom:16px;">
          Seluruh informasi dasar, harga, fasilitas termasuk/tidak termasuk, serta jadwal itinerary akan diduplikasi ke paket trip baru.
        </p>

        <div class="adm-form-group" style="margin-bottom:16px;">
          <label class="adm-form-label" for="clone_name">Nama Paket Trip Baru *</label>
          <input type="text" id="clone_name" name="new_name" class="adm-form-input" required />
        </div>

        <div class="adm-form-group" style="margin-bottom:24px;">
          <label class="adm-form-label" for="clone_code">Kode Trip Baru *</label>
          <input type="text" id="clone_code" name="new_code" class="adm-form-input" required />
        </div>

        <div style="display:flex;align-items:center;justify-content:flex-end;gap:10px;border-top:1.5px solid #f1f5f9;padding-top:16px;">
          <button type="button" class="btn btn-outline" onclick="closeCloneModal()">Batal</button>
          <button type="submit" class="btn btn-primary" style="display:inline-flex;align-items:center;gap:6px;">
            <span>📑</span> Duplikat Sekarang ➔
          </button>
        </div>

      </form>
    </div>

  </div>
</div>

<?php else: ?>

<!-- ── DETAIL & ITINERARY FORM ────────────────────────────── -->
<?php if ($errors): ?>
<div class="adm-error-msg" style="margin-bottom:20px;"><?= implode('<br>', array_map('htmlspecialchars', $errors)) ?></div>
<?php endif; ?>

<!-- Selected Trip Banner -->
<div style="background:#eff6ff;border:1.5px solid #bfdbfe;border-radius:10px;padding:16px 20px;margin-bottom:20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;">
  <div>
    <div style="font-size:12px;font-weight:700;color:#1d4ed8;letter-spacing:1px;text-transform:uppercase;">Paket Trip Aktif:</div>
    <div style="font-size:18px;font-weight:800;color:#1e293b;margin-top:2px;">
      <?= render_flag($currentTrip['flag']) ?> <?= htmlspecialchars($currentTrip['name']) ?> (<?= htmlspecialchars($currentTrip['code']) ?>)
    </div>
    <div style="font-size:12.5px;color:#64748b;margin-top:2px;">
      Destinasi: <strong><?= htmlspecialchars($currentTrip['country_name']) ?></strong> | Durasi: <strong><?= htmlspecialchars($currentTrip['duration']) ?></strong> | Harga: <strong>Rp <?= number_format($currentTrip['price'], 0, ',', '.') ?></strong>
    </div>
  </div>
  <a href="trip-form.php?id=<?= urlencode($currentTrip['id']) ?>" class="btn btn-outline btn-sm">
    ✏️ Edit Info Dasar (Step 2)
  </a>
</div>

<form method="POST" enctype="multipart/form-data" class="adm-form">

  <!-- Quick Import / Copy From Another Trip Bar -->
  <div style="background:#f0fdf4;border:1.5px solid #bbf7d0;border-radius:12px;padding:14px 18px;margin-bottom:20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;">
    <div>
      <div style="font-weight:700;color:#166534;font-size:13.5px;display:flex;align-items:center;gap:6px;">
        <span>📥</span> Salin Cepat Fasilitas &amp; Itinerary dari Paket Trip Lain
      </div>
      <div style="font-size:12.5px;color:#15803d;margin-top:2px;">
        Isi otomatis fasilitas (Includes/Excludes) dan seluruh jadwal itinerary dari paket trip lain tanpa perlu mengetik ulang.
      </div>
    </div>
    <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
      <select id="quickCopySelect" class="adm-form-select" style="min-width:260px;font-size:13px;padding:7px 10px;">
        <option value="">-- Pilih Trip Sumber Referensi --</option>
        <?php foreach ($allTrips as $src): ?>
          <?php if ($src['id'] !== $currentTrip['id']): ?>
            <?php 
              $sDays = count(json_decode($src['itinerary'] ?? '[]', true) ?: []);
            ?>
            <option value="<?= htmlspecialchars($src['id']) ?>">
              <?= htmlspecialchars($src['country_name']) ?> — <?= htmlspecialchars($src['name']) ?> (<?= htmlspecialchars($src['code']) ?>) [<?= $sDays ?> Hari]
            </option>
          <?php endif; ?>
        <?php endforeach; ?>
      </select>
      <button type="button" class="btn btn-primary btn-sm" onclick="applyQuickCopy()" style="background:#16a34a;border-color:#16a34a;display:inline-flex;align-items:center;gap:4px;">
        <span>Terapkan ke Form ➔</span>
      </button>
    </div>
  </div>

  <!-- Section: Includes & Excludes -->
  <div class="adm-card">
    <div class="adm-card-header">
      <span class="adm-card-title">✅ Fasilitas: Yang Termasuk &amp; Tidak Termasuk</span>
    </div>
    <div class="adm-card-body">
      <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;">

        <!-- Includes -->
        <div>
          <div class="adm-form-label" style="margin-bottom:10px;color:#10b981;font-weight:700;">✓ Yang Termasuk (Includes)</div>
          <div class="adm-dyn-list" id="includes-list">
            <?php foreach ($inclArr as $item): ?>
            <div class="adm-dyn-item">
              <input type="text" name="includes[]" class="adm-form-input" value="<?= htmlspecialchars($item) ?>" placeholder="cth: Hotel ★4" />
              <button type="button" class="btn-icon danger" onclick="removeItem(this)" title="Hapus">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
              </button>
            </div>
            <?php endforeach; ?>
            <?php if (empty($inclArr)): ?>
            <div class="adm-dyn-item">
              <input type="text" name="includes[]" class="adm-form-input" placeholder="cth: Hotel ★4" />
              <button type="button" class="btn-icon danger" onclick="removeItem(this)">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
              </button>
            </div>
            <?php endif; ?>
          </div>
          <button type="button" class="btn btn-outline btn-sm adm-add-row" onclick="addItem('includes-list','includes[]','cth: Tour Leader')">
            + Tambah Fasilitas Termasuk
          </button>
        </div>

        <!-- Excludes -->
        <div>
          <div class="adm-form-label" style="margin-bottom:10px;color:#94a3b8;font-weight:700;">✗ Tidak Termasuk (Excludes)</div>
          <div class="adm-dyn-list" id="excludes-list">
            <?php foreach ($exclArr as $item): ?>
            <div class="adm-dyn-item">
              <input type="text" name="excludes[]" class="adm-form-input" value="<?= htmlspecialchars($item) ?>" placeholder="cth: Tiket Pesawat Internasional" />
              <button type="button" class="btn-icon danger" onclick="removeItem(this)">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
              </button>
            </div>
            <?php endforeach; ?>
            <?php if (empty($exclArr)): ?>
            <div class="adm-dyn-item">
              <input type="text" name="excludes[]" class="adm-form-input" placeholder="cth: Tiket Pesawat" />
              <button type="button" class="btn-icon danger" onclick="removeItem(this)">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
              </button>
            </div>
            <?php endif; ?>
          </div>
          <button type="button" class="btn btn-outline btn-sm adm-add-row" onclick="addItem('excludes-list','excludes[]','cth: Visa & Insurance')">
            + Tambah Fasilitas Tidak Termasuk
          </button>
        </div>

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

  <!-- Section: Itinerary Builder -->
  <div class="adm-card">
    <div class="adm-card-header">
      <span class="adm-card-title">🗓️ Jadwal Kegiatan Harian (Itinerary Timeline)</span>
      <button type="button" class="btn btn-outline btn-sm" onclick="addItinDay()">+ Tambah Hari</button>
    </div>
    <div class="adm-card-body">
      <div class="adm-itin-list" id="itin-list">
        <?php foreach ($itinArr as $idx => $day): ?>
        <div class="adm-itin-item" data-idx="<?= $idx ?>">
          <div class="adm-itin-header" onclick="toggleItin(this)">
            <div style="display:flex;align-items:center;">
              <span class="adm-itin-day-label">HARI <?= (int)$day['day'] ?></span>
              <span class="adm-itin-day-title" id="itin-title-display-<?= $idx ?>"><?= !empty($day['title']) ? ' — ' . htmlspecialchars($day['title']) : '' ?></span>
            </div>
            <div style="display:flex;gap:6px;align-items:center;">
              <button type="button" class="btn-icon btn-sm" onclick="event.stopPropagation();duplicateItinDay(this)" title="Duplikat Hari Ini" style="color:#0284c7;background:#e0f2fe;">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.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>
              <button type="button" class="btn-icon danger btn-sm" onclick="event.stopPropagation();removeItin(this)" title="Hapus Hari">
                <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
              </button>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="itin-chevron"><polyline points="6 9 12 15 18 9"/></svg>
            </div>
          </div>
          <div class="adm-itin-body">
            <input type="hidden" name="itin_day[]" value="<?= (int)$day['day'] ?>" class="itin-day-val" />
            <div class="adm-form-group">
              <label class="adm-form-label">Judul Aktivitas Hari Ini *</label>
              <input type="text" name="itin_title[]" class="adm-form-input itin-title-inp"
                     placeholder="Contoh: ARRIVAL TOKYO / CITY TOUR"
                     value="<?= htmlspecialchars($day['title']) ?>"
                     oninput="updateItinTitle(this)" required />
            </div>
            <div class="adm-form-group">
              <label class="adm-form-label">Rincian Kegiatan</label>
              <textarea name="itin_desc[]" class="adm-form-textarea"
                        placeholder="Deskripsi kegiatan, rute kunjungan, tempat makan, dll..."><?= htmlspecialchars($day['desc']) ?></textarea>
            </div>
            <div class="adm-form-group">
              <label class="adm-form-label">Foto Kegiatan Hari Ini (opsional)</label>
              <?php if(!empty($day['img'])): 
                $prevImg = str_starts_with($day['img'],'http') ? $day['img'] : '../' . $day['img'];
              ?>
              <img class="adm-itin-preview show" id="itin-prev-<?= $idx ?>" src="<?= htmlspecialchars($prevImg) ?>" alt="" />
              <?php else: ?>
              <img class="adm-itin-preview" id="itin-prev-<?= $idx ?>" src="" alt="" />
              <?php endif; ?>
              <input type="hidden" name="itin_img_existing[]" value="<?= htmlspecialchars($day['img'] ?? '') ?>" />
              <label class="adm-upload-label" for="itin-file-<?= $idx ?>">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>
                <span id="itin-lbl-<?= $idx ?>"><?= !empty($day['img']) ? 'Ganti Foto' : 'Upload Foto Kegiatan' ?></span>
                <input type="file" id="itin-file-<?= $idx ?>" name="itin_img_file_<?= $idx ?>" accept="image/jpeg,image/png,image/webp"
                  onchange="previewUpload(this,'itin-prev-<?= $idx ?>','itin-lbl-<?= $idx ?>')" />
              </label>
              <span class="adm-form-hint" style="color:#0284c7;font-weight:600;">
                📐 Rasio Aspek: 4:3 atau 16:9 (Landscape). Rekomendasi: 800×600 px atau 1200×800 px. Format: JPG, PNG, WebP (Maks 5 MB).
              </span>
            </div>
          </div>
        </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

  <!-- Submit Buttons -->
  <div style="display:flex;gap:12px;padding-bottom:32px;align-items:center;">
    <button type="submit" class="btn btn-primary" style="padding:13px 28px;font-size:14px;">
      💾 Simpan Detail &amp; Itinerary
    </button>
    <a href="../detail-trip?trip=<?= urlencode($currentTrip['id']) ?>" target="_blank" class="btn btn-outline" style="margin-left:auto;">
      👁️ Lihat di Website
    </a>
  </div>

</form>

<?php endif; ?>

<script>
// Pre-bundled trips data for client-side quick copy
var allTripsData = <?= json_encode(array_map(function($t) {
    return [
        'id' => $t['id'],
        'name' => $t['name'],
        'code' => $t['code'],
        'includes' => json_decode($t['includes'] ?? '[]', true) ?: [],
        'excludes' => json_decode($t['excludes'] ?? '[]', true) ?: [],
        'itinerary' => json_decode($t['itinerary'] ?? '[]', true) ?: [],
    ];
}, $allTrips), JSON_UNESCAPED_UNICODE) ?>;

function escapeHtml(str) {
  if (!str) return '';
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

// Modal: Copy Itinerary to Another Trip
function openCopyModal(trip) {
  document.getElementById('copy_source_id').value = trip.id;
  document.getElementById('copy_source_name').innerHTML = (trip.flag ? trip.flag + ' ' : '') + escapeHtml(trip.name) + ' <span class="adm-badge adm-badge-blue" style="font-size:11px;margin-left:6px;">' + escapeHtml(trip.code) + '</span>';
  document.getElementById('copy_source_stats').textContent = trip.country + ' • ' + trip.inclCount + ' Fasilitas Termasuk • ' + trip.exclCount + ' Tidak Termasuk • ' + trip.itinCount + ' Hari Itinerary';

  // Disable/hide source trip in target select
  var sel = document.getElementById('copy_target_id');
  if (sel) {
    for (var i = 0; i < sel.options.length; i++) {
      var opt = sel.options[i];
      if (opt.value === trip.id) {
        opt.disabled = true;
        opt.style.display = 'none';
      } else {
        opt.disabled = false;
        opt.style.display = '';
      }
    }
    sel.value = '';
  }

  var modal = document.getElementById('copyItineraryModal');
  if (modal) modal.style.display = 'flex';
}

function closeCopyModal() {
  var modal = document.getElementById('copyItineraryModal');
  if (modal) modal.style.display = 'none';
}

// Modal: Clone Trip Package
function openCloneModal(trip) {
  document.getElementById('clone_source_id').value = trip.id;
  document.getElementById('clone_name').value = trip.name + ' (Copy)';
  document.getElementById('clone_code').value = trip.code + '-COPY';
  var modal = document.getElementById('cloneTripModal');
  if (modal) modal.style.display = 'flex';
}

function closeCloneModal() {
  var modal = document.getElementById('cloneTripModal');
  if (modal) modal.style.display = 'none';
}

// Quick Copy in Form Editor
function applyQuickCopy() {
  var sel = document.getElementById('quickCopySelect');
  if (!sel || !sel.value) {
    showToast('Pilih paket trip sumber terlebih dahulu.', 'error');
    return;
  }
  var trip = allTripsData.find(function(t) { return t.id === sel.value; });
  if (!trip) {
    showToast('Data trip tidak ditemukan.', 'error');
    return;
  }

  if (!confirm('Terapkan fasilitas & jadwal itinerary dari "' + trip.name + '" ke form ini? Input yang ada saat ini akan digantikan.')) {
    return;
  }

  // 1. Populate Includes
  var inclList = document.getElementById('includes-list');
  if (inclList && trip.includes && trip.includes.length > 0) {
    inclList.innerHTML = '';
    trip.includes.forEach(function(item) {
      var div = document.createElement('div');
      div.className = 'adm-dyn-item';
      div.innerHTML = '<input type="text" name="includes[]" class="adm-form-input" value="' + escapeHtml(item) + '" placeholder="cth: Hotel ★4" />' +
        '<button type="button" class="btn-icon danger" onclick="removeItem(this)" title="Hapus">' +
          '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>' +
        '</button>';
      inclList.appendChild(div);
    });
  }

  // 2. Populate Excludes
  var exclList = document.getElementById('excludes-list');
  if (exclList && trip.excludes && trip.excludes.length > 0) {
    exclList.innerHTML = '';
    trip.excludes.forEach(function(item) {
      var div = document.createElement('div');
      div.className = 'adm-dyn-item';
      div.innerHTML = '<input type="text" name="excludes[]" class="adm-form-input" value="' + escapeHtml(item) + '" placeholder="cth: Tiket Pesawat Internasional" />' +
        '<button type="button" class="btn-icon danger" onclick="removeItem(this)" title="Hapus">' +
          '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>' +
        '</button>';
      exclList.appendChild(div);
    });
  }

  // 3. Populate Itinerary Days
  var itinList = document.getElementById('itin-list');
  if (itinList && trip.itinerary && trip.itinerary.length > 0) {
    itinList.innerHTML = '';
    trip.itinerary.forEach(function(day, idx) {
      var dayNum = idx + 1;
      var uid = Date.now() + '_' + idx;
      var div = document.createElement('div');
      div.className = 'adm-itin-item';
      div.dataset.idx = idx;
      
      var prevSrc = day.img ? (day.img.startsWith('http') ? day.img : '../' + day.img) : '';
      var imgPreviewHtml = prevSrc 
        ? '<img class="adm-itin-preview show" id="itin-prev-' + uid + '" src="' + escapeHtml(prevSrc) + '" alt="" />'
        : '<img class="adm-itin-preview" id="itin-prev-' + uid + '" src="" alt="" />';

      div.innerHTML =
        '<div class="adm-itin-header" onclick="toggleItin(this)">' +
          '<div style="display:flex;align-items:center;">' +
            '<span class="adm-itin-day-label">HARI ' + dayNum + '</span>' +
            '<span class="adm-itin-day-title" id="itin-title-display-' + uid + '">' + (day.title ? ' — ' + escapeHtml(day.title) : '') + '</span>' +
          '</div>' +
          '<div style="display:flex;gap:6px;align-items:center;">' +
            '<button type="button" class="btn-icon btn-sm" onclick="event.stopPropagation();duplicateItinDay(this)" title="Duplikat Hari Ini" style="color:#0284c7;background:#e0f2fe;">' +
              '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.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>' +
            '<button type="button" class="btn-icon danger btn-sm" onclick="event.stopPropagation();removeItin(this)" title="Hapus Hari">' +
              '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>' +
            '</button>' +
            '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="itin-chevron"><polyline points="6 9 12 15 18 9"/></svg>' +
          '</div>' +
        '</div>' +
        '<div class="adm-itin-body ' + (idx === 0 ? 'open' : '') + '">' +
          '<input type="hidden" name="itin_day[]" value="' + dayNum + '" class="itin-day-val" />' +
          '<div class="adm-form-group">' +
            '<label class="adm-form-label">Judul Aktivitas Hari Ini *</label>' +
            '<input type="text" name="itin_title[]" class="adm-form-input itin-title-inp" value="' + escapeHtml(day.title || '') + '" placeholder="Contoh: ARRIVAL TOKYO / CITY TOUR" oninput="updateItinTitle(this)" required />' +
          '</div>' +
          '<div class="adm-form-group">' +
            '<label class="adm-form-label">Rincian Kegiatan</label>' +
            '<textarea name="itin_desc[]" class="adm-form-textarea" placeholder="Deskripsi kegiatan, rute kunjungan, tempat makan, dll...">' + escapeHtml(day.desc || '') + '</textarea>' +
          '</div>' +
          '<div class="adm-form-group">' +
            '<label class="adm-form-label">Foto Kegiatan Hari Ini (opsional)</label>' +
            imgPreviewHtml +
            '<input type="hidden" name="itin_img_existing[]" value="' + escapeHtml(day.img || '') + '" />' +
            '<label class="adm-upload-label" for="itin-file-' + uid + '">' +
              '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>' +
              '<span id="itin-lbl-' + uid + '">' + (day.img ? 'Ganti Foto' : 'Upload Foto Kegiatan') + '</span>' +
              '<input type="file" id="itin-file-' + uid + '" name="itin_img_file_' + uid + '" accept="image/jpeg,image/png,image/webp" onchange="previewUpload(this,\'itin-prev-' + uid + '\',\'itin-lbl-' + uid + '\')" />' +
            '</label>' +
            '<span class="adm-form-hint" style="color:#0284c7;font-weight:600;">📐 Rasio Aspek: 4:3 atau 16:9 (Landscape). Format: JPG, PNG, WebP (Maks 5 MB).</span>' +
          '</div>' +
        '</div>';
      itinList.appendChild(div);
    });
  }

  showToast('Fasilitas & itinerary dari "' + trip.name + '" berhasil disalin ke form! Klik Simpan untuk menyimpan permanen.', 'success');
}

// Duplicate a specific day in the timeline
function duplicateItinDay(btn) {
  var item = btn.closest('.adm-itin-item');
  if (!item) return;
  var title = item.querySelector('.itin-title-inp')?.value || '';
  var desc = item.querySelector('textarea')?.value || '';
  var existingImg = item.querySelector('input[name="itin_img_existing[]"]')?.value || '';
  var previewImg = item.querySelector('.adm-itin-preview')?.src || '';

  var list = document.getElementById('itin-list');
  var dayNum = list.children.length + 1;
  var uid = Date.now();
  var div = document.createElement('div');
  div.className = 'adm-itin-item';

  var imgPreviewHtml = existingImg && previewImg
    ? '<img class="adm-itin-preview show" id="itin-prev-' + uid + '" src="' + escapeHtml(previewImg) + '" alt="" />'
    : '<img class="adm-itin-preview" id="itin-prev-' + uid + '" src="" alt="" />';

  div.innerHTML =
    '<div class="adm-itin-header" onclick="toggleItin(this)">' +
      '<div style="display:flex;align-items:center;">' +
        '<span class="adm-itin-day-label">HARI ' + dayNum + '</span>' +
        '<span class="adm-itin-day-title" id="itin-title-display-' + uid + '">' + (title ? ' — ' + escapeHtml(title) : '') + '</span>' +
      '</div>' +
      '<div style="display:flex;gap:6px;align-items:center;">' +
        '<button type="button" class="btn-icon btn-sm" onclick="event.stopPropagation();duplicateItinDay(this)" title="Duplikat Hari Ini" style="color:#0284c7;background:#e0f2fe;">' +
          '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.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>' +
        '<button type="button" class="btn-icon danger btn-sm" onclick="event.stopPropagation();removeItin(this)" title="Hapus Hari">' +
          '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>' +
        '</button>' +
        '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="itin-chevron"><polyline points="6 9 12 15 18 9"/></svg>' +
      '</div>' +
    '</div>' +
    '<div class="adm-itin-body open">' +
      '<input type="hidden" name="itin_day[]" value="' + dayNum + '" class="itin-day-val" />' +
      '<div class="adm-form-group">' +
        '<label class="adm-form-label">Judul Aktivitas Hari Ini *</label>' +
        '<input type="text" name="itin_title[]" class="adm-form-input itin-title-inp" value="' + escapeHtml(title) + '" placeholder="Contoh: ARRIVAL TOKYO / CITY TOUR" oninput="updateItinTitle(this)" required />' +
      '</div>' +
      '<div class="adm-form-group">' +
        '<label class="adm-form-label">Rincian Kegiatan</label>' +
        '<textarea name="itin_desc[]" class="adm-form-textarea" placeholder="Deskripsi kegiatan, rute kunjungan, tempat makan, dll...">' + escapeHtml(desc) + '</textarea>' +
      '</div>' +
      '<div class="adm-form-group">' +
        '<label class="adm-form-label">Foto Kegiatan Hari Ini (opsional)</label>' +
        imgPreviewHtml +
        '<input type="hidden" name="itin_img_existing[]" value="' + escapeHtml(existingImg) + '" />' +
        '<label class="adm-upload-label" for="itin-file-' + uid + '">' +
          '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>' +
          '<span id="itin-lbl-' + uid + '">' + (existingImg ? 'Ganti Foto' : 'Upload Foto Kegiatan') + '</span>' +
          '<input type="file" id="itin-file-' + uid + '" name="itin_img_file_' + uid + '" accept="image/jpeg,image/png,image/webp" onchange="previewUpload(this,\'itin-prev-' + uid + '\',\'itin-lbl-' + uid + '\')" />' +
        '</label>' +
        '<span class="adm-form-hint" style="color:#0284c7;font-weight:600;">📐 Rasio Aspek: 4:3 atau 16:9 (Landscape). Format: JPG, PNG, WebP (Maks 5 MB).</span>' +
      '</div>' +
    '</div>';

  list.appendChild(div);
  renumberItin();
  div.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
  showToast('Hari ' + dayNum + ' berhasil diduplikasi!', 'success');
}

// Remove dynamic item
function removeItem(btn) {
  const item = btn.closest('.adm-dyn-item');
  const list = item.parentElement;
  if (list.children.length > 1) item.remove();
  else item.querySelector('input').value = '';
}

// Add dynamic item
function addItem(listId, inputName, placeholder) {
  const list = document.getElementById(listId);
  const div = document.createElement('div');
  div.className = 'adm-dyn-item';
  div.innerHTML = `<input type="text" name="${inputName}" class="adm-form-input" placeholder="${placeholder}" />
    <button type="button" class="btn-icon danger" onclick="removeItem(this)">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
    </button>`;
  list.appendChild(div);
  div.querySelector('input').focus();
}

// Itinerary toggle
function toggleItin(header) {
  const body = header.nextElementSibling;
  const chevron = header.querySelector('.itin-chevron');
  body.classList.toggle('open');
  chevron.style.transform = body.classList.contains('open') ? 'rotate(180deg)' : '';
}

// Update header title live
function updateItinTitle(inp) {
  const item = inp.closest('.adm-itin-item');
  const display = item.querySelector('.adm-itin-day-title');
  display.textContent = inp.value ? ' — ' + inp.value : '';
}

// Remove itinerary day
function removeItin(btn) {
  const item = btn.closest('.adm-itin-item');
  const list = document.getElementById('itin-list');
  if (list.children.length > 1) {
    item.remove();
    renumberItin();
  } else {
    showToast('Minimal harus ada 1 hari itinerary.', 'error');
  }
}

// Add itinerary day
function addItinDay() {
  var list = document.getElementById('itin-list');
  var dayNum = list.children.length + 1;
  var idx = Date.now();
  var div = document.createElement('div');
  div.className = 'adm-itin-item';
  div.innerHTML =
    '<div class="adm-itin-header" onclick="toggleItin(this)">' +
      '<div style="display:flex;align-items:center;">' +
        '<span class="adm-itin-day-label">HARI ' + dayNum + '</span>' +
        '<span class="adm-itin-day-title"></span>' +
      '</div>' +
      '<div style="display:flex;gap:6px;align-items:center;">' +
        '<button type="button" class="btn-icon btn-sm" onclick="event.stopPropagation();duplicateItinDay(this)" title="Duplikat Hari Ini" style="color:#0284c7;background:#e0f2fe;">' +
          '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.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>' +
        '<button type="button" class="btn-icon danger btn-sm" onclick="event.stopPropagation();removeItin(this)" title="Hapus Hari">' +
          '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>' +
        '</button>' +
        '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" class="itin-chevron"><polyline points="6 9 12 15 18 9"/></svg>' +
      '</div>' +
    '</div>' +
    '<div class="adm-itin-body open">' +
      '<input type="hidden" name="itin_day[]" value="' + dayNum + '" class="itin-day-val" />' +
      '<div class="adm-form-group">' +
        '<label class="adm-form-label">Judul Aktivitas Hari Ini *</label>' +
        '<input type="text" name="itin_title[]" class="adm-form-input itin-title-inp" placeholder="Contoh: ARRIVAL TOKYO / CITY TOUR" oninput="updateItinTitle(this)" required />' +
      '</div>' +
      '<div class="adm-form-group">' +
        '<label class="adm-form-label">Rincian Kegiatan</label>' +
        '<textarea name="itin_desc[]" class="adm-form-textarea" placeholder="Deskripsi kegiatan, rute kunjungan, tempat makan, dll..."></textarea>' +
      '</div>' +
      '<div class="adm-form-group">' +
        '<label class="adm-form-label">Foto Kegiatan Hari Ini (opsional)</label>' +
        '<img class="adm-itin-preview" id="itin-prev-' + idx + '" src="" alt="" />' +
        '<input type="hidden" name="itin_img_existing[]" value="" />' +
        '<label class="adm-upload-label" for="itin-file-' + idx + '">' +
          '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>' +
          '<span id="itin-lbl-' + idx + '">Upload Foto Kegiatan</span>' +
          '<input type="file" id="itin-file-' + idx + '" name="itin_img_file_' + idx + '" accept="image/jpeg,image/png,image/webp" onchange="previewUpload(this,\'itin-prev-' + idx + '\',\'itin-lbl-' + idx + '\')" />' +
        '</label>' +
        '<span class="adm-form-hint" style="color:#0284c7;font-weight:600;">📐 Rasio Aspek: 4:3 atau 16:9 (Landscape). Rekomendasi: 800×600 px atau 1200×800 px. Format: JPG, PNG, WebP (Maks 5 MB).</span>' +
      '</div>' +
    '</div>';
  list.appendChild(div);
  div.querySelector('.adm-itin-body').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

// Renumber days
function renumberItin() {
  document.querySelectorAll('#itin-list .adm-itin-item').forEach(function(item, i) {
    const label = item.querySelector('.adm-itin-day-label');
    const dayInput = item.querySelector('.itin-day-val');
    if (label) label.textContent = 'HARI ' + (i + 1);
    if (dayInput) dayInput.value = i + 1;
  });
}

document.addEventListener('DOMContentLoaded', function() {
  const first = document.querySelector('.adm-itin-body');
  if (first) first.classList.add('open');
});
</script>

<?php adm_layout_end(); ?>
