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

$editId  = $_GET['id'] ?? null;
$editRow = null;
$errors  = [];

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

// Load existing trip if editing
if ($editId) {
    $stmt = $pdo->prepare("SELECT * FROM trips WHERE id = ?");
    $stmt->execute([$editId]);
    $editRow = $stmt->fetch();
}

/* ── HANDLE POST ──────────────────────────────────────────── */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postAction  = $_POST['_action'] ?? 'add';
    $id          = trim($_POST['id'] ?? '');
    $country_id  = (int)($_POST['country_id'] ?? 0);
    $code        = trim($_POST['code'] ?? '');
    $name        = trim($_POST['name'] ?? '');
    $duration    = trim($_POST['duration'] ?? '');
    $durShort    = trim($_POST['durationShort'] ?? '');
    $dateRange   = trim($_POST['dateRange'] ?? '');
    $dateStart   = trim($_POST['dateStart'] ?? '');
    $dateEnd     = trim($_POST['dateEnd'] ?? '');
    $minPax      = (int)($_POST['minPax'] ?? 0);
    $dp_info     = trim($_POST['dp_info'] ?? '');
    $dp_label    = trim($_POST['dp_label'] ?? 'Pembayaran DP') ?: 'Pembayaran DP';
    $price       = (int)($_POST['price'] ?? 0);

    // Validation
    if (!$id)         $errors[] = 'ID Trip wajib diisi.';
    if (!$country_id) $errors[] = 'Destinasi wajib dipilih.';
    if (!$name)       $errors[] = 'Nama trip wajib diisi.';
    if (!$price)      $errors[] = 'Harga wajib diisi.';

    if (empty($errors)) {
        if ($postAction === 'edit') {
            $oldId = trim($_POST['old_id'] ?? $id);
            if ($oldId !== $id) {
                // If ID changed, copy existing json fields from old record
                $oldRow = $pdo->prepare("SELECT includes, excludes, itinerary FROM trips WHERE id = ?");
                $oldRow->execute([$oldId]);
                $oldData = $oldRow->fetch() ?: ['includes'=>'[]','excludes'=>'[]','itinerary'=>'[]'];

                $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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
                    ->execute([$id,$country_id,$code,$name,$duration,$durShort,$dateRange,$dateStart,$dateEnd,$minPax,$dp_info,$dp_label,$price,$oldData['includes'],$oldData['excludes'],$oldData['itinerary']]);
                $pdo->prepare("DELETE FROM trips WHERE id = ?")->execute([$oldId]);
            } else {
                // Keep existing includes/excludes/itinerary untouched
                $pdo->prepare("UPDATE trips SET country_id=?,code=?,name=?,duration=?,durationShort=?,dateRange=?,dateStart=?,dateEnd=?,minPax=?,dp_info=?,dp_label=?,price=? WHERE id=?")
                    ->execute([$country_id,$code,$name,$duration,$durShort,$dateRange,$dateStart,$dateEnd,$minPax,$dp_info,$dp_label,$price,$id]);
            }
            $_SESSION['adm_toast'] = ['msg' => "Info Paket Trip \"$name\" berhasil diperbarui!", 'type' => 'success'];
        } else {
            // Check ID duplicate
            $exists = $pdo->prepare("SELECT COUNT(*) FROM trips WHERE id = ?");
            $exists->execute([$id]);
            if ($exists->fetchColumn() > 0) {
                $errors[] = "ID trip \"$id\" sudah digunakan. Gunakan ID yang lain.";
            } else {
                $defaultJson = '[]';
                $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 (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
                    ->execute([$id,$country_id,$code,$name,$duration,$durShort,$dateRange,$dateStart,$dateEnd,$minPax,$dp_info,$dp_label,$price,$defaultJson,$defaultJson,$defaultJson]);
                $_SESSION['adm_toast'] = ['msg' => "Paket Trip \"$name\" berhasil dibuat! Lanjutkan ke Step 3 untuk mengisi fasilitas & itinerary.", 'type' => 'success'];
            }
        }

        if (empty($errors)) {
            $saveAction = $_POST['save_action'] ?? 'next';
            if ($saveAction === 'next') {
                header('Location: itinerary.php?trip_id=' . urlencode($id));
            } else {
                header('Location: trips.php');
            }
            exit;
        }
    }

    // On validation error, re-populate from POST
    $editRow = [
        'id' => $id, 'country_id' => $country_id, 'code' => $code, 'name' => $name,
        'duration' => $duration, 'durationShort' => $durShort, 'dateRange' => $dateRange,
        'dateStart' => $dateStart, 'dateEnd' => $dateEnd,
        'minPax' => $minPax, 'dp_info' => $dp_info, 'dp_label' => $dp_label, 'price' => $price,
    ];
}

$isEdit = ($editRow && isset($editRow['id']));

adm_layout_start('trips', ($isEdit ? 'Step 2: Edit Paket Trip' : 'Step 2: Tambah 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>
  <?php if ($isEdit): ?>
  <a href="itinerary.php?trip_id=<?= urlencode($editRow['id']) ?>" class="adm-step-item">
    <span class="adm-step-num">3</span>
    <span>Detail &amp; Itinerary</span>
  </a>
  <?php else: ?>
  <div class="adm-step-item">
    <span class="adm-step-num">3</span>
    <span>Detail &amp; Itinerary</span>
  </div>
  <?php endif; ?>
</div>

<div class="adm-page-header">
  <div>
    <h1 class="adm-page-title"><?= $isEdit ? 'Step 2: Edit Paket Trip' : 'Step 2: Tambah Paket Trip' ?></h1>
    <p class="adm-page-sub"><?= $isEdit ? 'Ubah informasi paket perjalanan untuk destinasi terpilih' : 'Isi informasi dasar paket perjalanan untuk destinasi terpilih' ?></p>
  </div>
  <div style="display:flex;gap:10px;">
    <?php if ($isEdit): ?>
    <a href="itinerary.php?trip_id=<?= urlencode($editRow['id']) ?>" class="btn btn-outline">
      🗓️ Ke Step 3 (Detail &amp; Itinerary) →
    </a>
    <?php endif; ?>
    <a href="trips.php" class="btn btn-outline">← Kembali</a>
  </div>
</div>

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

<form method="POST" class="adm-form" id="trip-form">
  <input type="hidden" name="_action" value="<?= $isEdit ? 'edit' : 'add' ?>" />
  <?php if ($isEdit): ?>
  <input type="hidden" name="old_id" value="<?= htmlspecialchars($editRow['id']) ?>" />
  <?php endif; ?>

  <!-- Section: Info Dasar Paket Trip -->
  <div class="adm-card">
    <div class="adm-card-header"><span class="adm-card-title">ℹ️ Informasi Dasar Paket Trip</span></div>
    <div class="adm-card-body">
      <div class="adm-form" style="gap:16px;">

        <div class="adm-form-row">
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-country">Destinasi / Negara *</label>
            <select id="f-country" name="country_id" class="adm-form-select" required>
              <option value="">— Pilih Destinasi —</option>
              <?php foreach ($countries as $c): ?>
              <option value="<?= $c['id'] ?>" <?= ($editRow['country_id'] ?? '') == $c['id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($c['name']) ?>
              </option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-id">ID Trip (URL) *</label>
            <input type="text" id="f-id" name="id" class="adm-form-input"
                   placeholder="japan-403n-aug"
                   value="<?= htmlspecialchars($editRow['id'] ?? '') ?>" required />
            <span class="adm-form-hint">Unik, huruf kecil, tanda hubung. Contoh: <code>japan-403n-aug</code></span>
          </div>
        </div>

        <div class="adm-form-row">
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-code">Kode Trip *</label>
            <input type="text" id="f-code" name="code" class="adm-form-input"
                   placeholder="JAPAN 403N"
                   value="<?= htmlspecialchars($editRow['code'] ?? '') ?>" required />
          </div>
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-name">Nama Trip *</label>
            <input type="text" id="f-name" name="name" class="adm-form-input"
                   placeholder="Tokyo – Osaka – Kyoto"
                   value="<?= htmlspecialchars($editRow['name'] ?? '') ?>" required />
          </div>
        </div>

        <div class="adm-form-row">
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-dur">Durasi Lengkap</label>
            <input type="text" id="f-dur" name="duration" class="adm-form-input"
                   placeholder="4 Days 3 Nights"
                   value="<?= htmlspecialchars($editRow['duration'] ?? '') ?>" />
          </div>
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-durshort">Durasi Singkat</label>
            <input type="text" id="f-durshort" name="durationShort" class="adm-form-input"
                   placeholder="4H 3M"
                   value="<?= htmlspecialchars($editRow['durationShort'] ?? '') ?>" />
          </div>
        </div>

        <div class="adm-form-row">
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-daterange">Range Tanggal (tampil)</label>
            <input type="text" id="f-daterange" name="dateRange" class="adm-form-input"
                   placeholder="22 – 25 Aug 2026"
                   value="<?= htmlspecialchars($editRow['dateRange'] ?? '') ?>" />
          </div>
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-minpax">Minimum Peserta (Angka Pax)</label>
            <input type="number" id="f-minpax" name="minPax" class="adm-form-input"
                   placeholder="15" min="1"
                   value="<?= (int)($editRow['minPax'] ?? 0) ?: '' ?>" />
          </div>
        </div>

        <div class="adm-form-row">
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-dplabel">Label Ringkasan DP</label>
            <input type="text" id="f-dplabel" name="dp_label" class="adm-form-input"
                   placeholder="Pembayaran DP"
                   value="<?= htmlspecialchars($editRow['dp_label'] ?? 'Pembayaran DP') ?>" />
            <span class="adm-form-hint">Label judul kolom ke-3 ringkasan trip (contoh: <code>Pembayaran DP</code> atau <code>Minimum Peserta</code>).</span>
          </div>
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-dpinfo">Info Pembayaran DP / Ketentuan *</label>
            <input type="text" id="f-dpinfo" name="dp_info" class="adm-form-input"
                   placeholder="Contoh: 3,5Jt/Pax atau 3,5 Jt / Pax"
                   value="<?= htmlspecialchars($editRow['dp_info'] ?? '') ?>" />
            <span class="adm-form-hint">Teks yang ditampilkan di kolom ringkasan trip &amp; sidebar (contoh: <code>3,5Jt/Pax</code>).</span>
          </div>
        </div>

        <div class="adm-form-row">
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-dstart">Tanggal Mulai</label>
            <input type="text" id="f-dstart" name="dateStart" class="adm-form-input"
                   placeholder="22 Agustus 2026"
                   value="<?= htmlspecialchars($editRow['dateStart'] ?? '') ?>" />
          </div>
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-dend">Tanggal Selesai</label>
            <input type="text" id="f-dend" name="dateEnd" class="adm-form-input"
                   placeholder="25 Agustus 2026"
                   value="<?= htmlspecialchars($editRow['dateEnd'] ?? '') ?>" />
          </div>
        </div>

        <div class="adm-form-group">
          <label class="adm-form-label" for="f-price">Harga per Pax (Rp) *</label>
          <input type="number" id="f-price" name="price" class="adm-form-input"
                 placeholder="9900000" min="0"
                 value="<?= (int)($editRow['price'] ?? 0) ?: '' ?>" required />
        </div>

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

  <!-- Submit Buttons -->
  <div style="display:flex;gap:12px;padding-bottom:32px;flex-wrap:wrap;align-items:center;">
    <button type="submit" name="save_action" value="next" class="btn btn-primary" style="padding:13px 24px;font-size:14px;">
      💾 Simpan &amp; Lanjut ke Step 3 (Detail &amp; Itinerary) →
    </button>
    <button type="submit" name="save_action" value="stay" class="btn btn-outline" style="padding:13px 18px;font-size:13.5px;">
      💾 Simpan Saja
    </button>
    <a href="trips.php" class="btn btn-outline" style="padding:13px 18px;font-size:13.5px;">Batal</a>
    <?php if ($isEdit): ?>
    <a href="../detail-trip?trip=<?= urlencode($editRow['id']) ?>" target="_blank"
       class="btn btn-outline" style="margin-left:auto;padding:13px 18px;font-size:13.5px;">
       👁️ Lihat di Website
    </a>
    <?php endif; ?>
  </div>

</form>

<?php adm_layout_end(); ?>
