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

$action  = $_GET['action'] ?? 'list';
$editId  = isset($_GET['id']) ? (int)$_GET['id'] : null;
$editRow = null;
$errors  = [];

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

    // DELETE
    if ($postAction === 'delete') {
        $id = (int)$_POST['id'];
        // get heroImg to potentially delete file
        $row = $pdo->prepare("SELECT heroImg FROM countries WHERE id = ?");
        $row->execute([$id]);
        $row = $row->fetch();
        $pdo->prepare("DELETE FROM countries WHERE id = ?")->execute([$id]);
        // delete uploaded file if local
        if ($row && str_starts_with($row['heroImg'], 'assets/uploads/')) {
            $f = dirname(__DIR__) . '/' . $row['heroImg'];
            if (file_exists($f)) @unlink($f);
        }
        $_SESSION['adm_toast'] = ['msg' => 'Destinasi berhasil dihapus.', 'type' => 'success'];
        header('Location: destinasi.php');
        exit;
    }

    // TOGGLE HOME VISIBILITY QUICK ACTION
    if ($postAction === 'toggle_home') {
        $id = (int)$_POST['id'];
        $val = (int)$_POST['val'] === 1 ? 0 : 1;
        $pdo->prepare("UPDATE countries SET show_on_home = ? WHERE id = ?")->execute([$val, $id]);
        $msg = $val ? 'Destinasi sekarang ditampilkan di Beranda.' : 'Destinasi disembunyikan dari Beranda.';
        $_SESSION['adm_toast'] = ['msg' => $msg, 'type' => 'success'];
        header('Location: destinasi.php');
        exit;
    }

    // ADD / EDIT
    $slug        = trim($_POST['slug'] ?? '');
    $name        = trim($_POST['name'] ?? '');
    $flag        = trim($_POST['flag'] ?? '');
    $tagline     = trim($_POST['tagline'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $showOnHome  = isset($_POST['show_on_home']) ? 1 : 0;
    $existImg    = trim($_POST['existing_heroImg'] ?? '');

    if (!$slug) $errors[] = 'Slug wajib diisi.';
    if (!$name) $errors[] = 'Nama wajib diisi.';

    // Handle image upload
    $upload = adm_upload_image('heroImg', 'countries', $existImg);
    if ($upload['error']) {
        $errors[] = $upload['error'];
    }
    $heroImg = $upload['path'];
    if (!$heroImg && $postAction !== 'edit') {
        $errors[] = 'Gambar hero wajib diunggah.';
    }

    if (empty($errors)) {
        try {
            if ($postAction === 'edit') {
                $id = (int)$_POST['id'];
                $pdo->prepare("UPDATE countries SET slug=?,name=?,flag=?,heroImg=?,tagline=?,description=?,show_on_home=? WHERE id=?")
                    ->execute([$slug, $name, $flag, $heroImg, $tagline, $description, $showOnHome, $id]);
                $_SESSION['adm_toast'] = ['msg' => "Destinasi \"$name\" berhasil diperbarui!", 'type' => 'success'];
            } else {
                $pdo->prepare("INSERT INTO countries (slug,name,flag,heroImg,tagline,description,show_on_home) VALUES (?,?,?,?,?,?,?)")
                    ->execute([$slug, $name, $flag, $heroImg, $tagline, $description, $showOnHome]);
                $_SESSION['adm_toast'] = ['msg' => "Destinasi \"$name\" berhasil ditambahkan!", 'type' => 'success'];
            }
            header('Location: destinasi.php');
            exit;
        } catch (\PDOException $e) {
            if ($e->getCode() === '23000') {
                $errors[] = "Slug \"$slug\" sudah digunakan oleh destinasi lain. Gunakan slug yang berbeda.";
            } else {
                $errors[] = 'Database error: ' . $e->getMessage();
            }
        }
    }

    // Re-populate for re-display
    $editRow = [
        'id' => $_POST['id'] ?? null,
        'slug' => $slug, 'name' => $name, 'flag' => $flag,
        'heroImg' => $heroImg ?: $existImg,
        'tagline' => $tagline, 'description' => $description,
        'show_on_home' => $showOnHome,
    ];
    $action = $postAction === 'edit' ? 'edit' : 'add';
}

/* ── FETCH DATA ───────────────────────────────────────────── */
$countries = $pdo->query(
    "SELECT c.*, COUNT(t.id) AS trip_count
     FROM countries c
     LEFT JOIN trips t ON c.id = t.country_id
     GROUP BY c.id ORDER BY c.show_on_home DESC, c.name ASC"
)->fetchAll();

if ($editId && !$editRow) {
    $stmt = $pdo->prepare("SELECT * FROM countries WHERE id = ?");
    $stmt->execute([$editId]);
    $editRow = $stmt->fetch();
    $action  = 'edit';
}

$showForm = ($action === 'add' || $action === 'edit');

adm_layout_start('destinasi', 'Step 1: Manajemen Destinasi');
?>

<!-- Stepper Bar -->
<div class="adm-stepper">
  <div class="adm-step-item active">
    <span class="adm-step-num">1</span>
    <span>Destinasi (Negara)</span>
  </div>
  <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>
  <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 1: Destinasi (Negara)</h1>
    <p class="adm-page-sub">Buat dan kelola negara/destinasi utama yang tampil di website</p>
  </div>
  <?php if (!$showForm): ?>
  <div style="display:flex;gap:10px;">
    <a href="?action=add" 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 Destinasi
    </a>
    <a href="trips.php" class="btn btn-outline">
      Lanjut ke Step 2 (Paket Trip) →
    </a>
  </div>
  <?php else: ?>
  <a href="destinasi.php" class="btn btn-outline">← Kembali</a>
  <?php endif; ?>
</div>

<?php if ($showForm): ?>
<!-- ── FORM ───────────────────────────────────────────────── -->
<div class="adm-card">
  <div class="adm-card-header">
    <span class="adm-card-title"><?= $action === 'edit' ? 'Edit Destinasi' : 'Tambah Destinasi Baru' ?></span>
  </div>
  <div class="adm-card-body">

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

    <form method="POST" enctype="multipart/form-data" class="adm-form">
      <input type="hidden" name="_action" value="<?= $action === 'edit' ? 'edit' : 'add' ?>" />
      <?php if (!empty($editRow['id'])): ?>
      <input type="hidden" name="id" value="<?= (int)$editRow['id'] ?>" />
      <?php endif; ?>
      <input type="hidden" name="existing_heroImg" value="<?= htmlspecialchars($editRow['heroImg'] ?? '') ?>" />

      <!-- Option: Tampilkan di Beranda -->
      <label class="adm-switch-card" for="f-show-home">
        <div class="adm-switch-info">
          <div class="adm-switch-title">🏠 Tampilkan di Beranda (Home)</div>
          <div class="adm-switch-desc">Jika diaktifkan, destinasi ini akan muncul pada kartu rekomendasi di halaman utama/beranda.</div>
        </div>
        <div class="adm-switch">
          <input type="checkbox" id="f-show-home" name="show_on_home" value="1"
                 <?= (!isset($editRow['show_on_home']) || !empty($editRow['show_on_home'])) ? 'checked' : '' ?> />
          <span class="adm-slider"></span>
        </div>
      </label>

      <div class="adm-form-row">
        <div class="adm-form-group">
          <label class="adm-form-label" for="f-slug">Slug (URL) *</label>
          <input type="text" id="f-slug" name="slug" class="adm-form-input"
                 placeholder="japan" value="<?= htmlspecialchars($editRow['slug'] ?? '') ?>" required />
          <span class="adm-form-hint">Huruf kecil, tanpa spasi. Contoh: <code>japan</code>, <code>korea</code></span>
        </div>
        <div class="adm-form-group">
          <label class="adm-form-label" for="f-name">Nama Negara / Destinasi *</label>
          <input type="text" id="f-name" name="name" class="adm-form-input"
                 placeholder="Japan" value="<?= htmlspecialchars($editRow['name'] ?? '') ?>" required />
        </div>
      </div>

      <div class="adm-form-row">
        <!-- Flag Picker Field -->
        <div class="adm-form-group">
          <div style="display:flex;align-items:center;justify-content:space-between;">
            <label class="adm-form-label" for="f-flag">Bendera Negara</label>
            <a href="https://flagpedia.net/index" target="_blank" rel="noopener noreferrer" class="btn btn-outline btn-sm" style="padding:3px 10px;font-size:11.5px;display:flex;align-items:center;gap:5px;text-decoration:none;" title="Buka daftar 254 bendera negara di Flagpedia">
              <span>🚩</span> Daftar Bendera (Flagpedia.net) ↗
            </a>
          </div>
          <div style="display:flex;align-items:center;gap:10px;">
            <div id="flag-live-preview" style="min-width:32px;display:flex;align-items:center;justify-content:center;">
              <?= render_flag($editRow['flag'] ?? '') ?>
            </div>
            <input type="text" id="f-flag" name="flag" class="adm-form-input"
                   placeholder="Contoh: id, jp, kr, cn, us..."
                   value="<?= htmlspecialchars($editRow['flag'] ?? '') ?>"
                   oninput="updateFlagPreview(this.value)" />
          </div>
          <span class="adm-form-hint">Ketik 2 huruf kode negara (misal: <code>id</code> untuk 🇮🇩, <code>jp</code> untuk 🇯🇵, <code>kr</code> untuk 🇰🇷, <code>cn</code> untuk 🇨🇳). Klik <b>Daftar Bendera</b> untuk melihat semua 254 kode negara di dunia.</span>
        </div>

        <div class="adm-form-group">
          <label class="adm-form-label" for="f-tagline">Tagline</label>
          <input type="text" id="f-tagline" name="tagline" class="adm-form-input"
                 placeholder="Negeri Matahari Terbit"
                 value="<?= htmlspecialchars($editRow['tagline'] ?? '') ?>" />
        </div>
      </div>

      <!-- Image Upload -->
      <div class="adm-form-group">
        <label class="adm-form-label">Gambar Hero <?= $action === 'add' ? '*' : '' ?></label>
        <?php if (!empty($editRow['heroImg'])): 
          $prevSrc = str_starts_with($editRow['heroImg'], 'http') ? $editRow['heroImg'] : '../' . $editRow['heroImg'];
        ?>
        <div class="adm-current-img">
          <img src="<?= htmlspecialchars($prevSrc) ?>" alt="Gambar saat ini" class="adm-img-preview show" id="hero-preview" />
          <span class="adm-form-hint">Gambar saat ini. Upload baru untuk menggantinya.</span>
        </div>
        <?php else: ?>
        <img id="hero-preview" class="adm-img-preview" src="" alt="Preview" />
        <?php endif; ?>
        <label class="adm-upload-label" for="f-hero">
          <svg width="18" height="18" 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="hero-file-label">Pilih Gambar<?= $action === 'edit' ? ' (opsional)' : '' ?></span>
          <input type="file" id="f-hero" name="heroImg" accept="image/jpeg,image/png,image/webp,image/gif"
                 onchange="previewUpload(this, 'hero-preview', 'hero-file-label')" />
        </label>
        <span class="adm-form-hint" style="color:#0284c7;font-weight:600;">
          📐 Rasio Aspek: 16:9 (Landscape Lebar). Rekomendasi: 1920×1080 px atau 1600×900 px. Format: JPG, PNG, WebP (Maks 5 MB).
        </span>
      </div>

      <div class="adm-form-group">
        <label class="adm-form-label" for="f-desc">Deskripsi</label>
        <textarea id="f-desc" name="description" class="adm-form-textarea"
                  placeholder="Deskripsi singkat tentang destinasi ini..."><?= htmlspecialchars($editRow['description'] ?? '') ?></textarea>
      </div>

      <div style="display:flex;gap:10px;padding-top:4px;">
        <button type="submit" class="btn btn-primary">
          <?= $action === 'edit' ? '💾 Simpan Perubahan' : '+ Tambah Destinasi' ?>
        </button>
        <a href="destinasi.php" class="btn btn-outline">Batal</a>
      </div>
    </form>
  </div>
</div>

<?php else: ?>
<!-- ── LIST ───────────────────────────────────────────────── -->
<div class="adm-card">
  <div class="adm-table-wrap">
    <table class="adm-table">
      <thead>
        <tr>
          <th>Gambar</th>
          <th>Flag</th>
          <th>Nama</th>
          <th>Slug</th>
          <th>Tampil di Home</th>
          <th>Tagline</th>
          <th>Trips</th>
          <th>Aksi</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($countries as $c): ?>
        <tr>
          <td>
            <?php
            $imgSrc = $c['heroImg'];
            if ($imgSrc && !str_starts_with($imgSrc, 'http')) {
                $imgSrc = '../' . $imgSrc;
            }
            ?>
            <img src="<?= htmlspecialchars($imgSrc) ?>" alt="<?= htmlspecialchars($c['name']) ?>"
                 class="adm-table-img" onerror="this.src='data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 width=%2252%22 height=%2238%22><rect fill=%22%23f0f0f0%22 width=%2252%22 height=%2238%22/></svg>'" />
          </td>
          <td class="adm-table-flag"><?= render_flag($c['flag']) ?></td>
          <td><strong><?= htmlspecialchars($c['name']) ?></strong></td>
          <td><code><?= htmlspecialchars($c['slug']) ?></code></td>
          <td>
            <form method="POST" style="display:inline;">
              <input type="hidden" name="_action" value="toggle_home" />
              <input type="hidden" name="id" value="<?= $c['id'] ?>" />
              <input type="hidden" name="val" value="<?= (int)$c['show_on_home'] ?>" />
              <?php if (!empty($c['show_on_home'])): ?>
              <button type="submit" class="adm-badge adm-badge-blue" style="border:none;cursor:pointer;font-family:inherit;" title="Klik untuk sembunyikan dari beranda">
                ⭐ Beranda
              </button>
              <?php else: ?>
              <button type="submit" class="adm-badge" style="border:none;cursor:pointer;background:#f1f5f9;color:#94a3b8;font-family:inherit;" title="Klik untuk tampilkan di beranda">
                Hanya Destinasi
              </button>
              <?php endif; ?>
            </form>
          </td>
          <td><?= htmlspecialchars($c['tagline']) ?></td>
          <td><span class="adm-badge adm-badge-green"><?= $c['trip_count'] ?> trip</span></td>
          <td style="display:flex;gap:6px;align-items:center;">
            <a href="?action=edit&id=<?= $c['id'] ?>" class="btn-icon" title="Edit">
              <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>
            <a href="../negara?country=<?= urlencode($c['slug']) ?>" 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="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>
            </a>
            <button type="button" class="btn-icon danger del-country-btn"
              data-id="<?= $c['id'] ?>"
              data-name="<?= htmlspecialchars($c['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($countries)): ?>
        <tr><td colspan="8">
          <div class="adm-empty">
            <div class="adm-empty-icon">🌍</div>
            <h3>Belum ada destinasi</h3>
            <p>Mulai dengan menambahkan destinasi pertama.</p>
          </div>
        </td></tr>
        <?php endif; ?>
      </tbody>
    </table>
</div>
</div>
<?php endif; ?>

<script>
function updateFlagPreview(val) {
  var preview = document.getElementById('flag-live-preview');
  if (!preview) return;
  val = val.trim().toLowerCase();
  if (val.length === 2 && /^[a-z]{2}$/.test(val)) {
    preview.innerHTML = '<img src="https://flagcdn.com/w40/' + val + '.png" srcset="https://flagcdn.com/w80/' + val + '.png 2x" style="width:24px;height:16px;object-fit:cover;border-radius:2.5px;box-shadow:0 1px 3px rgba(0,0,0,0.18);" />';
  } else if (val) {
    preview.textContent = val;
  } else {
    preview.innerHTML = '';
  }
}

document.addEventListener('DOMContentLoaded', function() {
  document.querySelectorAll('.del-country-btn').forEach(function(btn) {
    btn.addEventListener('click', function() {
      var id   = this.dataset.id;
      var name = this.dataset.name;
      confirmDelete('Hapus destinasi "' + name + '"? Semua paket trip-nya ikut terhapus!', 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(); ?>
