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

ensure_videos_table();

// Handle AJAX Upload Video
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['action']) && $_GET['action'] === 'ajax_upload') {
    header('Content-Type: application/json; charset=utf-8');

    $maxBytes = 50 * 1024 * 1024; // 50 MB in bytes

    if (empty($_FILES['video_file']['name'])) {
        echo json_encode(['success' => false, 'message' => 'Silakan pilih file video yang ingin diunggah.']);
        exit;
    }

    $file = $_FILES['video_file'];

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $uploadErrors = [
            UPLOAD_ERR_INI_SIZE   => 'Ukuran file melebihi upload_max_filesize di server.',
            UPLOAD_ERR_FORM_SIZE  => 'Ukuran file melebihi form MAX_FILE_SIZE.',
            UPLOAD_ERR_PARTIAL    => 'File hanya terunggah sebagian.',
            UPLOAD_ERR_NO_FILE    => 'Tidak ada file yang dipilih.',
            UPLOAD_ERR_NO_TMP_DIR => 'Folder temporary server hilang.',
            UPLOAD_ERR_CANT_WRITE => 'Gagal menulis file ke disk server.',
            UPLOAD_ERR_EXTENSION  => 'Ekstensi PHP membatalkan upload file.',
        ];
        $msg = $uploadErrors[$file['error']] ?? 'Gagal mengunggah file (kode: ' . $file['error'] . ').';
        echo json_encode(['success' => false, 'message' => $msg]);
        exit;
    }

    if ($file['size'] > $maxBytes) {
        $uploadedMB = round($file['size'] / (1024 * 1024), 1);
        echo json_encode(['success' => false, 'message' => "Ukuran video ({$uploadedMB} MB) melebihi batas maksimal 50 MB."]);
        exit;
    }

    // Check extension & MIME
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowedExt = ['mp4', 'webm', 'ogg', 'mov'];
    if (!in_array($ext, $allowedExt, true)) {
        echo json_encode(['success' => false, 'message' => 'Format file video tidak didukung. Gunakan MP4, WebM, OGG, atau MOV.']);
        exit;
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime  = $finfo->file($file['tmp_name']);
    $allowedMimes = ['video/mp4', 'video/webm', 'video/ogg', 'video/quicktime', 'application/octet-stream'];
    if (!in_array($mime, $allowedMimes, true)) {
        echo json_encode(['success' => false, 'message' => 'MIME file video tidak valid (' . htmlspecialchars($mime) . ').']);
        exit;
    }

    $uploadDir = dirname(__DIR__) . '/assets/uploads/videos/';
    $coversDir = $uploadDir . 'covers/';
    if (!is_dir($uploadDir)) @mkdir($uploadDir, 0755, true);
    if (!is_dir($coversDir)) @mkdir($coversDir, 0755, true);

    $safeFileName = 'vid_' . uniqid('', true) . '.' . ($ext === 'mov' ? 'mp4' : $ext);
    $destVideoPath = $uploadDir . $safeFileName;

    if (!move_uploaded_file($file['tmp_name'], $destVideoPath)) {
        echo json_encode(['success' => false, 'message' => 'Gagal menyimpan file video ke server.']);
        exit;
    }

    $videoRelPath = 'assets/uploads/videos/' . $safeFileName;
    $thumbRelPath = null;

    // Process custom thumbnail upload if provided
    if (!empty($_FILES['custom_thumb']['name'])) {
        $thumbUpload = adm_upload_image('custom_thumb', 'videos/covers');
        if (empty($thumbUpload['error'])) {
            $thumbRelPath = $thumbUpload['path'];
        }
    }

    // Process auto thumbnail from canvas base64 if no custom thumbnail
    if (!$thumbRelPath && !empty($_POST['auto_thumbnail_base64'])) {
        $base64 = $_POST['auto_thumbnail_base64'];
        if (preg_match('/^data:image\/(\w+);base64,/', $base64, $type)) {
            $data = substr($base64, strpos($base64, ',') + 1);
            $decoded = base64_decode($data);
            if ($decoded !== false) {
                $thumbFileName = 'thumb_' . uniqid('', true) . '.jpg';
                $destThumb = $coversDir . $thumbFileName;
                if (file_put_contents($destThumb, $decoded)) {
                    $thumbRelPath = 'assets/uploads/videos/covers/' . $thumbFileName;
                }
            }
        }
    }

    $title       = trim($_POST['title'] ?? '') ?: 'Video Perjalanan ' . date('d/m/Y');
    $description = trim($_POST['description'] ?? '');
    $duration    = trim($_POST['duration'] ?? '');
    $fileSize    = $file['size'];
    $fileSizeStr = format_bytes($fileSize);

    // Get max sort_order
    $stmtOrder = $pdo->query("SELECT COALESCE(MAX(sort_order), 0) + 1 AS next_order FROM `videos`");
    $nextOrder = (int)$stmtOrder->fetchColumn();

    $stmtInsert = $pdo->prepare("INSERT INTO `videos` 
        (`title`, `description`, `video_path`, `thumbnail_path`, `file_size`, `file_size_formatted`, `duration`, `sort_order`, `is_active`)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)");
    
    $success = $stmtInsert->execute([
        $title,
        $description,
        $videoRelPath,
        $thumbRelPath,
        $fileSize,
        $fileSizeStr,
        $duration,
        $nextOrder
    ]);

    if ($success) {
        echo json_encode([
            'success' => true,
            'message' => 'Video berhasil diunggah!',
            'video_id' => $pdo->lastInsertId()
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Gagal mencatat data video ke database.']);
    }
    exit;
}

$errors = [];

// Handle standard POST actions (edit, delete, move, toggle)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postAction = $_POST['post_action'] ?? '';

    // DELETE VIDEO
    if ($postAction === 'delete') {
        $targetId = (int)($_POST['id'] ?? 0);
        if (delete_travel_video($targetId)) {
            $_SESSION['adm_toast'] = ['msg' => 'Video perjalanan berhasil dihapus.', 'type' => 'success'];
        } else {
            $_SESSION['adm_toast'] = ['msg' => 'Gagal menghapus video.', 'type' => 'error'];
        }
        header('Location: videos.php');
        exit;
    }

    // EDIT VIDEO DETAILS
    elseif ($postAction === 'edit') {
        $targetId    = (int)($_POST['id'] ?? 0);
        $title       = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $isActive    = isset($_POST['is_active']) ? 1 : 0;

        if (!$title) {
            $errors[] = 'Judul video tidak boleh kosong.';
        } else {
            $existing = get_travel_video_by_id($targetId);
            if ($existing) {
                $thumbPath = $existing['thumbnail_path'];

                // Check if new cover uploaded
                if (!empty($_FILES['custom_thumb']['name'])) {
                    $thumbUpload = adm_upload_image('custom_thumb', 'videos/covers', $thumbPath ?: '');
                    if (empty($thumbUpload['error'])) {
                        $thumbPath = $thumbUpload['path'];
                    } else {
                        $errors[] = $thumbUpload['error'];
                    }
                }

                if (empty($errors)) {
                    $stmt = $pdo->prepare("UPDATE `videos` SET `title` = ?, `description` = ?, `thumbnail_path` = ?, `is_active` = ? WHERE `id` = ?");
                    $stmt->execute([$title, $description, $thumbPath, $isActive, $targetId]);
                    $_SESSION['adm_toast'] = ['msg' => 'Data video berhasil diperbarui!', 'type' => 'success'];
                    header('Location: videos.php');
                    exit;
                }
            }
        }
    }

    // TOGGLE ACTIVE STATUS
    elseif ($postAction === 'toggle_active') {
        $targetId = (int)($_POST['id'] ?? 0);
        $stmt = $pdo->prepare("UPDATE `videos` SET `is_active` = 1 - `is_active` WHERE `id` = ?");
        $stmt->execute([$targetId]);
        $_SESSION['adm_toast'] = ['msg' => 'Status aktif video berhasil diubah.', 'type' => 'success'];
        header('Location: videos.php');
        exit;
    }

    // MOVE ORDER
    elseif ($postAction === 'move') {
        $targetId  = (int)($_POST['id'] ?? 0);
        $direction = $_POST['direction'] ?? '';
        $allVideos = get_travel_videos(false);

        $currentIndex = -1;
        foreach ($allVideos as $idx => $v) {
            if ((int)$v['id'] === $targetId) {
                $currentIndex = $idx;
                break;
            }
        }

        if ($currentIndex !== -1) {
            $swapIndex = ($direction === 'up') ? $currentIndex - 1 : $currentIndex + 1;
            if (isset($allVideos[$swapIndex])) {
                $currId = (int)$allVideos[$currentIndex]['id'];
                $swapId = (int)$allVideos[$swapIndex]['id'];

                $currOrder = (int)$allVideos[$currentIndex]['sort_order'];
                $swapOrder = (int)$allVideos[$swapIndex]['sort_order'];

                if ($currOrder === $swapOrder) {
                    $currOrder = $currentIndex;
                    $swapOrder = $swapIndex;
                }

                $pdo->prepare("UPDATE `videos` SET `sort_order` = ? WHERE `id` = ?")->execute([$swapOrder, $currId]);
                $pdo->prepare("UPDATE `videos` SET `sort_order` = ? WHERE `id` = ?")->execute([$currOrder, $swapId]);

                $_SESSION['adm_toast'] = ['msg' => 'Urutan video berhasil diperbarui!', 'type' => 'success'];
            }
        }
        header('Location: videos.php');
        exit;
    }
}

// Fetch all videos
$videos = get_travel_videos(false);
$totalVideos = count($videos);
$activeVideos = count(array_filter($videos, fn($v) => (int)$v['is_active'] === 1));

adm_layout_start('videos', 'Manajemen Video Perjalanan');
?>

<div class="adm-page-header">
  <div>
    <h1 class="adm-page-title">🎬 Video Perjalanan (Showcase Beranda)</h1>
    <p class="adm-page-sub">Kelola dan unggah video keseruan liburan yang ditampilkan secara interaktif dan smooth di halaman depan.</p>
  </div>
  <div style="display:flex;gap:10px;flex-wrap:wrap;">
    <button type="button" class="btn btn-primary btn-sm" onclick="openUploadModal()" style="display:inline-flex;align-items:center;gap:6px;">
      <svg width="16" height="16" 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>
      Unggah Video Baru
    </button>
    <a href="../#video" target="_blank" class="btn btn-outline btn-sm" style="display:inline-flex;align-items:center;gap:6px;">
      <span>👁️</span> Lihat di Beranda ↗
    </a>
  </div>
</div>

<!-- Info Banner -->
<div style="background:#eff6ff;border:1.5px solid #bfdbfe;border-radius:12px;padding:16px 20px;margin-bottom:24px;display:flex;align-items:flex-start;gap:14px;">
  <span style="font-size:24px;line-height:1;">💡</span>
  <div style="font-size:13.5px;color:#1e40af;line-height:1.6;">
    <strong>Ketentuan &amp; Panduan Upload Video:</strong>
    <ul style="margin:4px 0 0 18px;padding:0;">
      <li><b>Batas Ukuran:</b> Maksimal <b>50 MB</b> per file video (tervalidasi otomatis sebelum upload).</li>
      <li><b>Format Terbaik:</b> Disarankan format <b>MP4 (H.264)</b> atau <b>WebM</b> agar diputar lancar (smooth) tanpa jeda/lag di semua perangkat (Desktop &amp; HP).</li>
      <li><b>Banyak Video:</b> Anda dapat mengunggah banyak video. Pengunjung di beranda dapat menonton video utama dan memilih video lainnya melalui slider/playlist interaktif.</li>
      <li><b>Cover / Poster Otomatis:</b> Thumbnail poster diambil secara otomatis dari cuplikan awal video saat Anda memilih file.</li>
    </ul>
  </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; ?>

<!-- Stats Summary -->
<div style="display:grid;grid-template-columns:repeat(auto-fit, minmax(200px, 1fr));gap:16px;margin-bottom:24px;">
  <div style="background:#fff;padding:18px 20px;border-radius:12px;border:1.5px solid #e2e8f0;display:flex;align-items:center;gap:14px;">
    <div style="width:44px;height:44px;border-radius:10px;background:#e0f2fe;display:flex;align-items:center;justify-content:center;color:#0284c7;font-size:20px;">
      📹
    </div>
    <div>
      <div style="font-size:12px;color:#64748b;font-weight:600;text-transform:uppercase;">Total Video</div>
      <div style="font-size:22px;font-weight:800;color:#0f172a;"><?= $totalVideos ?> Video</div>
    </div>
  </div>

  <div style="background:#fff;padding:18px 20px;border-radius:12px;border:1.5px solid #e2e8f0;display:flex;align-items:center;gap:14px;">
    <div style="width:44px;height:44px;border-radius:10px;background:#dcfce7;display:flex;align-items:center;justify-content:center;color:#16a34a;font-size:20px;">
      ✅
    </div>
    <div>
      <div style="font-size:12px;color:#64748b;font-weight:600;text-transform:uppercase;">Video Aktif</div>
      <div style="font-size:22px;font-weight:800;color:#16a34a;"><?= $activeVideos ?> Video</div>
    </div>
  </div>

  <div style="background:#fff;padding:18px 20px;border-radius:12px;border:1.5px solid #e2e8f0;display:flex;align-items:center;gap:14px;">
    <div style="width:44px;height:44px;border-radius:10px;background:#fef3c7;display:flex;align-items:center;justify-content:center;color:#d97706;font-size:20px;">
      ⚡
    </div>
    <div>
      <div style="font-size:12px;color:#64748b;font-weight:600;text-transform:uppercase;">Batas Maksimal</div>
      <div style="font-size:22px;font-weight:800;color:#d97706;">50 MB / File</div>
    </div>
  </div>
</div>

<!-- Videos Grid -->
<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">Daftar Video Perjalanan (<?= $totalVideos ?>)</span>
    <button type="button" class="btn btn-primary btn-sm" onclick="openUploadModal()">
      + Tambah Video
    </button>
  </div>
  <div class="adm-card-body" style="padding:20px;">
    <?php if (empty($videos)): ?>
      <div style="text-align:center;padding:48px 20px;color:#64748b;">
        <div style="font-size:48px;margin-bottom:12px;">🎥</div>
        <h3 style="font-size:18px;font-weight:700;color:#1e293b;margin-bottom:6px;">Belum Ada Video Perjalanan</h3>
        <p style="font-size:14px;max-width:440px;margin:0 auto 20px;color:#64748b;">
          Silakan unggah video dokumentasi keseruan trip traveler Travelica untuk ditampilkan di beranda.
        </p>
        <button type="button" class="btn btn-primary btn-sm" onclick="openUploadModal()">
          + Unggah Video Pertama Sekarang
        </button>
      </div>
    <?php else: ?>
      <div style="display:grid;grid-template-columns:repeat(auto-fill, minmax(320px, 1fr));gap:20px;">
        <?php foreach ($videos as $index => $v): ?>
          <div style="background:#fff;border-radius:14px;border:1.5px solid #e2e8f0;overflow:hidden;display:flex;flex-direction:column;box-shadow:0 2px 8px rgba(0,0,0,0.04);transition:all .2s ease;">
            
            <!-- Video Thumbnail / Player Preview -->
            <div style="position:relative;background:#0f172a;aspect-ratio:16/9;overflow:hidden;">
              <?php if (!empty($v['thumbnail_path'])): ?>
                <img src="../<?= htmlspecialchars($v['thumbnail_path']) ?>" alt="<?= htmlspecialchars($v['title']) ?>" style="width:100%;height:100%;object-fit:cover;" />
              <?php else: ?>
                <video src="../<?= htmlspecialchars($v['video_path']) ?>" preload="metadata" style="width:100%;height:100%;object-fit:cover;"></video>
              <?php endif; ?>

              <!-- Play Overlay Button (Modal Preview) -->
              <button type="button" onclick="playVideoModal('../<?= htmlspecialchars($v['video_path']) ?>', '<?= htmlspecialchars(addslashes($v['title'])) ?>')" style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:52px;height:52px;border-radius:50%;background:rgba(255,255,255,0.9);border:none;box-shadow:0 8px 24px rgba(0,0,0,0.35);display:flex;align-items:center;justify-content:center;color:#1a73e8;font-size:20px;cursor:pointer;transition:transform .2s ease;">
                ▶
              </button>

              <!-- Badges -->
              <div style="position:absolute;bottom:10px;left:10px;display:flex;gap:6px;">
                <?php if (!empty($v['file_size_formatted'])): ?>
                  <span style="background:rgba(15,23,42,0.75);backdrop-filter:blur(4px);color:#fff;font-size:11px;font-weight:700;padding:3px 8px;border-radius:6px;">
                    💾 <?= htmlspecialchars($v['file_size_formatted']) ?>
                  </span>
                <?php endif; ?>
                <?php if (!empty($v['duration'])): ?>
                  <span style="background:rgba(15,23,42,0.75);backdrop-filter:blur(4px);color:#fff;font-size:11px;font-weight:700;padding:3px 8px;border-radius:6px;">
                    ⏱️ <?= htmlspecialchars($v['duration']) ?>
                  </span>
                <?php endif; ?>
              </div>

              <!-- Status Badge -->
              <div style="position:absolute;top:10px;right:10px;">
                <?php if ((int)$v['is_active'] === 1): ?>
                  <span style="background:#10b981;color:#fff;font-size:11px;font-weight:700;padding:3px 9px;border-radius:20px;box-shadow:0 2px 6px rgba(16,185,129,0.4);">
                    Aktif
                  </span>
                <?php else: ?>
                  <span style="background:#64748b;color:#fff;font-size:11px;font-weight:700;padding:3px 9px;border-radius:20px;">
                    Nonaktif
                  </span>
                <?php endif; ?>
              </div>
            </div>

            <!-- Video Info -->
            <div style="padding:16px;flex:1;display:flex;flex-direction:column;">
              <h3 style="font-size:16px;font-weight:700;color:#0f172a;margin:0 0 6px;line-height:1.35;">
                <?= htmlspecialchars($v['title']) ?>
              </h3>
              <?php if (!empty($v['description'])): ?>
                <p style="font-size:13px;color:#64748b;margin:0 0 14px;line-height:1.5;flex:1;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;">
                  <?= htmlspecialchars($v['description']) ?>
                </p>
              <?php else: ?>
                <div style="flex:1;"></div>
              <?php endif; ?>

              <!-- Actions -->
              <div style="display:flex;align-items:center;justify-content:space-between;padding-top:12px;border-top:1px solid #f1f5f9;margin-top:auto;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)$v['id'] ?>">
                    <input type="hidden" name="direction" value="up">
                    <button type="submit" class="btn btn-outline btn-sm" style="padding:4px 8px;" title="Pindah ke Atas" <?= $index === 0 ? 'disabled' : '' ?>>▲</button>
                  </form>
                  <form method="POST" style="display:inline;">
                    <input type="hidden" name="post_action" value="move">
                    <input type="hidden" name="id" value="<?= (int)$v['id'] ?>">
                    <input type="hidden" name="direction" value="down">
                    <button type="submit" class="btn btn-outline btn-sm" style="padding:4px 8px;" title="Pindah ke Bawah" <?= $index === $totalVideos - 1 ? 'disabled' : '' ?>>▼</button>
                  </form>
                </div>

                <div style="display:flex;align-items:center;gap:6px;">
                  <!-- Toggle Active -->
                  <form method="POST" style="display:inline;">
                    <input type="hidden" name="post_action" value="toggle_active">
                    <input type="hidden" name="id" value="<?= (int)$v['id'] ?>">
                    <button type="submit" class="btn btn-outline btn-sm" style="padding:5px 9px;font-size:12px;" title="<?= (int)$v['is_active'] === 1 ? 'Nonaktifkan Video' : 'Aktifkan Video' ?>">
                      <?= (int)$v['is_active'] === 1 ? '👁️ Sembunyikan' : '✅ Tampilkan' ?>
                    </button>
                  </form>

                  <!-- Edit button -->
                  <button type="button" class="btn btn-outline btn-sm" style="padding:5px 9px;font-size:12px;" onclick="openEditModal(<?= htmlspecialchars(json_encode($v)) ?>)">
                    ✏️ Edit
                  </button>

                  <!-- Delete button -->
                  <form method="POST" style="display:inline;" onsubmit="return confirm('Apakah Anda yakin ingin menghapus video ini secara permanen?');">
                    <input type="hidden" name="post_action" value="delete">
                    <input type="hidden" name="id" value="<?= (int)$v['id'] ?>">
                    <button type="submit" class="btn btn-danger btn-sm" style="padding:5px 9px;font-size:12px;background:#ef4444;border-color:#ef4444;" title="Hapus Video">
                      🗑️
                    </button>
                  </form>
                </div>

              </div>
            </div>

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

<!-- ============================================================
     MODAL UPLOAD VIDEO (WITH PROGRESS BAR & 50MB LIMIT)
============================================================ -->
<div id="uploadModal" 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:580px;width:100%;box-shadow:0 24px 60px rgba(0,0,0,0.25);border:1px solid #e2e8f0;overflow:hidden;position:relative;animation:admModalIn .25s cubic-bezier(.16,1,.3,1);">
    
    <!-- Modal Header -->
    <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> Unggah Video Perjalanan Baru
      </h3>
      <button type="button" onclick="closeUploadModal()" style="background:none;border:none;font-size:22px;color:#94a3b8;cursor:pointer;line-height:1;">&times;</button>
    </div>

    <!-- Modal Body -->
    <div style="padding:24px;">
      <form id="videoUploadForm" onsubmit="submitVideoUpload(event)">
        <input type="hidden" id="auto_thumbnail_base64" name="auto_thumbnail_base64" value="" />
        <input type="hidden" id="video_duration" name="duration" value="" />

        <!-- Title -->
        <div class="adm-form-group" style="margin-bottom:16px;">
          <label class="adm-form-label" for="up-title">Judul Video *</label>
          <input type="text" id="up-title" name="title" class="adm-form-input" placeholder="Contoh: Keseruan Musim Semi di Tokyo &amp; Kyoto" required />
        </div>

        <!-- Description -->
        <div class="adm-form-group" style="margin-bottom:16px;">
          <label class="adm-form-label" for="up-desc">Deskripsi Singkat (Opsional)</label>
          <textarea id="up-desc" name="description" class="adm-form-textarea" rows="2" placeholder="Tuliskan cerita singkat tentang momen keseruan di video ini..."></textarea>
        </div>

        <!-- File Upload Drag & Drop Zone -->
        <div class="adm-form-group" style="margin-bottom:16px;">
          <label class="adm-form-label">
            File Video * <span style="color:#ef4444;font-weight:700;">(Maksimal 50 MB)</span>
          </label>
          
          <div id="dropZone" style="border:2px dashed #cbd5e1;border-radius:12px;padding:26px 20px;text-align:center;background:#f8fafc;cursor:pointer;transition:all .2s ease;position:relative;"
               onclick="document.getElementById('videoFileInput').click()"
               ondragover="handleDragOver(event)"
               ondragleave="handleDragLeave(event)"
               ondrop="handleFileDrop(event)">
            
            <input type="file" id="videoFileInput" name="video_file" accept="video/mp4,video/webm,video/ogg,video/quicktime" style="display:none;" onchange="handleFileSelect(this)" />
            
            <div id="dropZonePrompt">
              <div style="font-size:36px;margin-bottom:8px;">📤</div>
              <div style="font-weight:700;font-size:14px;color:#1e293b;margin-bottom:4px;">Klik untuk memilih video atau seret file ke sini</div>
              <div style="font-size:12px;color:#64748b;">Format: MP4, WebM, MOV. <b>Maksimal 50 MB per video.</b></div>
            </div>

            <!-- Selected File Info -->
            <div id="selectedFileInfo" style="display:none;align-items:center;justify-content:center;gap:12px;text-align:left;">
              <div style="width:40px;height:40px;border-radius:8px;background:#e0f2fe;display:flex;align-items:center;justify-content:center;color:#0284c7;font-size:20px;flex-shrink:0;">
                🎬
              </div>
              <div style="flex:1;min-width:0;">
                <div id="selFileName" style="font-weight:700;font-size:13px;color:#0f172a;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;"></div>
                <div id="selFileSize" style="font-size:12px;color:#64748b;"></div>
              </div>
              <button type="button" onclick="event.stopPropagation(); resetSelectedVideo();" style="background:#fee2e2;border:none;color:#ef4444;border-radius:6px;padding:4px 8px;font-size:12px;cursor:pointer;font-weight:600;">
                Ganti
              </button>
            </div>

          </div>

          <!-- Alert for Size Over Limit -->
          <div id="sizeLimitAlert" style="display:none;margin-top:10px;padding:12px 14px;border-radius:8px;background:#fef2f2;border:1px solid #fecaca;color:#b91c1c;font-size:13px;font-weight:600;">
            ⚠️ Ukuran file melebihi batas maksimal 50 MB! Silakan pilih video lain dengan ukuran lebih kecil.
          </div>
        </div>

        <!-- Auto-Captured Thumbnail Preview -->
        <div id="thumbPreviewWrap" style="display:none;margin-bottom:16px;">
          <label class="adm-form-label" style="display:flex;align-items:center;justify-content:space-between;">
            <span>📸 Poster / Cover Video (Otomatis Diambil):</span>
            <span style="font-size:11px;color:#10b981;font-weight:600;">✓ Auto-Generated Frame</span>
          </label>
          <div style="position:relative;border-radius:10px;overflow:hidden;border:1.5px solid #e2e8f0;background:#0f172a;max-height:160px;aspect-ratio:16/9;margin-top:6px;">
            <img id="thumbPreviewImg" src="" alt="Thumbnail Preview" style="width:100%;height:100%;object-fit:cover;display:block;" />
          </div>
        </div>

        <!-- Optional Custom Cover Upload -->
        <div class="adm-form-group" style="margin-bottom:20px;">
          <label class="adm-form-label" for="custom_thumb">Ganti Cover dengan Gambar Custom (Opsional)</label>
          <input type="file" id="custom_thumb" name="custom_thumb" accept="image/jpeg,image/png,image/webp" class="adm-form-input" onchange="previewCustomCover(this)" />
          <span class="adm-form-hint">Jika tidak diisi, sistem otomatis menggunakan cuplikan frame video di atas.</span>
        </div>

        <!-- Real-Time Progress Bar Section -->
        <div id="uploadProgressContainer" style="display:none;margin-bottom:20px;background:#f8fafc;border:1.5px solid #e2e8f0;border-radius:12px;padding:16px;">
          <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;">
            <span id="progStatusLabel" style="font-size:13px;font-weight:700;color:#0f172a;display:flex;align-items:center;gap:6px;">
              <span class="adm-spinner" style="width:14px;height:14px;border:2px solid #cbd5e1;border-top-color:#1a73e8;border-radius:50%;display:inline-block;animation:spin 0.8s linear infinite;"></span>
              Mengunggah video...
            </span>
            <span id="progPercentLabel" style="font-size:14px;font-weight:800;color:#1a73e8;">0%</span>
          </div>

          <!-- Progress Bar Track -->
          <div style="background:#e2e8f0;border-radius:10px;height:12px;overflow:hidden;position:relative;">
            <div id="progBarFill" style="background:linear-gradient(90deg, #1a73e8, #38bdf8);height:100%;width:0%;border-radius:10px;transition:width .15s ease;box-shadow:0 0 10px rgba(26,115,232,0.5);"></div>
          </div>

          <!-- Transfer Stats -->
          <div style="display:flex;align-items:center;justify-content:space-between;margin-top:8px;font-size:12px;color:#64748b;">
            <span id="progSizeLabel">0 MB / 0 MB</span>
            <span id="progSpeedLabel">Menyiapkan koneksi...</span>
          </div>
        </div>

        <!-- Buttons -->
        <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" id="btnCancelUpload" class="btn btn-outline" onclick="cancelOrCloseUploadModal()">Batal</button>
          <button type="submit" id="btnSubmitUpload" class="btn btn-primary" style="display:inline-flex;align-items:center;gap:6px;">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="16 16 12 12 8 16"/><line x1="12" y1="12" x2="12" y2="21"/><path d="M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"/></svg>
            Mulai Unggah Video
          </button>
        </div>

      </form>
    </div>

  </div>
</div>

<!-- ============================================================
     MODAL EDIT VIDEO
============================================================ -->
<div id="editModal" 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;">
        ✏️ Edit Data Video Perjalanan
      </h3>
      <button type="button" onclick="closeEditModal()" 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" enctype="multipart/form-data">
        <input type="hidden" name="post_action" value="edit" />
        <input type="hidden" id="edit_id" name="id" value="" />

        <div class="adm-form-group" style="margin-bottom:16px;">
          <label class="adm-form-label" for="edit_title">Judul Video *</label>
          <input type="text" id="edit_title" name="title" class="adm-form-input" required />
        </div>

        <div class="adm-form-group" style="margin-bottom:16px;">
          <label class="adm-form-label" for="edit_desc">Deskripsi Singkat</label>
          <textarea id="edit_desc" name="description" class="adm-form-textarea" rows="2"></textarea>
        </div>

        <div class="adm-form-group" style="margin-bottom:16px;">
          <label class="adm-form-label" for="edit_custom_thumb">Ganti Cover / Poster Thumbnail (Opsional)</label>
          <input type="file" id="edit_custom_thumb" name="custom_thumb" accept="image/jpeg,image/png,image/webp" class="adm-form-input" />
          <div id="editThumbPreviewWrap" style="margin-top:8px;border-radius:8px;overflow:hidden;border:1px solid #e2e8f0;max-height:140px;aspect-ratio:16/9;display:none;">
            <img id="editThumbPreviewImg" src="" alt="Cover" style="width:100%;height:100%;object-fit:cover;" />
          </div>
        </div>

        <div class="adm-form-group" style="margin-bottom:24px;">
          <label style="display:flex;align-items:center;gap:10px;cursor:pointer;font-weight:600;font-size:14px;color:#1e293b;">
            <input type="checkbox" id="edit_is_active" name="is_active" value="1" style="width:18px;height:18px;accent-color:#1a73e8;" />
            Tampilkan video ini di halaman depan (Aktif)
          </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="closeEditModal()">Batal</button>
          <button type="submit" class="btn btn-primary">Simpan Perubahan</button>
        </div>

      </form>
    </div>

  </div>
</div>

<!-- ============================================================
     MODAL PREVIEW VIDEO PLAYER (IN ADMIN)
============================================================ -->
<div id="playerModal" style="display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(15,23,42,0.85);backdrop-filter:blur(6px);z-index:99999;align-items:center;justify-content:center;padding:20px;" onclick="closePlayerModal()">
  <div style="background:#0f172a;border-radius:18px;max-width:800px;width:100%;overflow:hidden;position:relative;box-shadow:0 30px 80px rgba(0,0,0,0.6);border:1px solid rgba(255,255,255,0.1);" onclick="event.stopPropagation()">
    
    <div style="padding:14px 20px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid rgba(255,255,255,0.08);background:rgba(15,23,42,0.6);">
      <h4 id="playerModalTitle" style="color:#ffffff;font-size:15px;font-weight:700;margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">Preview Video</h4>
      <button type="button" onclick="closePlayerModal()" style="background:none;border:none;color:#ffffff;font-size:24px;cursor:pointer;line-height:1;opacity:0.8;">&times;</button>
    </div>

    <div style="aspect-ratio:16/9;background:#000;display:flex;align-items:center;justify-content:center;">
      <video id="modalVideoPlayer" controls autoplay playsinline style="width:100%;height:100%;display:block;"></video>
    </div>

  </div>
</div>

<style>
@keyframes admModalIn {
  from { opacity: 0; transform: translateY(12px) scale(0.98); }
  to { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes spin {
  to { transform: rotate(360deg); }
}
</style>

<script>
const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB
let currentXHR = null;
let uploadStartTime = 0;

function openUploadModal() {
  document.getElementById('uploadModal').style.display = 'flex';
}

function closeUploadModal() {
  if (currentXHR) {
    if (confirm('Proses upload sedang berjalan. Apakah Anda yakin ingin membatalkan?')) {
      currentXHR.abort();
      currentXHR = null;
    } else {
      return;
    }
  }
  document.getElementById('uploadModal').style.display = 'none';
  resetSelectedVideo();
}

function cancelOrCloseUploadModal() {
  closeUploadModal();
}

function handleDragOver(e) {
  e.preventDefault();
  document.getElementById('dropZone').style.borderColor = '#1a73e8';
  document.getElementById('dropZone').style.background = '#eff6ff';
}

function handleDragLeave(e) {
  e.preventDefault();
  document.getElementById('dropZone').style.borderColor = '#cbd5e1';
  document.getElementById('dropZone').style.background = '#f8fafc';
}

function handleFileDrop(e) {
  e.preventDefault();
  handleDragLeave(e);
  if (e.dataTransfer && e.dataTransfer.files.length > 0) {
    const file = e.dataTransfer.files[0];
    validateAndSelectVideo(file);
  }
}

function handleFileSelect(input) {
  if (input.files && input.files.length > 0) {
    const file = input.files[0];
    validateAndSelectVideo(file);
  }
}

function validateAndSelectVideo(file) {
  const alertEl = document.getElementById('sizeLimitAlert');
  alertEl.style.display = 'none';

  // 1. Check size limit 50 MB
  if (file.size > MAX_FILE_SIZE) {
    const sizeMB = (file.size / (1024 * 1024)).toFixed(1);
    resetSelectedVideo();
    alertEl.innerHTML = `⚠️ Ukuran video <b>${sizeMB} MB</b> melebihi batas maksimal <b>50 MB</b>. Harap pilih video yang lebih kecil.`;
    alertEl.style.display = 'block';
    return;
  }

  // Display file info
  document.getElementById('dropZonePrompt').style.display = 'none';
  document.getElementById('selectedFileInfo').style.display = 'flex';
  document.getElementById('selFileName').textContent = file.name;
  document.getElementById('selFileSize').textContent = formatBytesJS(file.size);

  // Auto-fill title if empty
  const titleInput = document.getElementById('up-title');
  if (!titleInput.value.trim()) {
    const cleanName = file.name.replace(/\.[^/.]+$/, "").replace(/[-_]/g, " ");
    titleInput.value = cleanName.charAt(0).toUpperCase() + cleanName.slice(1);
  }

  // Extract thumbnail and duration using offscreen video
  captureVideoFrame(file);
}

function resetSelectedVideo(hideAlert = true) {
  document.getElementById('videoFileInput').value = '';
  document.getElementById('dropZonePrompt').style.display = 'block';
  document.getElementById('selectedFileInfo').style.display = 'none';
  document.getElementById('thumbPreviewWrap').style.display = 'none';
  document.getElementById('auto_thumbnail_base64').value = '';
  document.getElementById('video_duration').value = '';
  if (hideAlert) {
    document.getElementById('sizeLimitAlert').style.display = 'none';
  }
}

function captureVideoFrame(file) {
  const video = document.createElement('video');
  video.preload = 'metadata';
  video.src = URL.createObjectURL(file);
  video.muted = true;
  video.playsInline = true;

  video.onloadedmetadata = function() {
    // Format duration e.g. 01:45
    const mins = Math.floor(video.duration / 60);
    const secs = Math.floor(video.duration % 60);
    const durStr = String(mins).padStart(2, '0') + ':' + String(secs).padStart(2, '0');
    document.getElementById('video_duration').value = durStr;

    // Seek to 1s or half duration for capture
    video.currentTime = Math.min(1.0, video.duration / 2);
  };

  video.onseeked = function() {
    try {
      const canvas = document.createElement('canvas');
      canvas.width = Math.min(video.videoWidth || 1280, 1280);
      canvas.height = Math.min(video.videoHeight || 720, 720);
      const ctx = canvas.getContext('2d');
      ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
      const dataUrl = canvas.toDataURL('image/jpeg', 0.82);

      document.getElementById('auto_thumbnail_base64').value = dataUrl;
      document.getElementById('thumbPreviewImg').src = dataUrl;
      document.getElementById('thumbPreviewWrap').style.display = 'block';
    } catch (err) {
      console.warn('Canvas frame capture error:', err);
    }
  };
}

function previewCustomCover(input) {
  if (input.files && input.files[0]) {
    const reader = new FileReader();
    reader.onload = function(e) {
      document.getElementById('thumbPreviewImg').src = e.target.result;
      document.getElementById('thumbPreviewWrap').style.display = 'block';
    };
    reader.readAsDataURL(input.files[0]);
  }
}

function submitVideoUpload(e) {
  e.preventDefault();

  const fileInput = document.getElementById('videoFileInput');
  if (!fileInput.files || fileInput.files.length === 0) {
    alert('Silakan pilih file video terlebih dahulu.');
    return;
  }

  const file = fileInput.files[0];
  if (file.size > MAX_FILE_SIZE) {
    alert('Ukuran video melebihi batas maksimal 50 MB!');
    return;
  }

  const form = document.getElementById('videoUploadForm');
  const formData = new FormData(form);

  // Show progress container
  const progContainer = document.getElementById('uploadProgressContainer');
  const progFill = document.getElementById('progBarFill');
  const progPercent = document.getElementById('progPercentLabel');
  const progSize = document.getElementById('progSizeLabel');
  const progSpeed = document.getElementById('progSpeedLabel');
  const progStatus = document.getElementById('progStatusLabel');
  const btnSubmit = document.getElementById('btnSubmitUpload');
  const btnCancel = document.getElementById('btnCancelUpload');

  progContainer.style.display = 'block';
  btnSubmit.disabled = true;
  btnSubmit.style.opacity = '0.6';
  btnCancel.textContent = 'Batalkan Upload';

  uploadStartTime = Date.now();

  const xhr = new XMLHttpRequest();
  currentXHR = xhr;

  xhr.upload.onprogress = function(event) {
    if (event.lengthComputable) {
      const percent = Math.round((event.loaded / event.total) * 100);
      progFill.style.width = percent + '%';
      progPercent.textContent = percent + '%';

      const loadedMB = (event.loaded / (1024 * 1024)).toFixed(1);
      const totalMB = (event.total / (1024 * 1024)).toFixed(1);
      progSize.textContent = `${loadedMB} MB / ${totalMB} MB`;

      // Speed calculation
      const elapsedSec = (Date.now() - uploadStartTime) / 1000;
      if (elapsedSec > 0.5) {
        const speedMBps = (event.loaded / (1024 * 1024) / elapsedSec).toFixed(1);
        progSpeed.textContent = `Kecepatan: ~${speedMBps} MB/s`;
      }

      if (percent >= 100) {
        progStatus.innerHTML = '<span class="adm-spinner" style="width:14px;height:14px;border:2px solid #cbd5e1;border-top-color:#10b981;border-radius:50%;display:inline-block;animation:spin 0.8s linear infinite;"></span> Memproses &amp; menyimpan video di server...';
      }
    }
  };

  xhr.onload = function() {
    currentXHR = null;
    try {
      const res = JSON.parse(xhr.responseText);
      if (res.success) {
        progFill.style.width = '100%';
        progFill.style.background = '#10b981';
        progPercent.textContent = '100%';
        progPercent.style.color = '#10b981';
        progStatus.innerHTML = '✅ ' + (res.message || 'Video berhasil diunggah!');
        
        setTimeout(() => {
          showToast(res.message || 'Video berhasil diunggah!', 'success');
          window.location.reload();
        }, 600);
      } else {
        alert('Gagal mengunggah video: ' + (res.message || 'Terjadi kesalahan.'));
        resetProgressUI();
      }
    } catch (err) {
      alert('Respon server tidak valid saat memproses upload.');
      resetProgressUI();
    }
  };

  xhr.onerror = function() {
    currentXHR = null;
    alert('Terjadi kesalahan jaringan saat mengunggah video.');
    resetProgressUI();
  };

  xhr.onabort = function() {
    currentXHR = null;
    resetProgressUI();
  };

  xhr.open('POST', 'videos.php?action=ajax_upload', true);
  xhr.send(formData);
}

function resetProgressUI() {
  document.getElementById('uploadProgressContainer').style.display = 'none';
  document.getElementById('btnSubmitUpload').disabled = false;
  document.getElementById('btnSubmitUpload').style.opacity = '1';
  document.getElementById('btnCancelUpload').textContent = 'Batal';
}

function openEditModal(video) {
  document.getElementById('edit_id').value = video.id;
  document.getElementById('edit_title').value = video.title;
  document.getElementById('edit_desc').value = video.description || '';
  document.getElementById('edit_is_active').checked = (parseInt(video.is_active) === 1);

  const wrap = document.getElementById('editThumbPreviewWrap');
  const img = document.getElementById('editThumbPreviewImg');
  if (video.thumbnail_path) {
    img.src = '../' + video.thumbnail_path;
    wrap.style.display = 'block';
  } else {
    wrap.style.display = 'none';
  }

  document.getElementById('editModal').style.display = 'flex';
}

function closeEditModal() {
  document.getElementById('editModal').style.display = 'none';
}

function playVideoModal(src, title) {
  const player = document.getElementById('modalVideoPlayer');
  player.src = src;
  document.getElementById('playerModalTitle').textContent = title || 'Preview Video';
  document.getElementById('playerModal').style.display = 'flex';
  player.play().catch(() => {});
}

function closePlayerModal() {
  const player = document.getElementById('modalVideoPlayer');
  player.pause();
  player.src = '';
  document.getElementById('playerModal').style.display = 'none';
}

function formatBytesJS(bytes) {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}
</script>

<?php
adm_layout_end();
