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

$errors = [];
$gallery = get_tour_gallery();
$action = $_GET['action'] ?? 'list';
$editId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

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

    // ADD NEW PHOTO
    if ($postAction === 'add') {
        $title   = trim($_POST['title'] ?? '');
        $caption = trim($_POST['caption'] ?? '');

        if (empty($_FILES['photo']['name'])) {
            $errors[] = 'Silakan pilih file foto dokumentasi tour yang ingin diunggah.';
        } else {
            $upload = adm_upload_image('photo', 'gallery');
            if ($upload['error']) {
                $errors[] = $upload['error'];
            } else {
                $newId = time() . rand(10, 99);
                $gallery[] = [
                    'id'      => $newId,
                    'img'     => $upload['path'],
                    'title'   => $title ?: 'Dokumentasi Tour',
                    'caption' => $caption,
                ];
                save_tour_gallery($gallery);
                $_SESSION['adm_toast'] = ['msg' => 'Foto dokumentasi tour berhasil ditambahkan!', 'type' => 'success'];
                header('Location: galeri.php');
                exit;
            }
        }
    }

    // EDIT PHOTO
    elseif ($postAction === 'edit') {
        $targetId = (int)$_POST['id'];
        $title    = trim($_POST['title'] ?? '');
        $caption  = trim($_POST['caption'] ?? '');

        foreach ($gallery as &$item) {
            if ((int)$item['id'] === $targetId) {
                $existImg = $item['img'];
                if (!empty($_FILES['photo']['name'])) {
                    $upload = adm_upload_image('photo', 'gallery', $existImg);
                    if ($upload['error']) {
                        $errors[] = $upload['error'];
                        break;
                    }
                    $item['img'] = $upload['path'];
                }
                $item['title']   = $title ?: 'Dokumentasi Tour';
                $item['caption'] = $caption;
                break;
            }
        }
        unset($item);

        if (empty($errors)) {
            save_tour_gallery($gallery);
            $_SESSION['adm_toast'] = ['msg' => 'Data foto dokumentasi tour berhasil diperbarui!', 'type' => 'success'];
            header('Location: galeri.php');
            exit;
        }
    }

    // DELETE PHOTO
    elseif ($postAction === 'delete') {
        $targetId = (int)$_POST['id'];
        $newGallery = [];
        foreach ($gallery as $item) {
            if ((int)$item['id'] === $targetId) {
                // Delete physical file if under assets/uploads/
                if (!empty($item['img']) && str_starts_with($item['img'], 'assets/uploads/')) {
                    $fullPath = dirname(__DIR__) . '/' . $item['img'];
                    if (file_exists($fullPath)) @unlink($fullPath);
                }
            } else {
                $newGallery[] = $item;
            }
        }
        $gallery = $newGallery;
        save_tour_gallery($gallery);
        $_SESSION['adm_toast'] = ['msg' => 'Foto dokumentasi tour berhasil dihapus.', 'type' => 'success'];
        header('Location: galeri.php');
        exit;
    }

    // MOVE ORDER (UP / DOWN)
    elseif ($postAction === 'move') {
        $targetId = (int)$_POST['id'];
        $dir = $_POST['direction'] ?? '';
        $idx = -1;
        foreach ($gallery as $i => $item) {
            if ((int)$item['id'] === $targetId) {
                $idx = $i;
                break;
            }
        }

        if ($idx !== -1) {
            if ($dir === 'up' && $idx > 0) {
                $temp = $gallery[$idx - 1];
                $gallery[$idx - 1] = $gallery[$idx];
                $gallery[$idx] = $temp;
            } elseif ($dir === 'down' && $idx < count($gallery) - 1) {
                $temp = $gallery[$idx + 1];
                $gallery[$idx + 1] = $gallery[$idx];
                $gallery[$idx] = $temp;
            }
            save_tour_gallery($gallery);
            $_SESSION['adm_toast'] = ['msg' => 'Urutan foto berhasil diperbarui!', 'type' => 'success'];
            header('Location: galeri.php');
            exit;
        }
    }
}

// Find item for edit mode
$editItem = null;
if ($action === 'edit' && $editId) {
    foreach ($gallery as $g) {
        if ((int)$g['id'] === $editId) {
            $editItem = $g;
            break;
        }
    }
}

adm_layout_start('galeri', 'Manajemen Galeri Foto Tour');
?>

<div class="adm-page-header">
  <div>
    <h1 class="adm-page-title">📸 Galeri Foto Tour (Slider Beranda)</h1>
    <p class="adm-page-sub">Kelola foto-foto dokumentasi keseruan tour yang ditampilkan dalam slider foto di bawah video beranda.</p>
  </div>
  <div style="display:flex;gap:10px;flex-wrap:wrap;">
    <a href="../index.php#video" target="_blank" class="btn btn-outline btn-sm" style="display:inline-flex;align-items:center;gap:6px;">
      <span>👁️</span> Lihat Slider di Beranda ↗
    </a>
  </div>
</div>

<?php if (!empty($errors)): ?>
  <div class="adm-alert adm-alert-danger" style="margin-bottom:20px;padding:14px 18px;border-radius:10px;background:#fef2f2;border:1px solid #fecaca;color:#991b1b;">
    <strong>Terjadi kesalahan:</strong>
    <ul style="margin:6px 0 0 18px;">
      <?php foreach ($errors as $err): ?>
        <li><?= htmlspecialchars($err) ?></li>
      <?php endforeach; ?>
    </ul>
  </div>
<?php endif; ?>

<div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(320px, 1fr));gap:24px;align-items:start;">

  <!-- FORM: Upload / Edit Photo -->
  <div class="adm-card">
    <div class="adm-card-header">
      <span class="adm-card-title">
        <?= $editItem ? '✏️ Edit Foto Dokumentasi' : '➕ Upload Foto Tour Baru' ?>
      </span>
      <?php if ($editItem): ?>
        <a href="galeri.php" class="btn btn-outline btn-sm">Batal Edit</a>
      <?php endif; ?>
    </div>
    <div class="adm-card-body">
      <form method="POST" enctype="multipart/form-data" class="adm-form" style="gap:16px;">
        <input type="hidden" name="post_action" value="<?= $editItem ? 'edit' : 'add' ?>" />
        <?php if ($editItem): ?>
          <input type="hidden" name="id" value="<?= (int)$editItem['id'] ?>" />
        <?php endif; ?>

        <!-- File Upload -->
        <div class="adm-form-group">
          <label class="adm-form-label" for="f-photo">
            File Foto Tour <?= $editItem ? '(Kosongkan jika tidak diganti)' : '*' ?>
          </label>
          <input type="file" id="f-photo" name="photo" class="adm-form-input" accept="image/jpeg,image/png,image/webp" <?= $editItem ? '' : 'required' ?> onchange="previewUploadImage(this)" />
          <span class="adm-form-hint">Format didukung: JPG, PNG, WebP. Otomatis dikonversi & dikompresi agar loading web cepat.</span>
          
          <!-- Image Preview -->
          <div id="upload-preview-wrap" style="margin-top:12px;border-radius:10px;overflow:hidden;border:1.5px solid #e2e8f0;max-height:220px;display:<?= ($editItem && !empty($editItem['img'])) ? 'block' : 'none' ?>;background:#f8fafc;">
            <img id="upload-preview-img" src="<?= ($editItem && !empty($editItem['img'])) ? '../' . htmlspecialchars($editItem['img']) : '' ?>" alt="Preview" style="width:100%;height:100%;object-fit:cover;display:block;" />
          </div>
        </div>

        <!-- Title -->
        <div class="adm-form-group">
          <label class="adm-form-label" for="f-title">Judul / Lokasi Foto *</label>
          <input type="text" id="f-title" name="title" class="adm-form-input"
                 placeholder="Contoh: Dokumentasi Tour Jepang Sakura"
                 value="<?= htmlspecialchars($editItem['title'] ?? '') ?>" required />
        </div>

        <!-- Caption -->
        <div class="adm-form-group">
          <label class="adm-form-label" for="f-caption">Keterangan / Deskripsi Singkat</label>
          <textarea id="f-caption" name="caption" class="adm-form-textarea" rows="3"
                    placeholder="Contoh: Momen tak terlupakan rombongan traveler Travelica menikmati musim semi sakura di Tokyo..."><?= htmlspecialchars($editItem['caption'] ?? '') ?></textarea>
        </div>

        <button type="submit" class="btn btn-primary" style="padding:12px 24px;font-size:14px;font-weight:700;">
          <?= $editItem ? '💾 Simpan Perubahan Foto' : '📤 Upload ke Galeri Slider' ?>
        </button>
      </form>
    </div>
  </div>

  <!-- LIST: Current Gallery Photos -->
  <div class="adm-card" style="grid-column: span 1 / -1;">
    <div class="adm-card-header">
      <span class="adm-card-title">🖼️ Daftar Foto Galeri Tour Aktif (<?= count($gallery) ?>)</span>
    </div>
    <div class="adm-card-body">
      <?php if (empty($gallery)): ?>
        <div style="text-align:center;padding:40px 20px;color:#94a3b8;">
          <div style="font-size:42px;margin-bottom:10px;">📸</div>
          <p style="font-size:14px;margin:0;">Belum ada foto tour yang diunggah. Silakan upload foto pertama di form atas.</p>
        </div>
      <?php else: ?>
        <div style="display:grid;grid-template-columns:repeat(auto-fill, minmax(280px, 1fr));gap:20px;">
          <?php foreach ($gallery as $index => $item): ?>
            <div style="background:#ffffff;border:1.5px solid #e2e8f0;border-radius:14px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.04);display:flex;flex-direction:column;transition:transform .2s ease, box-shadow .2s ease;" onmouseover="this.style.boxShadow='0 8px 20px rgba(0,0,0,0.08)';this.style.transform='translateY(-2px)'" onmouseout="this.style.boxShadow='0 2px 8px rgba(0,0,0,0.04)';this.style.transform='none'">
              
              <!-- Thumbnail -->
              <div style="width:100%;height:180px;position:relative;background:#0f172a;overflow:hidden;">
                <img src="../<?= htmlspecialchars($item['img']) ?>" alt="<?= htmlspecialchars($item['title']) ?>" style="width:100%;height:100%;object-fit:cover;display:block;" onerror="this.src='../assets/images/hero_bg.webp'" />
                <span style="position:absolute;top:10px;left:10px;background:rgba(15,23,42,0.75);color:#fff;font-size:11px;font-weight:800;padding:3px 8px;border-radius:6px;backdrop-filter:blur(4px);">
                  #<?= $index + 1 ?>
                </span>
              </div>

              <!-- Content Info -->
              <div style="padding:16px;flex-grow:1;display:flex;flex-direction:column;justify-content:space-between;">
                <div>
                  <h4 style="font-size:15px;font-weight:700;color:#0f172a;margin:0 0 6px;line-height:1.35;">
                    <?= htmlspecialchars($item['title']) ?>
                  </h4>
                  <?php if (!empty($item['caption'])): ?>
                    <p style="font-size:12.5px;color:#64748b;margin:0;line-height:1.5;">
                      <?= htmlspecialchars($item['caption']) ?>
                    </p>
                  <?php endif; ?>
                </div>

                <!-- Actions -->
                <div style="margin-top:16px;padding-top:12px;border-top:1px solid #f1f5f9;display:flex;align-items:center;justify-content:space-between;gap:8px;">
                  
                  <!-- Order buttons -->
                  <div style="display:flex;gap:4px;">
                    <form method="POST" style="display:inline;">
                      <input type="hidden" name="post_action" value="move" />
                      <input type="hidden" name="id" value="<?= (int)$item['id'] ?>" />
                      <input type="hidden" name="direction" value="up" />
                      <button type="submit" class="btn btn-outline btn-sm" style="padding:4px 8px;font-size:12px;" title="Geser ke Kiri/Atas" <?= $index === 0 ? 'disabled style="opacity:0.4;cursor:not-allowed;"' : '' ?>>
                        ◀
                      </button>
                    </form>
                    <form method="POST" style="display:inline;">
                      <input type="hidden" name="post_action" value="move" />
                      <input type="hidden" name="id" value="<?= (int)$item['id'] ?>" />
                      <input type="hidden" name="direction" value="down" />
                      <button type="submit" class="btn btn-outline btn-sm" style="padding:4px 8px;font-size:12px;" title="Geser ke Kanan/Bawah" <?= $index === count($gallery) - 1 ? 'disabled style="opacity:0.4;cursor:not-allowed;"' : '' ?>>
                        ▶
                      </button>
                    </form>
                  </div>

                  <!-- Edit & Delete -->
                  <div style="display:flex;gap:6px;">
                    <a href="galeri.php?action=edit&id=<?= (int)$item['id'] ?>" class="btn btn-outline btn-sm" style="font-size:12px;padding:4px 10px;">
                      ✏️ Edit
                    </a>
                    <button type="button" class="btn btn-sm" style="background:#fee2e2;color:#dc2626;border:1px solid #fecaca;font-size:12px;padding:4px 10px;cursor:pointer;border-radius:6px;" onclick="confirmDeletePhoto(<?= (int)$item['id'] ?>, '<?= htmlspecialchars(addslashes($item['title'])) ?>')">
                      🗑️ Hapus
                    </button>
                  </div>

                </div>

              </div>

            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>
  </div>

</div>

<!-- Delete Confirmation Modal / Form -->
<form id="delete-photo-form" method="POST" style="display:none;">
  <input type="hidden" name="post_action" value="delete" />
  <input type="hidden" name="id" id="delete-photo-id" value="" />
</form>

<script>
function previewUploadImage(input) {
  var wrap = document.getElementById('upload-preview-wrap');
  var img = document.getElementById('upload-preview-img');
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      img.src = e.target.result;
      wrap.style.display = 'block';
    };
    reader.readAsDataURL(input.files[0]);
  }
}

function confirmDeletePhoto(id, title) {
  if (confirm('Yakin ingin menghapus foto "' + title + '" dari galeri tour slider?')) {
    document.getElementById('delete-photo-id').value = id;
    document.getElementById('delete-photo-form').submit();
  }
}
</script>

<?php adm_layout_end(); ?>
