| Server IP : 127.0.0.1 / Your IP : 192.168.99.1 Web Server : Apache/2.4.35 (Win64) OpenSSL/1.1.1b mod_fcgid/2.3.9 System : Windows NT WIN-JEJMB9EN0L0 10.0 build 14393 (Windows Server 2016) AMD64 User : Administrator ( 0) PHP Version : 7.4.33 Disable Function : NONE MySQL : OFF | cURL : ON | WGET : OFF | Perl : OFF | Python : OFF | Sudo : OFF | Pkexec : OFF Directory : /bpkd/admin/ |
Upload File : |
<?php
$page_title = 'Manajemen Media Galeri';
require_once 'config/database.php';
require_once '../includes/config.php';
require_once 'includes/init.php';
requireLogin();
// =====================================================
// HELPER: createSlug fallback
// =====================================================
if (!function_exists('createSlug')) {
function createSlug($str) {
$str = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $str)));
return trim($str, '-');
}
}
// =====================================================
// HELPER: getYouTubeId
// =====================================================
if (!function_exists('getYouTubeId')) {
function getYouTubeId($url) {
if (empty($url)) return '';
// Pola yang didukung:
// - youtube.com/watch?v=ID
// - youtu.be/ID
// - youtube.com/embed/ID
// - youtube.com/shorts/ID
// - youtube.com/live/ID
// - youtube.com/v/ID
// - m.youtube.com/...
// - youtube-nocookie.com/embed/ID
$pattern = '~
(?:youtube(?:-nocookie)?\.com/
(?:
(?:[^/]+/.+/) # user/channel path
|(?:v|e(?:mbed)?|shorts|live)/ # v/, embed/, shorts/, live/
|.*[?&]v= # ?v= atau &v=
)
|youtu\.be/
)
([A-Za-z0-9_-]{11}) # YouTube ID = 11 karakter
~x';
if (preg_match($pattern, $url, $matches)) {
return $matches[1];
}
return '';
}
}
// =====================================================
// KONFIGURASI UPLOAD
// =====================================================
$target_dir = dirname(__DIR__) . "/uploads/gallery/";
$allowed_image_types = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$allowed_video_types = ['mp4', 'webm', 'ogg'];
$max_file_size = 10 * 1024 * 1024; // 10MB
$max_image_size = 5 * 1024 * 1024; // 5MB
if (!file_exists($target_dir)) {
mkdir($target_dir, 0777, true);
}
$success_message = null;
$error_message = null;
// =====================================================
// HANDLE MULTI UPLOAD
// =====================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_multi'])) {
$album_id = isset($_POST['album_id']) ? (int)$_POST['album_id'] : 0;
$title_prefix = sanitize($_POST['title_prefix'] ?? '');
$category = sanitize($_POST['category'] ?? '');
$status = sanitize($_POST['status'] ?? 'active');
$featured = isset($_POST['featured']) ? 1 : 0;
$uploaded = 0;
$failed = 0;
// Validasi album_id
if ($album_id > 0) {
$check_album = $conn->query("SELECT id FROM albums WHERE id = $album_id");
if (!$check_album || $check_album->num_rows == 0) {
$album_id = 0;
}
}
if (isset($_FILES['image_files']) && is_array($_FILES['image_files']['name'])) {
$files = $_FILES['image_files'];
$file_count = count($files['name']);
for ($i = 0; $i < $file_count; $i++) {
if ($files['error'][$i] != 0) continue;
$file_name = $files['name'][$i];
$file_tmp = $files['tmp_name'][$i];
$file_size = $files['size'][$i];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
if (!in_array($file_ext, $allowed_image_types)) { $failed++; continue; }
if ($file_size > $max_image_size) { $failed++; continue; }
$new_filename = time() . '_' . uniqid() . '.' . $file_ext;
$target_file = $target_dir . $new_filename;
if (move_uploaded_file($file_tmp, $target_file)) {
$title = !empty($title_prefix) ? $title_prefix . ' ' . ($i + 1) : $file_name;
$filepath = 'uploads/gallery/' . $new_filename;
$query = "INSERT INTO gallery (album_id, title, description, image, category, type, status, featured, created_at)
VALUES ($album_id, '$title', '', '$filepath', '$category', 'image', '$status', $featured, NOW())";
if ($conn->query($query)) {
$uploaded++;
} else {
$failed++;
}
} else {
$failed++;
}
}
}
if ($uploaded > 0) {
$success_message = "Berhasil upload $uploaded file" . ($uploaded > 1 ? '!' : '!');
}
if ($failed > 0) {
$error_message = "$failed file gagal diupload.";
}
if ($uploaded == 0 && $failed == 0) {
$error_message = "Tidak ada file yang dipilih.";
}
}
// =====================================================
// HANDLE SINGLE UPLOAD
// =====================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload'])) {
$type = $_POST['type'] ?? 'image';
$category = sanitize($_POST['category'] ?? '');
$status = sanitize($_POST['status'] ?? 'active');
$featured = isset($_POST['featured']) ? 1 : 0;
$album_id = isset($_POST['album_id']) ? (int)$_POST['album_id'] : 0;
$video_url = sanitize($_POST['video_url'] ?? '');
if ($album_id > 0) {
$check_album = $conn->query("SELECT id FROM albums WHERE id = $album_id");
if (!$check_album || $check_album->num_rows == 0) $album_id = 0;
}
$errors = [];
// ---------- VIDEO (YouTube) ----------
if ($type == 'video') {
$title = sanitize($_POST['video_title'] ?? '');
if (empty($title)) $errors[] = "Judul video wajib diisi.";
if (empty($video_url)) $errors[] = "URL video wajib diisi.";
if (empty($errors)) {
$video_id = getYouTubeId($video_url);
if (empty($video_id)) {
$errors[] = "URL YouTube tidak valid. Gunakan format:
https://www.youtube.com/watch?v=ID,
https://youtu.be/ID, atau
https://www.youtube.com/shorts/ID";
} else {
// Simpan URL embed yang bisa diputar di <iframe>
$embed_url = 'https://www.youtube.com/embed/' . $video_id;
$thumbnail = 'https://img.youtube.com/vi/' . $video_id . '/hqdefault.jpg';
// Simpan video_id + embed_url + thumbnail di kolom yang tepat
$filename = $video_id; // simpan ID asli, bukan dummy
$query = "INSERT INTO gallery
(album_id, title, description, image, category, type, video_url, status, featured, created_at)
VALUES
($album_id, '$title', '', '$thumbnail', '$category', 'video', '$embed_url', '$status', $featured, NOW())";
if ($conn->query($query)) {
$success_message = "Video berhasil ditambahkan!";
} else {
$errors[] = "Gagal menyimpan video: " . $conn->error;
}
}
}
if (!empty($errors)) $error_message = implode('<br>', $errors);
}
// ---------- IMAGE (Single) ----------
elseif ($type == 'image') {
$title = sanitize($_POST['single_title'] ?? '');
if (empty($title)) {
$errors[] = "Judul gambar wajib diisi.";
}
if (!isset($_FILES['single_image_file']) || $_FILES['single_image_file']['error'] != 0) {
$errors[] = "Silakan pilih file gambar.";
}
if (empty($errors)) {
$file = $_FILES['single_image_file'];
$file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$file_size = $file['size'];
if (!in_array($file_ext, $allowed_image_types)) {
$errors[] = "Tipe file tidak diizinkan. Gunakan: " . implode(', ', $allowed_image_types);
}
if ($file_size > $max_image_size) {
$errors[] = "Ukuran file maksimal " . ($max_image_size / 1024 / 1024) . "MB";
}
if (empty($errors)) {
$new_filename = time() . '_' . uniqid() . '.' . $file_ext;
$target_file = $target_dir . $new_filename;
if (move_uploaded_file($file['tmp_name'], $target_file)) {
$filepath = 'uploads/gallery/' . $new_filename;
$description = sanitize($_POST['single_description'] ?? '');
$query = "INSERT INTO gallery (album_id, title, description, image, category, type, status, featured, created_at)
VALUES ($album_id, '$title', '$description', '$filepath', '$category', 'image', '$status', $featured, NOW())";
if ($conn->query($query)) {
$success_message = "Gambar berhasil diupload!";
} else {
$errors[] = "Gagal menyimpan ke database: " . $conn->error;
}
} else {
$errors[] = "Gagal mengupload file.";
}
}
}
} else {
$errors[] = "Tipe upload tidak valid.";
}
if (!empty($errors)) {
$error_message = implode('<br>', $errors);
}
}
// =====================================================
// HANDLE TAMBAH ALBUM
// =====================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_album'])) {
$name = sanitize($_POST['name']);
$description = sanitize($_POST['description']);
$slug = createSlug($name);
$check = $conn->query("SELECT id FROM albums WHERE slug = '$slug'");
if ($check && $check->num_rows > 0) {
$slug .= '-' . time();
}
$query = "INSERT INTO albums (name, slug, description) VALUES ('$name', '$slug', '$description')";
if ($conn->query($query)) {
$success_message = "Album '$name' berhasil dibuat!";
} else {
$error_message = "Gagal membuat album: " . $conn->error;
}
}
// =====================================================
// HANDLE EDIT ALBUM
// =====================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit_album'])) {
$id = (int)$_POST['id'];
$name = sanitize($_POST['name']);
$description = sanitize($_POST['description']);
$status = sanitize($_POST['status']);
$query = "UPDATE albums SET name = '$name', description = '$description', status = '$status' WHERE id = $id";
if ($conn->query($query)) {
$success_message = "Album berhasil diupdate!";
} else {
$error_message = "Gagal mengupdate album: " . $conn->error;
}
}
// =====================================================
// HANDLE DELETE ALBUM
// =====================================================
if (isset($_GET['delete_album'])) {
$id = (int)$_GET['delete_album'];
$conn->query("UPDATE gallery SET album_id = NULL WHERE album_id = $id");
if ($conn->query("DELETE FROM albums WHERE id = $id")) {
$success_message = "Album berhasil dihapus!";
} else {
$error_message = "Gagal menghapus album: " . $conn->error;
}
}
// =====================================================
// HANDLE EDIT GALLERY ITEM
// =====================================================
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['edit'])) {
$id = (int)$_POST['id'];
$title = sanitize($_POST['title']);
$description = sanitize($_POST['description']);
$category = sanitize($_POST['category']);
$status = sanitize($_POST['status']);
$featured = isset($_POST['featured']) ? 1 : 0;
$album_id = isset($_POST['album_id']) ? (int)$_POST['album_id'] : 0;
$query = "UPDATE gallery SET
title = '$title',
description = '$description',
category = '$category',
status = '$status',
featured = $featured,
album_id = $album_id
WHERE id = $id";
if ($conn->query($query)) {
$success_message = "Data berhasil diupdate!";
} else {
$error_message = "Gagal mengupdate: " . $conn->error;
}
}
// =====================================================
// HANDLE DELETE GALLERY ITEM
// =====================================================
if (isset($_GET['delete'])) {
$id = (int)$_GET['delete'];
$item = $conn->query("SELECT * FROM gallery WHERE id = $id")->fetch_assoc();
if ($item && $item['type'] == 'image' && !empty($item['image'])) {
$file_path = dirname(__DIR__) . "/" . $item['image'];
if (file_exists($file_path)) unlink($file_path);
}
if ($conn->query("DELETE FROM gallery WHERE id = $id")) {
redirect(BASE_URL . '/admin/media.php?msg=deleted');
} else {
$error_message = "Gagal menghapus: " . $conn->error;
}
}
// =====================================================
// HANDLE TOGGLE FEATURED
// =====================================================
if (isset($_GET['toggle_featured'])) {
$id = (int)$_GET['toggle_featured'];
$current = $conn->query("SELECT featured FROM gallery WHERE id = $id")->fetch_assoc();
$new_val = $current['featured'] ? 0 : 1;
$conn->query("UPDATE gallery SET featured = $new_val WHERE id = $id");
redirect(BASE_URL . '/admin/media.php');
}
// =====================================================
// PAGINATION
// =====================================================
$limit = 12;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;
// =====================================================
// FILTER
// =====================================================
$type_filter = isset($_GET['type']) ? sanitize($_GET['type']) : '';
$category_filter = isset($_GET['category']) ? sanitize($_GET['category']) : '';
$status_filter = isset($_GET['status']) ? sanitize($_GET['status']) : '';
$album_filter = isset($_GET['album_id']) ? (int)$_GET['album_id'] : 0;
$where = ["1=1"];
if (!empty($type_filter)) $where[] = "type = '$type_filter'";
if (!empty($category_filter)) $where[] = "category = '$category_filter'";
if (!empty($status_filter)) $where[] = "status = '$status_filter'";
if ($album_filter > 0) $where[] = "album_id = $album_filter";
$where_clause = implode(' AND ', $where);
$total_records = $conn->query("SELECT COUNT(*) as total FROM gallery WHERE $where_clause")->fetch_assoc()['total'];
$total_pages = $total_records > 0 ? ceil($total_records / $limit) : 1;
$items = $conn->query("
SELECT * FROM gallery
WHERE $where_clause
ORDER BY featured DESC, created_at DESC
LIMIT $offset, $limit
");
// =====================================================
// DATA UNTUK FILTER & DROPDOWN
// =====================================================
$categories = $conn->query("SELECT DISTINCT category FROM gallery WHERE category != '' ORDER BY category");
$album_arr = [];
$res_albums = $conn->query("SELECT id, name, slug, status FROM albums ORDER BY name");
while ($r = $res_albums->fetch_assoc()) $album_arr[] = $r;
$album_name = '';
if ($album_filter > 0) {
foreach ($album_arr as $a) {
if ($a['id'] == $album_filter) { $album_name = $a['name']; break; }
}
}
require_once 'includes/header.php';
?>
<div class="container-fluid">
<!-- Header -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">
<i class="fas fa-images me-2"></i>Manajemen Media Galeri
<?php if ($album_filter > 0 && !empty($album_name)): ?>
<small class="text-muted">/ Album: <?php echo htmlspecialchars($album_name); ?></small>
<?php endif; ?>
</h1>
<div>
<button type="button" class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#albumModal">
<i class="fas fa-folder-plus me-2"></i>Buat Album
</button>
<button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#uploadModal">
<i class="fas fa-upload me-2"></i>Upload Media
</button>
</div>
</div>
<!-- Flash Messages -->
<?php if (!empty($success_message)): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<i class="fas fa-check-circle me-2"></i><?php echo $success_message; ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<?php if (!empty($error_message)): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<i class="fas fa-exclamation-circle me-2"></i><?php echo $error_message; ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<!-- =====================================================
DAFTAR ALBUM
===================================================== -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-white">
<i class="fas fa-folder me-2"></i>Album
</h6>
</div>
<div class="card-body">
<div class="row">
<?php if (!empty($album_arr)): ?>
<?php foreach ($album_arr as $album): ?>
<div class="col-md-2 col-4 mb-3">
<div class="card album-card text-center h-100">
<div class="card-body">
<i class="fas fa-folder-open fa-3x text-warning mb-2"></i>
<h6 class="text-truncate"><?php echo htmlspecialchars($album['name']); ?></h6>
<small class="text-muted"><?php echo htmlspecialchars($album['status']); ?></small>
</div>
<div class="card-footer bg-transparent p-1">
<a href="<?php echo BASE_URL; ?>/galeri/album/<?php echo $album['slug']; ?>"
class="btn btn-sm btn-primary" target="_blank">
<i class="fas fa-external-link-alt me-1"></i> Lihat
</a>
<button class="btn btn-sm btn-success"
onclick="copyAlbumLink('<?php echo BASE_URL; ?>/galeri/album/<?php echo $album['slug']; ?>', '<?php echo addslashes($album['name']); ?>')">
<i class="fas fa-copy me-1"></i> Salin Link
</button>
<button class="btn btn-sm btn-warning" onclick="editAlbum(<?php echo $album['id']; ?>)">
<i class="fas fa-edit"></i>
</button>
<a href="<?php echo BASE_URL; ?>/admin/media.php?delete_album=<?php echo $album['id']; ?>"
class="btn btn-sm btn-danger"
onclick="return confirm('Hapus album ini? Semua foto akan dilepas dari album.')">
<i class="fas fa-trash"></i>
</a>
</div>
</div>
</div>
<?php endforeach; ?>
<?php else: ?>
<div class="col-12">
<p class="text-muted text-center py-3">Belum ada album. Buat album baru untuk mengelompokkan foto.</p>
</div>
<?php endif; ?>
</div>
</div>
</div>
<!-- =====================================================
FILTER
===================================================== -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-white">
<i class="fas fa-filter me-2"></i>Filter
</h6>
</div>
<div class="card-body">
<form method="GET" class="row g-3">
<div class="col-md-2">
<label class="form-label">Tipe</label>
<select class="form-control" name="type">
<option value="">Semua Tipe</option>
<option value="image" <?php echo $type_filter == 'image' ? 'selected' : ''; ?>>Gambar</option>
<option value="video" <?php echo $type_filter == 'video' ? 'selected' : ''; ?>>Video</option>
</select>
</div>
<div class="col-md-2">
<label class="form-label">Kategori</label>
<select class="form-control" name="category">
<option value="">Semua Kategori</option>
<?php if ($categories && $categories->num_rows > 0):
$categories->data_seek(0);
while ($cat = $categories->fetch_assoc()): ?>
<option value="<?php echo htmlspecialchars($cat['category']); ?>"
<?php echo $category_filter == $cat['category'] ? 'selected' : ''; ?>>
<?php echo htmlspecialchars($cat['category']); ?>
</option>
<?php endwhile; endif; ?>
</select>
</div>
<div class="col-md-2">
<label class="form-label">Status</label>
<select class="form-control" name="status">
<option value="">Semua Status</option>
<option value="active" <?php echo $status_filter == 'active' ? 'selected' : ''; ?>>Aktif</option>
<option value="inactive" <?php echo $status_filter == 'inactive' ? 'selected' : ''; ?>>Tidak Aktif</option>
</select>
</div>
<div class="col-md-3">
<label class="form-label">Album</label>
<select class="form-control" name="album_id">
<option value="">Semua Album</option>
<?php foreach ($album_arr as $alb): ?>
<option value="<?php echo $alb['id']; ?>" <?php echo ($album_filter == $alb['id']) ? 'selected' : ''; ?>>
<?php echo htmlspecialchars($alb['name']); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-md-3">
<label class="form-label">Aksi</label>
<div class="d-flex">
<button type="submit" class="btn btn-primary me-2">
<i class="fas fa-filter me-2"></i>Filter
</button>
<a href="<?php echo BASE_URL; ?>/admin/media.php" class="btn btn-secondary">
<i class="fas fa-sync-alt"></i>
</a>
</div>
</div>
</form>
</div>
</div>
<!-- =====================================================
GALLERY GRID
===================================================== -->
<div class="card shadow mb-4">
<div class="card-header py-3 d-flex justify-content-between align-items-center">
<h6 class="m-0 font-weight-bold text-white">
<i class="fas fa-th me-2"></i>Daftar Media
<span class="badge bg-primary ms-2"><?php echo $total_records; ?> Total</span>
</h6>
<?php if ($total_pages > 1): ?>
<div class="pagination-info">
Halaman <?php echo $page; ?> dari <?php echo $total_pages; ?>
</div>
<?php endif; ?>
</div>
<div class="card-body">
<?php if ($items && $items->num_rows > 0): ?>
<div class="row" id="gallery-grid">
<?php while ($item = $items->fetch_assoc()): ?>
<div class="col-xl-3 col-lg-4 col-md-6 mb-4">
<div class="card gallery-card h-100">
<div class="card-img-top position-relative" style="height: 180px; overflow: hidden;">
<?php if ($item['type'] == 'video'): ?>
<button type="button"
class="btn btn-sm btn-danger position-absolute bottom-0 end-0 m-2"
onclick="previewVideo('<?php echo htmlspecialchars($item['video_url']); ?>', '<?php echo addslashes($item['title']); ?>')"
title="Putar video">
<i class="fas fa-play"></i>
</button>
<?php
// Prioritas: kalau $item['image'] sudah URL thumbnail, pakai itu
// Kalau bukan, ekstrak dari video_url
$thumb = '';
if (!empty($item['image']) && preg_match('#^https?://#', $item['image'])) {
$thumb = $item['image'];
} else {
$yt_id = getYouTubeId($item['video_url']);
if ($yt_id) {
$thumb = 'https://img.youtube.com/vi/' . $yt_id . '/hqdefault.jpg';
}
}
?>
<?php if ($thumb): ?>
<img src="<?php echo $thumb; ?>"
alt="<?php echo htmlspecialchars($item['title']); ?>"
style="width:100%; height:100%; object-fit:cover;">
<?php else: ?>
<div class="bg-secondary text-white d-flex align-items-center justify-content-center h-100">
<i class="fas fa-video fa-3x"></i>
</div>
<?php endif; ?>
<div class="position-absolute top-50 start-50 translate-middle">
<i class="fas fa-play-circle fa-3x text-white" style="opacity:0.8;"></i>
</div>
<?php else: ?>
<?php
$image_path = $item['image'];
if (strpos($image_path, 'uploads/gallery/') === false && strpos($image_path, 'uploads/') !== false) {
$image_path = str_replace('uploads/', 'uploads/gallery/', $image_path);
}
?>
<img src="<?php echo BASE_URL; ?>/<?php echo $image_path; ?>"
alt="<?php echo htmlspecialchars($item['title']); ?>"
style="width:100%; height:100%; object-fit:cover;"
onerror="this.src='<?php echo BASE_URL; ?>/admin/assets/img/no-image.png'">
<?php endif; ?>
<?php if ($item['featured']): ?>
<span class="position-absolute top-0 start-0 badge bg-warning m-2">
<i class="fas fa-star me-1"></i>Featured
</span>
<?php endif; ?>
<span class="position-absolute top-0 end-0 badge bg-<?php echo $item['type'] == 'video' ? 'danger' : 'primary'; ?> m-2">
<i class="fas fa-<?php echo $item['type'] == 'video' ? 'video' : 'camera'; ?> me-1"></i>
<?php echo ucfirst($item['type']); ?>
</span>
</div>
<div class="card-body">
<h6 class="card-title text-truncate"><?php echo htmlspecialchars($item['title']); ?></h6>
<?php if (!empty($item['category'])): ?>
<small class="text-muted d-block">
<i class="fas fa-tag me-1"></i><?php echo htmlspecialchars($item['category']); ?>
</small>
<?php endif; ?>
<small class="text-muted d-block">
<i class="far fa-calendar me-1"></i><?php echo date('d M Y', strtotime($item['created_at'])); ?>
</small>
<div class="mt-2">
<span class="badge bg-<?php echo $item['status'] == 'active' ? 'success' : 'secondary'; ?>">
<?php echo $item['status'] == 'active' ? 'Aktif' : 'Tidak Aktif'; ?>
</span>
<?php if ($item['album_id'] > 0):
$album_nama = null;
foreach ($album_arr as $a) {
if ($a['id'] == $item['album_id']) { $album_nama = $a['name']; break; }
}
if ($album_nama):
?>
<span class="badge bg-info">
<i class="fas fa-folder me-1"></i><?php echo htmlspecialchars($album_nama); ?>
</span>
<?php endif; endif; ?>
</div>
</div>
<div class="card-footer bg-transparent">
<div class="btn-group w-100">
<button type="button" class="btn btn-sm btn-info" onclick="editItem(<?php echo $item['id']; ?>)">
<i class="fas fa-edit"></i> Edit
</button>
<a href="<?php echo BASE_URL; ?>/admin/media.php?toggle_featured=<?php echo $item['id']; ?>"
class="btn btn-sm btn-<?php echo $item['featured'] ? 'warning' : 'secondary'; ?>"
title="<?php echo $item['featured'] ? 'Hapus dari Featured' : 'Jadikan Featured'; ?>">
<i class="fas fa-star"></i>
</a>
<a href="<?php echo BASE_URL; ?>/admin/media.php?delete=<?php echo $item['id']; ?>"
class="btn btn-sm btn-danger"
onclick="return confirm('Yakin ingin menghapus item ini?')">
<i class="fas fa-trash"></i>
</a>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
<!-- Pagination -->
<?php if ($total_pages > 1): ?>
<nav class="mt-4">
<ul class="pagination justify-content-center">
<li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
<a class="page-link" href="<?php echo BASE_URL; ?>/admin/media.php?page=1&type=<?php echo urlencode($type_filter); ?>&category=<?php echo urlencode($category_filter); ?>&status=<?php echo urlencode($status_filter); ?>&album_id=<?php echo $album_filter; ?>">
<i class="fas fa-angle-double-left"></i>
</a>
</li>
<?php for ($i = 1; $i <= $total_pages; $i++): ?>
<li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
<a class="page-link" href="<?php echo BASE_URL; ?>/admin/media.php?page=<?php echo $i; ?>&type=<?php echo urlencode($type_filter); ?>&category=<?php echo urlencode($category_filter); ?>&status=<?php echo urlencode($status_filter); ?>&album_id=<?php echo $album_filter; ?>">
<?php echo $i; ?>
</a>
</li>
<?php endfor; ?>
<li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
<a class="page-link" href="<?php echo BASE_URL; ?>/admin/media.php?page=<?php echo $page+1; ?>&type=<?php echo urlencode($type_filter); ?>&category=<?php echo urlencode($category_filter); ?>&status=<?php echo urlencode($status_filter); ?>&album_id=<?php echo $album_filter; ?>">
<i class="fas fa-angle-double-right"></i>
</a>
</li>
</ul>
</nav>
<?php endif; ?>
<?php else: ?>
<div class="text-center py-5">
<i class="fas fa-images fa-4x text-muted mb-3"></i>
<h5>Belum Ada Media</h5>
<p class="text-muted">Klik tombol "Upload Media" untuk menambahkan foto atau video.</p>
</div>
<?php endif; ?>
</div>
</div>
</div>
<!-- =====================================================
MODAL UPLOAD MEDIA
===================================================== -->
<div class="modal fade" id="uploadModal" tabindex="-1" data-bs-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form method="POST" enctype="multipart/form-data" id="uploadForm"
action="<?php echo BASE_URL; ?>/admin/media.php" novalidate>
<div class="modal-header">
<h5 class="modal-title">
<i class="fas fa-upload me-2"></i>Upload Media
</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<!-- Tab Nav -->
<ul class="nav nav-tabs mb-3" id="uploadTab" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="multi-tab" data-bs-toggle="tab"
data-bs-target="#multi" type="button" role="tab">
<i class="fas fa-images me-1"></i>Multi Upload
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="single-tab" data-bs-toggle="tab"
data-bs-target="#single" type="button" role="tab">
<i class="fas fa-file-upload me-1"></i>Single Upload
</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="video-tab" data-bs-toggle="tab"
data-bs-target="#video" type="button" role="tab">
<i class="fas fa-video me-1"></i>Video (YouTube)
</button>
</li>
</ul>
<div class="tab-content">
<!-- TAB MULTI -->
<div class="tab-pane fade show active" id="multi" role="tabpanel">
<div class="mb-3">
<label class="form-label fw-bold">Pilih Album</label>
<select class="form-control" name="album_id">
<option value="">-- Pilih Album --</option>
<?php foreach ($album_arr as $alb): ?>
<option value="<?php echo $alb['id']; ?>"><?php echo htmlspecialchars($alb['name']); ?></option>
<?php endforeach; ?>
</select>
<small class="text-muted">Buat album baru melalui tombol "Buat Album"</small>
</div>
<div class="mb-3">
<label class="form-label">Pilih File Gambar <span class="text-danger">*</span></label>
<input type="file" class="form-control" name="image_files[]" accept="image/*" multiple>
<small class="text-muted">Format: JPG, PNG, GIF, WEBP. Maks 5MB per file.</small>
</div>
<div id="fileList" class="mb-3"></div>
<div class="mb-3">
<label class="form-label">Prefiks Judul (Opsional)</label>
<input type="text" class="form-control" name="title_prefix" placeholder="Contoh: Kegiatan Lomba 2025">
<small class="text-muted">Jika diisi, judul otomatis "Prefiks 1", "Prefiks 2", dst.</small>
</div>
</div>
<!-- TAB SINGLE -->
<div class="tab-pane fade" id="single" role="tabpanel">
<div class="mb-3">
<label class="form-label">Pilih Album</label>
<select class="form-control" name="album_id">
<option value="">-- Tanpa Album --</option>
<?php foreach ($album_arr as $alb): ?>
<option value="<?php echo $alb['id']; ?>"><?php echo htmlspecialchars($alb['name']); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-3">
<label class="form-label">File Gambar <span class="text-danger">*</span></label>
<input type="file" class="form-control" name="single_image_file" accept="image/*">
</div>
<div class="mb-3">
<label class="form-label">Judul <span class="text-danger">*</span></label>
<input type="text" class="form-control" name="single_title">
</div>
<div class="mb-3">
<label class="form-label">Deskripsi</label>
<textarea class="form-control" name="single_description" rows="2"></textarea>
</div>
</div>
<!-- TAB VIDEO -->
<div class="tab-pane fade" id="video" role="tabpanel">
<div class="mb-3">
<label class="form-label">Pilih Album</label>
<select class="form-control" name="album_id">
<option value="">-- Tanpa Album --</option>
<?php foreach ($album_arr as $alb): ?>
<option value="<?php echo $alb['id']; ?>"><?php echo htmlspecialchars($alb['name']); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-3">
<label class="form-label">URL Video (YouTube) <span class="text-danger">*</span></label>
<input type="url" class="form-control" name="video_url"
placeholder="https://www.youtube.com/watch?v=xxxxx">
<small class="text-muted">Masukkan URL video YouTube.</small>
</div>
<div class="mb-3">
<label class="form-label">Judul <span class="text-danger">*</span></label>
<input type="text" class="form-control" name="video_title">
</div>
</div>
</div>
<!-- Common Fields -->
<input type="hidden" name="type" value="image" id="uploadType">
<div class="row">
<div class="col-md-6 mb-3">
<label class="form-label">Kategori</label>
<input type="text" class="form-control" name="category" placeholder="Contoh: Kegiatan">
</div>
<div class="col-md-6 mb-3">
<label class="form-label">Status</label>
<select class="form-control" name="status">
<option value="active">Aktif</option>
<option value="inactive">Tidak Aktif</option>
</select>
</div>
</div>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="featured" id="featured">
<label class="form-check-label" for="featured">
<i class="fas fa-star text-warning me-1"></i>Jadikan Featured (Unggulan)
</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
<button type="submit" name="upload_multi" class="btn btn-success" id="submitMultiUpload">
<i class="fas fa-cloud-upload-alt me-2"></i>Upload
</button>
<button type="submit" name="upload" class="btn btn-primary" id="submitSingleUpload" style="display:none;">
<i class="fas fa-upload me-2"></i>Upload
</button>
</div>
</form>
</div>
</div>
</div>
<!-- =====================================================
MODAL BUAT ALBUM
===================================================== -->
<div class="modal fade" id="albumModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<form method="POST" action="<?php echo BASE_URL; ?>/admin/media.php">
<div class="modal-header">
<h5 class="modal-title"><i class="fas fa-folder-plus me-2"></i>Buat Album Baru</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<div class="mb-3">
<label class="form-label">Nama Album <span class="text-danger">*</span></label>
<input type="text" class="form-control" name="name" required>
</div>
<div class="mb-3">
<label class="form-label">Deskripsi</label>
<textarea class="form-control" name="description" rows="3"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
<button type="submit" name="add_album" class="btn btn-primary">
<i class="fas fa-save me-2"></i>Simpan Album
</button>
</div>
</form>
</div>
</div>
</div>
<!-- =====================================================
MODAL EDIT ALBUM
===================================================== -->
<div class="modal fade" id="editAlbumModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<form method="POST" id="editAlbumForm" action="<?php echo BASE_URL; ?>/admin/media.php">
<div class="modal-header">
<h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Album</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<input type="hidden" name="id" id="editAlbumId">
<div class="mb-3">
<label class="form-label">Nama Album</label>
<input type="text" class="form-control" name="name" id="editAlbumName" required>
</div>
<div class="mb-3">
<label class="form-label">Deskripsi</label>
<textarea class="form-control" name="description" id="editAlbumDesc" rows="3"></textarea>
</div>
<div class="mb-3">
<label class="form-label">Status</label>
<select class="form-control" name="status" id="editAlbumStatus">
<option value="active">Aktif</option>
<option value="inactive">Tidak Aktif</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
<button type="submit" name="edit_album" class="btn btn-primary">
<i class="fas fa-save me-2"></i>Simpan Perubahan
</button>
</div>
</form>
</div>
</div>
</div>
<!-- =====================================================
MODAL EDIT GALLERY ITEM
===================================================== -->
<div class="modal fade" id="editModal" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<form method="POST" id="editForm" action="<?php echo BASE_URL; ?>/admin/media.php">
<div class="modal-header">
<h5 class="modal-title"><i class="fas fa-edit me-2"></i>Edit Media</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body">
<input type="hidden" name="id" id="editId">
<div class="mb-3">
<label class="form-label">Judul</label>
<input type="text" class="form-control" name="title" id="editTitle" required>
</div>
<div class="mb-3">
<label class="form-label">Deskripsi</label>
<textarea class="form-control" name="description" id="editDescription" rows="3"></textarea>
</div>
<div class="mb-3">
<label class="form-label">Kategori</label>
<input type="text" class="form-control" name="category" id="editCategory">
</div>
<div class="mb-3">
<label class="form-label">Album</label>
<select class="form-control" name="album_id" id="editAlbumIdGallery">
<option value="0">-- Tanpa Album --</option>
<?php foreach ($album_arr as $alb): ?>
<option value="<?php echo $alb['id']; ?>"><?php echo htmlspecialchars($alb['name']); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-3">
<label class="form-label">Status</label>
<select class="form-control" name="status" id="editStatus">
<option value="active">Aktif</option>
<option value="inactive">Tidak Aktif</option>
</select>
</div>
<div class="mb-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="featured" id="editFeatured">
<label class="form-check-label" for="editFeatured">
<i class="fas fa-star text-warning me-1"></i>Jadikan Featured (Unggulan)
</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
<button type="submit" name="edit" class="btn btn-primary">
<i class="fas fa-save me-2"></i>Simpan Perubahan
</button>
</div>
</form>
</div>
</div>
</div>
<!-- =====================================================
MODAL PREVIEW VIDEO
===================================================== -->
<div class="modal fade" id="videoPreviewModal" tabindex="-1">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><i class="fas fa-play-circle me-2"></i><span id="videoPreviewTitle"></span></h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<div class="modal-body p-0">
<div class="ratio ratio-16x9">
<iframe id="videoPreviewFrame"
src=""
title="Video preview"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen
referrerpolicy="strict-origin-when-cross-origin">
</iframe>
</div>
</div>
</div>
</div>
</div>
<style>
.gallery-card { transition: all 0.3s; border: 1px solid #e3e6f0; overflow: hidden; }
.gallery-card:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.1); border-color: var(--primary-color); }
.gallery-card .card-img-top { transition: transform 0.5s; }
.gallery-card:hover .card-img-top img { transform: scale(1.1); }
.gallery-card .btn-group { opacity: 0.8; transition: opacity 0.3s; }
.gallery-card:hover .btn-group { opacity: 1; }
.album-card { transition: all 0.3s; border: 1px solid #e3e6f0; }
.album-card:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
.toast-notification {
position: fixed; bottom: 30px; right: 30px;
background: #1e293b; color: white; padding: 14px 24px;
border-radius: 12px; font-size: 14px; font-weight: 500;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
transform: translateY(100px); opacity: 0;
transition: all 0.3s ease; z-index: 9999; max-width: 400px;
}
.toast-notification.show { transform: translateY(0); opacity: 1; }
.toast-notification.success { border-left: 4px solid #10b981; }
.toast-notification.error { border-left: 4px solid #ef4444; }
</style>
<script>
const BASE_URL = '<?php echo BASE_URL; ?>';
// =====================================================
// SHOW TOAST
// =====================================================
function showToast(message, type = 'success') {
const oldToast = document.querySelector('.toast-notification');
if (oldToast) oldToast.remove();
const toast = document.createElement('div');
toast.className = 'toast-notification ' + type;
toast.innerHTML = '<i class="fas fa-' + (type === 'success' ? 'check' : 'exclamation') + '-circle me-2"></i>' + message;
document.body.appendChild(toast);
setTimeout(() => toast.classList.add('show'), 100);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 3000);
}
// =====================================================
// MULTI UPLOAD - DAFTAR FILE
// =====================================================
document.querySelector('input[name="image_files[]"]')?.addEventListener('change', function() {
const fileList = document.getElementById('fileList');
if (!fileList) return;
fileList.innerHTML = '';
if (this.files.length === 0) return;
const list = document.createElement('ul');
list.className = 'list-group';
for (let i = 0; i < this.files.length; i++) {
const li = document.createElement('li');
li.className = 'list-group-item d-flex justify-content-between align-items-center';
const file = this.files[i];
const size = (file.size / 1024).toFixed(1) + ' KB';
li.innerHTML = `<span><i class="fas fa-file-image me-2"></i>${file.name}</span><span class="badge bg-secondary">${size}</span>`;
list.appendChild(li);
}
fileList.appendChild(list);
});
// =====================================================
// DISABLE FIELD TAB NON-AKTIF (WAJIB - fix error "not focusable")
// =====================================================
function syncTabFields() {
const active = document.querySelector('#uploadTab .nav-link.active').getAttribute('data-bs-target');
document.querySelectorAll('#uploadModal .tab-pane').forEach(pane => {
const isActive = '#' + pane.id === active;
pane.querySelectorAll('input, select, textarea').forEach(el => {
el.disabled = !isActive;
});
});
}
document.querySelectorAll('#uploadTab button[data-bs-toggle="tab"]').forEach(btn => {
btn.addEventListener('shown.bs.tab', syncTabFields);
});
document.getElementById('uploadModal')?.addEventListener('shown.bs.modal', syncTabFields);
// =====================================================
// TAB HANDLER - Toggle button submit
// =====================================================
document.querySelectorAll('#uploadTab button[data-bs-toggle="tab"]').forEach(btn => {
btn.addEventListener('shown.bs.tab', function(e) {
const target = e.target.getAttribute('data-bs-target');
const multiBtn = document.getElementById('submitMultiUpload');
const singleBtn = document.getElementById('submitSingleUpload');
const typeInput = document.getElementById('uploadType');
if (target === '#multi') {
multiBtn.style.display = 'inline-block';
singleBtn.style.display = 'none';
typeInput.value = 'image';
} else if (target === '#single') {
multiBtn.style.display = 'none';
singleBtn.style.display = 'inline-block';
typeInput.value = 'image';
} else if (target === '#video') {
multiBtn.style.display = 'none';
singleBtn.style.display = 'inline-block';
typeInput.value = 'video';
}
});
});
// =====================================================
// VALIDASI FORM SEBELUM SUBMIT
// =====================================================
document.getElementById('uploadForm')?.addEventListener('submit', function(e) {
const activeTab = document.querySelector('#uploadTab .nav-link.active').getAttribute('data-bs-target');
const errors = [];
if (activeTab === '#multi') {
const files = document.querySelector('input[name="image_files[]"]').files;
if (!files.length) errors.push('Pilih minimal 1 file gambar.');
}
if (activeTab === '#single') {
const file = document.querySelector('input[name="single_image_file"]').files;
const title = document.querySelector('input[name="single_title"]').value.trim();
if (!file.length) errors.push('Pilih file gambar.');
if (!title) errors.push('Judul gambar wajib diisi.');
}
if (activeTab === '#video') {
const url = document.querySelector('input[name="video_url"]').value.trim();
const title = document.querySelector('input[name="video_title"]').value.trim();
if (!url) errors.push('URL video wajib diisi.');
if (!title) errors.push('Judul video wajib diisi.');
if (url && !/^https?:\/\/(www\.)?(youtube\.com|youtu\.be)\//.test(url)) {
errors.push('URL harus link YouTube yang valid.');
}
}
if (errors.length) {
e.preventDefault();
showToast(errors.join('<br>'), 'error');
return false;
}
});
// =====================================================
// EDIT ALBUM (hanya sekali, tidak duplikat)
// =====================================================
function editAlbum(id) {
fetch(BASE_URL + '/admin/get_album.php?id=' + id)
.then(r => r.json())
.then(data => {
document.getElementById('editAlbumId').value = data.id;
document.getElementById('editAlbumName').value = data.name;
document.getElementById('editAlbumDesc').value = data.description || '';
document.getElementById('editAlbumStatus').value = data.status;
new bootstrap.Modal(document.getElementById('editAlbumModal')).show();
})
.catch(() => showToast('Gagal memuat data album', 'error'));
}
// =====================================================
// EDIT GALLERY ITEM
// =====================================================
function editItem(id) {
fetch(BASE_URL + '/admin/get_gallery_item.php?id=' + id)
.then(r => r.json())
.then(data => {
document.getElementById('editId').value = data.id;
document.getElementById('editTitle').value = data.title;
document.getElementById('editDescription').value = data.description || '';
document.getElementById('editCategory').value = data.category || '';
document.getElementById('editStatus').value = data.status;
document.getElementById('editFeatured').checked = data.featured == 1;
document.getElementById('editAlbumIdGallery').value = data.album_id || 0;
new bootstrap.Modal(document.getElementById('editModal')).show();
})
.catch(() => showToast('Gagal memuat data', 'error'));
}
// =====================================================
// COPY LINK ALBUM
// =====================================================
function copyAlbumLink(url, name) {
const tempInput = document.createElement('input');
tempInput.value = url;
document.body.appendChild(tempInput);
tempInput.select();
try {
document.execCommand('copy');
showToast('Link album "' + name + '" berhasil disalin!', 'success');
} catch (err) {
prompt('Salin link berikut:', url);
}
document.body.removeChild(tempInput);
}
// =====================================================
// RESET FORM SAAT MODAL DITUTUP
// =====================================================
document.getElementById('uploadModal')?.addEventListener('hidden.bs.modal', function() {
document.getElementById('uploadForm')?.reset();
const fileList = document.getElementById('fileList');
if (fileList) fileList.innerHTML = '';
// Kembali ke tab pertama
const firstTab = document.querySelector('#uploadTab .nav-link');
if (firstTab) new bootstrap.Tab(firstTab).show();
});
// =====================================================
// PREVIEW VIDEO YOUTUBE
// =====================================================
function previewVideo(embedUrl, title) {
// Pastikan embedUrl berbentuk /embed/VIDEOID
let finalUrl = embedUrl;
if (!finalUrl.includes('/embed/')) {
const m = finalUrl.match(/([A-Za-z0-9_-]{11})/);
if (m) finalUrl = 'https://www.youtube.com/embed/' + m[1];
}
// Tambahkan autoplay
finalUrl += (finalUrl.includes('?') ? '&' : '?') + 'autoplay=1&rel=0';
document.getElementById('videoPreviewTitle').textContent = title;
document.getElementById('videoPreviewFrame').src = finalUrl;
new bootstrap.Modal(document.getElementById('videoPreviewModal')).show();
}
// Hentikan video saat modal ditutup (biar suara tidak lanjut)
document.getElementById('videoPreviewModal')?.addEventListener('hidden.bs.modal', function() {
document.getElementById('videoPreviewFrame').src = '';
});
</script>
<?php require_once 'includes/footer.php'; ?>