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

$errors = [];
$success = false;

// Handle POST save settings
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $keys = [
        // Hero Beranda
        'hero_tagline', 'hero_title', 'hero_subtitle',
        // Kontak
        'whatsapp', 'whatsapp_admin1_name', 'whatsapp_admin1_number',
        'whatsapp_admin2_name', 'whatsapp_admin2_number',
        'email', 'instagram', 'tiktok', 'address', 'footer_tagline', 'copyright', 
        'maps_embed', 'youtube_embed', 'youtube_tagline', 'youtube_title', 'youtube_desc',
        'terms_conditions'
    ];

    // Handle hero image upload
    if (!empty($_FILES['hero_image_file']['name'])) {
        $uploadDir = dirname(__DIR__) . '/assets/uploads/hero/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
        $ext = strtolower(pathinfo($_FILES['hero_image_file']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png','webp','gif'];
        if (in_array($ext, $allowed) && $_FILES['hero_image_file']['error'] === UPLOAD_ERR_OK) {
            $filename = 'hero_bg_' . time() . '.' . $ext;
            $dest = $uploadDir . $filename;
            if (move_uploaded_file($_FILES['hero_image_file']['tmp_name'], $dest)) {
                $_POST['hero_image'] = 'assets/uploads/hero/' . $filename;
            }
        }
    }
    // Keep existing image if no upload and no URL change
    if (!isset($_POST['hero_image']) || $_POST['hero_image'] === '') {
        // keep existing
    }
    $keys[] = 'hero_image';
    
    // Auto-sync fallback whatsapp key with admin 1 if needed
    if (empty($_POST['whatsapp']) && !empty($_POST['whatsapp_admin1_number'])) {
        $_POST['whatsapp'] = $_POST['whatsapp_admin1_number'];
    }

    $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM settings WHERE `key` = ?");
    $stmtUpdate = $pdo->prepare("UPDATE settings SET `value` = ? WHERE `key` = ?");
    $stmtInsert = $pdo->prepare("INSERT INTO settings (`key`, `value`) VALUES (?, ?)");

    foreach ($keys as $k) {
        $val = trim($_POST[$k] ?? '');
        $stmtCheck->execute([$k]);
        if ($stmtCheck->fetchColumn() > 0) {
            $stmtUpdate->execute([$val, $k]);
        } else {
            $stmtInsert->execute([$k, $val]);
        }
    }

    $_SESSION['adm_toast'] = ['msg' => 'Pengaturan website berhasil disimpan!', 'type' => 'success'];
    header('Location: pengaturan.php');
    exit;
}

// Fetch current settings
$settings = get_site_settings();

adm_layout_start('pengaturan', 'Pengaturan Website & Kontak');
?>

<div class="adm-page-header">
  <div>
    <h1 class="adm-page-title">⚙️ Pengaturan Website &amp; Kontak</h1>
    <p class="adm-page-sub">Kelola 2 nomor WhatsApp Admin (Dorothy &amp; Anis), sosial media (Instagram, TikTok), email, peta Google Maps, dan informasi footer website.</p>
  </div>
</div>

<form method="POST" class="adm-form" style="max-width:960px;" enctype="multipart/form-data">

  <!-- Card 0: Hero Beranda -->
  <div class="adm-card" style="border-left:4px solid #2563eb;">
    <div class="adm-card-header">
      <span class="adm-card-title">🖼️ Konten Hero Beranda (Homepage)</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-hero-tagline">Tagline / Eyebrow Hero</label>
            <input type="text" id="f-hero-tagline" name="hero_tagline" class="adm-form-input"
                   placeholder="Travel More, Worry Less"
                   value="<?= htmlspecialchars($settings['hero_tagline'] ?? 'Travel More, Worry Less') ?>" />
            <span class="adm-form-hint">Teks kecil di atas judul utama. Contoh: <code>Travel More, Worry Less</code></span>
          </div>
        </div>

        <div class="adm-form-group">
          <label class="adm-form-label" for="f-hero-title">Judul Utama Hero *</label>
          <textarea id="f-hero-title" name="hero_title" class="adm-form-textarea" rows="2"
                    placeholder="Explore The World&#10;With Travelica"><?= htmlspecialchars($settings['hero_title'] ?? "Explore The World\nWith Travelica") ?></textarea>
          <span class="adm-form-hint">💡 Pisahkan baris dengan <code>Enter</code> untuk membuat baris baru di hero. Contoh baris 1: <code>Explore The World</code> — baris 2: <code>With Travelica</code></span>
        </div>

        <div class="adm-form-group">
          <label class="adm-form-label" for="f-hero-sub">Subtitle / Deskripsi Hero</label>
          <textarea id="f-hero-sub" name="hero_subtitle" class="adm-form-textarea" rows="2"
                    placeholder="Kami siap melayani dengan sepenuh hati..."><?= htmlspecialchars($settings['hero_subtitle'] ?? 'Kami siap melayani dengan sepenuh hati. Kami memberikan pelayanan terbaik untuk perjalanan impian Anda bersama Travelica.') ?></textarea>
        </div>

        <!-- Hero Image -->
        <div class="adm-form-group">
          <label class="adm-form-label">Gambar Hero (Background)</label>
          <div style="display:flex;gap:16px;flex-wrap:wrap;align-items:flex-start;">
            <div style="flex:1;min-width:220px;">
              <label style="display:block;font-size:12.5px;color:#64748b;font-weight:600;margin-bottom:6px;">Upload Gambar Baru</label>
              <input type="file" id="f-hero-img-file" name="hero_image_file"
                     accept="image/jpeg,image/png,image/webp,image/gif"
                     class="adm-form-input" style="padding:8px;"
                     onchange="previewHeroUpload(this)" />
              <span class="adm-form-hint">Format: JPG, PNG, WebP. Ukuran disarankan: 1920×1080px.</span>
            </div>
            <div style="flex:1;min-width:220px;">
              <label style="display:block;font-size:12.5px;color:#64748b;font-weight:600;margin-bottom:6px;">Atau masukkan URL gambar</label>
              <input type="text" id="f-hero-img-url" name="hero_image" class="adm-form-input"
                     placeholder="assets/images/hero_bg.webp atau https://..."
                     value="<?= htmlspecialchars($settings['hero_image'] ?? 'assets/images/hero_bg.webp') ?>"
                     oninput="previewHeroUrl(this.value)" />
            </div>
          </div>
          <!-- Preview -->
          <div style="margin-top:12px;">
            <label class="adm-form-label">Preview Gambar Hero Saat Ini:</label>
            <div id="hero-img-preview-box" style="border-radius:12px;overflow:hidden;border:1.5px solid #e2e8f0;height:200px;background:#f8fafc;position:relative;">
              <img id="hero-img-preview" src="../<?= htmlspecialchars($settings['hero_image'] ?? 'assets/images/hero_bg.webp') ?>"
                   style="width:100%;height:100%;object-fit:cover;display:block;"
                   onerror="this.style.display='none'" />
              <div style="position:absolute;inset:0;background:linear-gradient(135deg,rgba(10,20,60,.55),rgba(30,50,100,.4));display:flex;flex-direction:column;align-items:flex-start;justify-content:flex-end;padding:16px 20px;pointer-events:none;">
                <p style="font-size:11px;font-weight:700;color:rgba(255,255,255,.75);margin:0 0 4px;letter-spacing:.1em;" id="prev-tagline">✈ <?= htmlspecialchars($settings['hero_tagline'] ?? 'Travel More, Worry Less') ?></p>
                <p style="font-size:20px;font-weight:800;color:#fff;margin:0;" id="prev-title"><?= nl2br(htmlspecialchars($settings['hero_title'] ?? "Explore The World\nWith Travelica")) ?></p>
              </div>
            </div>
          </div>
        </div>

        <div style="display:flex;gap:10px;flex-wrap:wrap;">
          <a href="../" target="_blank" class="btn btn-outline btn-sm" style="display:inline-flex;align-items:center;gap:6px;">
            <span>👁️</span> Lihat Beranda Live ↗
          </a>
        </div>
      </div>
    </div>
  </div>

  <!-- Card 1: Kontak & WhatsApp (2 Admins) -->
  <div class="adm-card">
    <div class="adm-card-header">
      <span class="adm-card-title">📞 Informasi Kontak &amp; 2 Admin WhatsApp</span>
    </div>
    <div class="adm-card-body">
      <div class="adm-form" style="gap:16px;">
        
        <!-- Admin 1 -->
        <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:12px;padding:14px 16px;">
          <div style="font-weight:700;color:#0f172a;font-size:13.5px;margin-bottom:10px;display:flex;align-items:center;gap:6px;">
            <span style="color:#16a34a;">🟢</span> Admin 1 WhatsApp
          </div>
          <div class="adm-form-row">
            <div class="adm-form-group">
              <label class="adm-form-label" for="f-wa1-name">Label / Nama Admin 1 *</label>
              <input type="text" id="f-wa1-name" name="whatsapp_admin1_name" class="adm-form-input"
                     placeholder="ADMIN 1 (DOROTHY)"
                     value="<?= htmlspecialchars($settings['whatsapp_admin1_name'] ?? 'ADMIN 1 (DOROTHY)') ?>" required />
            </div>
            <div class="adm-form-group">
              <label class="adm-form-label" for="f-wa1-num">Nomor WhatsApp Admin 1 *</label>
              <input type="text" id="f-wa1-num" name="whatsapp_admin1_number" class="adm-form-input"
                     placeholder="6282125423945"
                     value="<?= htmlspecialchars($settings['whatsapp_admin1_number'] ?? '6282125423945') ?>" required />
            </div>
          </div>
        </div>

        <!-- Admin 2 -->
        <div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:12px;padding:14px 16px;">
          <div style="font-weight:700;color:#0f172a;font-size:13.5px;margin-bottom:10px;display:flex;align-items:center;gap:6px;">
            <span style="color:#16a34a;">🟢</span> Admin 2 WhatsApp
          </div>
          <div class="adm-form-row">
            <div class="adm-form-group">
              <label class="adm-form-label" for="f-wa2-name">Label / Nama Admin 2 *</label>
              <input type="text" id="f-wa2-name" name="whatsapp_admin2_name" class="adm-form-input"
                     placeholder="ADMIN 2 (ANIS)"
                     value="<?= htmlspecialchars($settings['whatsapp_admin2_name'] ?? 'ADMIN 2 (ANIS)') ?>" required />
            </div>
            <div class="adm-form-group">
              <label class="adm-form-label" for="f-wa2-num">Nomor WhatsApp Admin 2 *</label>
              <input type="text" id="f-wa2-num" name="whatsapp_admin2_number" class="adm-form-input"
                     placeholder="087809226402"
                     value="<?= htmlspecialchars($settings['whatsapp_admin2_number'] ?? '087809226402') ?>" required />
            </div>
          </div>
        </div>

        <!-- Email & Address -->
        <div class="adm-form-row">
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-email">Email Perusahaan *</label>
            <input type="email" id="f-email" name="email" class="adm-form-input"
                   placeholder="info@travelica.id"
                   value="<?= htmlspecialchars($settings['email']) ?>" required />
            <span class="adm-form-hint">Email kontak yang ditampilkan di footer dan halaman kontak.</span>
          </div>
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-wa-fallback">Nomor WhatsApp Cadangan / Fallback</label>
            <input type="text" id="f-wa-fallback" name="whatsapp" class="adm-form-input"
                   placeholder="6282125423945"
                   value="<?= htmlspecialchars($settings['whatsapp'] ?? '6282125423945') ?>" />
            <span class="adm-form-hint">Digunakan jika sistem membutuhkan nomor tunggal.</span>
          </div>
        </div>

        <div class="adm-form-group">
          <label class="adm-form-label" for="f-address">Alamat Kantor</label>
          <textarea id="f-address" name="address" class="adm-form-textarea" rows="2"
                    placeholder="Jl. Jenderal Sudirman No.Kav 21, Jakarta Selatan..."><?= htmlspecialchars($settings['address']) ?></textarea>
        </div>
      </div>
    </div>
  </div>

  <!-- Card 2: Sosial Media -->
  <div class="adm-card">
    <div class="adm-card-header">
      <span class="adm-card-title">📱 Akun Sosial Media</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-ig">Instagram (Username atau Link)</label>
            <input type="text" id="f-ig" name="instagram" class="adm-form-input"
                   placeholder="@travelica.id atau https://instagram.com/travelica.id"
                   value="<?= htmlspecialchars($settings['instagram']) ?>" />
            <span class="adm-form-hint">Contoh: <code>@travelica.id</code> atau URL lengkap Instagram.</span>
          </div>

          <div class="adm-form-group">
            <label class="adm-form-label" for="f-tt">TikTok (Username atau Link)</label>
            <input type="text" id="f-tt" name="tiktok" class="adm-form-input"
                   placeholder="@travelica.id atau https://tiktok.com/@travelica.id"
                   value="<?= htmlspecialchars($settings['tiktok']) ?>" />
            <span class="adm-form-hint">Contoh: <code>@travelica.id</code> atau URL lengkap TikTok.</span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Card 3: Embed Google Maps -->
  <div class="adm-card">
    <div class="adm-card-header">
      <span class="adm-card-title">🗺️ Embed Google Maps (Halaman Kontak)</span>
    </div>
    <div class="adm-card-body">
      <div class="adm-form" style="gap:16px;">
        <div class="adm-form-group">
          <label class="adm-form-label" for="f-maps">Kode Iframe / Link Google Maps</label>
          <textarea id="f-maps" name="maps_embed" class="adm-form-textarea" rows="3"
                    placeholder='Contoh: &lt;iframe src="https://www.google.com/maps/embed?pb=..." ...&gt;&lt;/iframe&gt;'
                    oninput="updateMapPreview(this.value)"><?= htmlspecialchars($settings['maps_embed'] ?? '') ?></textarea>
          <span class="adm-form-hint">
            💡 <b>Cara Ambil:</b> Buka <b>Google Maps</b> ➔ Cari lokasi kantor ➔ Klik <b>Bagikan (Share)</b> ➔ Pilih tab <b>Sematkan peta (Embed a map)</b> ➔ Klik <b>SALIN HTML</b> lalu tempel di kolom ini.
          </span>
        </div>

        <!-- Live Map Preview -->
        <div class="adm-form-group">
          <label class="adm-form-label">Preview Peta Saat Ini:</label>
          <div id="map-preview-box" style="border-radius:8px;overflow:hidden;border:1.5px solid #e2e8f0;height:240px;background:#f8fafc;display:flex;align-items:center;justify-content:center;">
            <?= get_maps_embed_html() ?>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Card: Video Perjalanan (Beranda) -->
  <?php 
  $uploadedVideosList = get_travel_videos(true);
  $activeCount = count($uploadedVideosList);
  $firstVideo = $uploadedVideosList[0] ?? null;
  ?>
  <div class="adm-card">
    <div class="adm-card-header" style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:10px;">
      <span class="adm-card-title">🎬 Video Perjalanan (Beranda / Homepage)</span>
      <a href="videos.php" class="btn btn-primary btn-sm" style="display:inline-flex;align-items:center;gap:6px;">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg>
        Kelola &amp; Upload Video (<?= $activeCount ?> Aktif) ➔
      </a>
    </div>
    <div class="adm-card-body">
      <div class="adm-form" style="gap:16px;">
        
        <!-- Video Upload Info Box -->
        <div style="background:#f0fdf4;border:1.5px solid #bbf7d0;border-radius:12px;padding:16px 18px;display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap;">
          <div>
            <div style="font-weight:700;color:#166534;font-size:14px;margin-bottom:3px;display:flex;align-items:center;gap:6px;">
              <span>✅</span> Sistem Video Upload Mandiri Aktif
            </div>
            <div style="font-size:12.5px;color:#15803d;line-height:1.5;">
              Saat ini terdapat <b><?= $activeCount ?> video aktif</b>. Video diunggah langsung ke server dengan batas maksimal <b>50 MB per video</b> dan progress bar real-time.
            </div>
          </div>
          <a href="videos.php" class="btn btn-primary btn-sm" style="background:#16a34a;border-color:#16a34a;">
            + Tambah Video Baru
          </a>
        </div>

        <div class="adm-form-row">
          <div class="adm-form-group">
            <label class="adm-form-label" for="f-yt-tagline">Tagline / Eyebrow Video</label>
            <input type="text" id="f-yt-tagline" name="youtube_tagline" class="adm-form-input"
                   placeholder="VIDEO PERJALANAN"
                   value="<?= htmlspecialchars($settings['youtube_tagline'] ?? 'VIDEO PERJALANAN') ?>" />
          </div>

          <div class="adm-form-group">
            <label class="adm-form-label" for="f-yt-title">Judul Bagian Video</label>
            <input type="text" id="f-yt-title" name="youtube_title" class="adm-form-input"
                   placeholder="Lihat Keseruan Liburan Bersama Kami"
                   value="<?= htmlspecialchars($settings['youtube_title'] ?? 'Lihat Keseruan Liburan Bersama Kami') ?>" />
          </div>
        </div>

        <div class="adm-form-group">
          <label class="adm-form-label" for="f-yt-desc">Deskripsi Singkat Video</label>
          <textarea id="f-yt-desc" name="youtube_desc" class="adm-form-textarea" rows="2"
                    placeholder="Saksikan momen-momen tak terlupakan dan keseruan para traveler saat menjelajahi destinasi impian bersama Travelica."><?= htmlspecialchars($settings['youtube_desc'] ?? '') ?></textarea>
        </div>

        <!-- Video Preview -->
        <div class="adm-form-group">
          <label class="adm-form-label">Preview Video Utama Saat Ini:</label>
          <div style="border-radius:12px;overflow:hidden;border:1.5px solid #e2e8f0;max-width:680px;width:100%;aspect-ratio:16/9;background:#0f172a;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 16px rgba(0,0,0,.08);position:relative;">
            <?php if ($firstVideo): ?>
              <video src="../<?= htmlspecialchars($firstVideo['video_path']) ?>" 
                     poster="<?= !empty($firstVideo['thumbnail_path']) ? '../' . htmlspecialchars($firstVideo['thumbnail_path']) : '' ?>" 
                     controls 
                     preload="metadata" 
                     style="width:100%;height:100%;object-fit:cover;"></video>
            <?php else: ?>
              <div style="text-align:center;color:#94a3b8;padding:20px;">
                <div style="font-size:36px;margin-bottom:8px;">🎥</div>
                <div style="font-size:14px;font-weight:600;color:#f8fafc;">Belum ada video yang diunggah</div>
                <div style="font-size:12px;margin-top:4px;color:#94a3b8;">Klik tombol di bawah untuk mengunggah video pertama Anda.</div>
                <a href="videos.php" class="btn btn-primary btn-sm" style="margin-top:12px;display:inline-block;">Unggah Video Sekarang</a>
              </div>
            <?php endif; ?>
          </div>
        </div>

        <!-- Tour Gallery Link -->
        <div style="background:#f0f9ff;border:1.5px solid #bae6fd;border-radius:10px;padding:14px 18px;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;">
          <div>
            <div style="font-weight:700;color:#0369a1;font-size:13.5px;margin-bottom:2px;">📸 Slider Foto Tour di Bawah Video</div>
            <div style="font-size:12.5px;color:#0284c7;">Kelola foto-foto dokumentasi tour yang tampil dalam slider di bawah video ini.</div>
          </div>
          <a href="galeri.php" class="btn btn-primary btn-sm" style="background:#0284c7;border-color:#0284c7;">
            Kelola Foto Galeri ➔
          </a>
        </div>
      </div>
    </div>
  </div>


  <!-- Card 4: Footer & Tagline -->
  <div class="adm-card">
    <div class="adm-card-header">
      <span class="adm-card-title">📄 Teks Footer &amp; Hak Cipta</span>
    </div>
    <div class="adm-card-body">
      <div class="adm-form" style="gap:16px;">
        <div class="adm-form-group">
          <label class="adm-form-label" for="f-tagline">Tagline / Deskripsi Footer</label>
          <textarea id="f-tagline" name="footer_tagline" class="adm-form-textarea" rows="2"
                    placeholder="Agen perjalanan terpercaya untuk liburan impian Anda..."><?= htmlspecialchars($settings['footer_tagline']) ?></textarea>
        </div>

        <div class="adm-form-group">
          <label class="adm-form-label" for="f-copy">Teks Hak Cipta (Copyright)</label>
          <input type="text" id="f-copy" name="copyright" class="adm-form-input"
                 placeholder="© 2024 Travelica Agency. All rights reserved."
                 value="<?= htmlspecialchars($settings['copyright']) ?>" />
        </div>
      </div>
    </div>
  </div>

  <!-- Card 5: Syarat & Ketentuan (Terms & Conditions Modal) -->
  <div class="adm-card">
    <div class="adm-card-header">
      <span class="adm-card-title">📋 Syarat &amp; Ketentuan Perjalanan (Terms &amp; Conditions Popup)</span>
    </div>
    <div class="adm-card-body">
      <div class="adm-form" style="gap:16px;">
        <div class="adm-form-group">
          <label class="adm-form-label" for="f-terms">Isi Syarat &amp; Ketentuan</label>
          <textarea id="f-terms" name="terms_conditions" class="adm-form-textarea" rows="12" style="font-family:monospace;line-height:1.6;font-size:13px;"
                    placeholder="Tuliskan syarat &amp; ketentuan perjalanan di sini..."
                    oninput="updateTermsPreview(this.value)"><?= htmlspecialchars($settings['terms_conditions'] ?? '') ?></textarea>
          <span class="adm-form-hint">
            💡 Teks ini akan otomatis tampil dalam <b>popup modal</b> ketika pengunjung mengklik tombol <b>&quot;Lihat Syarat &amp; Ketentuan&quot;</b> pada halaman detail trip.<br>
            Format: Gunakan <code>1. JUDUL:</code> untuk heading bagian, dan <code>•</code> atau <code>-</code> untuk poin-poin. Pisahkan bagian dengan baris kosong.
          </span>
        </div>

        <!-- Live Preview -->
        <div class="adm-form-group">
          <label class="adm-form-label">Preview Tampilan Syarat &amp; Ketentuan:</label>
          <div id="terms-preview-box" style="border:1.5px solid #e2e8f0;border-radius:10px;padding:20px 24px;background:#fafafa;max-height:360px;overflow-y:auto;font-size:13.5px;line-height:1.7;">
            <div id="terms-preview-content" style="color:#374151;"></div>
          </div>
        </div>

        <div style="display:flex;gap:10px;flex-wrap:wrap;">
          <a href="../detail-trip?trip=korea-502n-oct" target="_blank" class="btn btn-outline btn-sm">
            👁️ Lihat di Detail Trip ↗
          </a>
        </div>
      </div>
    </div>
  </div>

  <!-- Live Link Preview & Test -->
  <div class="adm-card" style="border-left: 4px solid #0284c7;">
    <div class="adm-card-header">
      <span class="adm-card-title">🔗 Uji Direct Link Saat Ini</span>
    </div>
    <div class="adm-card-body">
      <p style="font-size:13.5px;color:#64748b;margin-bottom:14px;">
        Berikut adalah link aktif yang sedang terpasang di footer dan seluruh halaman website:
      </p>
      <div style="display:flex;gap:10px;flex-wrap:wrap;">
        <a href="<?= get_wa_link('', $settings['whatsapp_admin1_number'] ?? '6282125423945') ?>" target="_blank" class="btn btn-outline btn-sm" style="display:inline-flex;align-items:center;gap:6px;">
          <span>💬</span> Chat <?= htmlspecialchars($settings['whatsapp_admin1_name'] ?? 'Admin 1') ?> (<code><?= clean_wa_number($settings['whatsapp_admin1_number'] ?? '6282125423945') ?></code>) ↗
        </a>
        <a href="<?= get_wa_link('', $settings['whatsapp_admin2_number'] ?? '087809226402') ?>" target="_blank" class="btn btn-outline btn-sm" style="display:inline-flex;align-items:center;gap:6px;">
          <span>💬</span> Chat <?= htmlspecialchars($settings['whatsapp_admin2_name'] ?? 'Admin 2') ?> (<code><?= clean_wa_number($settings['whatsapp_admin2_number'] ?? '087809226402') ?></code>) ↗
        </a>
        <a href="<?= get_ig_link() ?>" target="_blank" class="btn btn-outline btn-sm" style="display:inline-flex;align-items:center;gap:6px;">
          <span>📸</span> Instagram (<code><?= htmlspecialchars($settings['instagram']) ?></code>) ↗
        </a>
        <a href="<?= get_tiktok_link() ?>" target="_blank" class="btn btn-outline btn-sm" style="display:inline-flex;align-items:center;gap:6px;">
          <span>🎵</span> TikTok (<code><?= htmlspecialchars($settings['tiktok']) ?></code>) ↗
        </a>
        <a href="<?= get_email_link() ?>" class="btn btn-outline btn-sm" style="display:inline-flex;align-items:center;gap:6px;">
          <span>✉️</span> Email (<code><?= htmlspecialchars($settings['email']) ?></code>) ↗
        </a>
      </div>
    </div>
  </div>

  <!-- Submit Buttons -->
  <div style="display:flex;gap:12px;padding-bottom:32px;">
    <button type="submit" class="btn btn-primary" style="padding:13px 28px;font-size:14px;">
      💾 Simpan Pengaturan
    </button>
    <a href="../#video" target="_blank" class="btn btn-outline" style="padding:13px 20px;font-size:14px;">
      🏠 Lihat Video di Beranda ↗
    </a>
    <a href="../kontak" target="_blank" class="btn btn-outline" style="padding:13px 20px;font-size:14px;">
      👁️ Lihat Halaman Kontak ↗
    </a>
  </div>

</form>

<script>
function updateMapPreview(val) {
  var box = document.getElementById('map-preview-box');
  if (!val.trim()) {
    box.innerHTML = '<span style="color:#94a3b8;font-size:13px;">Tempel kode iframe Google Maps di atas untuk melihat preview.</span>';
    return;
  }
  var src = '';
  var doubleMatch = val.match(/src="([^"]+)"/i);
  var singleMatch = val.match(/src='([^']+)'/i);
  if (doubleMatch) {
    src = doubleMatch[1];
  } else if (singleMatch) {
    src = singleMatch[1];
  } else if (val.trim().startsWith('http')) {
    src = val.trim();
  }

  if (src) {
    box.innerHTML = '<iframe src="' + src + '" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade" style="border:0;width:100%;height:100%;"></iframe>';
  } else {
    box.innerHTML = '<span style="color:#ef4444;font-size:13px;">Format iframe tidak valid. Pastikan menyalin seluruh kode iframe dari Google Maps.</span>';
  }
}

function parseYoutubeUrl(val) {
  val = val.trim();
  if (!val) return '';
  // Check iframe src
  var iframeMatch = val.match(/src=["']([^"']+)["']/i);
  if (iframeMatch) val = iframeMatch[1];

  // Check embed url
  var embedMatch = val.match(/(?:youtube\.com|youtube-nocookie\.com)\/embed\/([a-zA-Z0-9_-]{11})/i);
  if (embedMatch) return 'https://www.youtube.com/embed/' + embedMatch[1];

  // youtu.be/ID
  var shortMatch = val.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/i);
  if (shortMatch) return 'https://www.youtube.com/embed/' + shortMatch[1];

  // watch?v=ID
  var watchMatch = val.match(/[?&]v=([a-zA-Z0-9_-]{11})/i);
  if (watchMatch) return 'https://www.youtube.com/embed/' + watchMatch[1];

  // shorts/ID
  var shortsMatch = val.match(/youtube\.com\/shorts\/([a-zA-Z0-9_-]{11})/i);
  if (shortsMatch) return 'https://www.youtube.com/embed/' + shortsMatch[1];

  // 11 char ID
  if (/^[a-zA-Z0-9_-]{11}$/.test(val)) {
    return 'https://www.youtube.com/embed/' + val;
  }

  if (val.startsWith('http://') || val.startsWith('https://')) {
    return val;
  }
  return '';
}

function updateYoutubePreview(val) {
  var box = document.getElementById('yt-preview-box');
  if (!val.trim()) {
    box.innerHTML = '<span style="color:#94a3b8;font-size:13px;">Masukkan link video YouTube di atas untuk melihat preview.</span>';
    return;
  }
  var src = parseYoutubeUrl(val);
  if (src) {
    box.innerHTML = '<iframe src="' + src + '" title="Preview Video YouTube" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen style="width:100%;height:100%;border:0;"></iframe>';
  } else {
    box.innerHTML = '<span style="color:#ef4444;font-size:13px;">Format link YouTube tidak dikenali. Coba masukkan link seperti https://youtu.be/...</span>';
  }
}

// ── Hero Image Preview ─────────────────────────────────────────
function previewHeroUpload(input) {
  var file = input.files[0];
  if (!file) return;
  var reader = new FileReader();
  reader.onload = function(e) {
    var img = document.getElementById('hero-img-preview');
    if (img) { img.src = e.target.result; img.style.display = 'block'; }
    // Clear URL input if file chosen
    var urlInput = document.getElementById('f-hero-img-url');
    if (urlInput) urlInput.value = '';
  };
  reader.readAsDataURL(file);
}

function previewHeroUrl(val) {
  val = val.trim();
  if (!val) return;
  var img = document.getElementById('hero-img-preview');
  if (!img) return;
  // Prefix with ../ for admin paths to local assets
  var src = val.startsWith('http') ? val : '../' + val;
  img.src = src;
  img.style.display = 'block';
}

// Update live preview overlay text as admin types
document.addEventListener('DOMContentLoaded', function() {
  var taglineInput = document.getElementById('f-hero-tagline');
  var titleInput   = document.getElementById('f-hero-title');

  if (taglineInput) {
    taglineInput.addEventListener('input', function() {
      var el = document.getElementById('prev-tagline');
      if (el) el.textContent = '✈ ' + this.value;
    });
  }
  if (titleInput) {
    titleInput.addEventListener('input', function() {
      var el = document.getElementById('prev-title');
      if (el) el.innerHTML = this.value.replace(/\n/g, '<br>');
    });
  }

  // Initialize T&C preview on load
  var termsTA = document.getElementById('f-terms');
  if (termsTA && termsTA.value) updateTermsPreview(termsTA.value);
});

// ── Terms & Conditions Live Preview ───────────────────────────
function updateTermsPreview(text) {
  var box = document.getElementById('terms-preview-content');
  if (!box) return;
  if (!text.trim()) {
    box.innerHTML = '<span style="color:#94a3b8;font-size:13px;">Tulis syarat & ketentuan di textarea di atas untuk melihat preview.</span>';
    return;
  }

  var sections = text.split(/\n\s*\n/);
  var html = '';

  sections.forEach(function(section) {
    section = section.trim();
    if (!section) return;
    var lines = section.split('\n');
    var firstLine = lines[0].trim();

    // Check if heading (starts with number+dot or uppercase word + colon)
    if (/^(\d+\.|[A-Z\s]{4,}:|\*\*)/.test(firstLine)) {
      html += '<div style="margin-bottom:14px;">';
      html += '<div style="font-weight:800;color:#1e293b;font-size:14px;margin-bottom:6px;border-left:3px solid #2563eb;padding-left:8px;">' + escHtmlP(firstLine) + '</div>';
      if (lines.length > 1) {
        html += '<ul style="margin:0 0 0 16px;padding:0;list-style:disc;color:#374151;">';
        for (var i = 1; i < lines.length; i++) {
          var item = lines[i].trim();
          if (!item) continue;
          item = item.replace(/^[•\-\*]\s*/, '');
          html += '<li style="margin-bottom:4px;font-size:13px;">' + escHtmlP(item) + '</li>';
        }
        html += '</ul>';
      }
      html += '</div>';
    } else {
      html += '<p style="color:#374151;font-size:13px;margin-bottom:10px;">' + escHtmlP(section).replace(/\n/g, '<br>') + '</p>';
    }
  });

  box.innerHTML = html || '<span style="color:#94a3b8;">Tidak ada konten.</span>';
}

function escHtmlP(str) {
  return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
</script>

<?php adm_layout_end(); ?>

