<?php
session_start();
require_once '../config/db.php';
require_once 'auth.php';

$album_id = (int)($_GET['album_id'] ?? 0);
if (!$album_id) { header('Location: gallery-photos.php'); exit; }

$album = $pdo->prepare("SELECT * FROM gallery_albums WHERE id=?");
$album->execute([$album_id]);
$album = $album->fetch();
if (!$album) { header('Location: gallery-photos.php'); exit; }

$pageTitle = 'Album: '.htmlspecialchars($album['title']);
$activePage = 'gallery_photos';
$msg = '';

// DELETE PHOTO
if (isset($_GET['delete'])) {
    $stmt = $pdo->prepare("SELECT image_path FROM gallery_photos WHERE id=? AND album_id=?");
    $stmt->execute([$_GET['delete'], $album_id]);
    $row = $stmt->fetch();
    if ($row && $row['image_path'] && file_exists(dirname(__DIR__).'/'.$row['image_path'])) @unlink(dirname(__DIR__).'/'.$row['image_path']);
    $pdo->prepare("DELETE FROM gallery_photos WHERE id=? AND album_id=?")->execute([$_GET['delete'], $album_id]);
    $msg = adminAlert('Foto berhasil dihapus.');
    header('Location: gallery-album-detail.php?album_id='.$album_id); exit;
}

// UPLOAD MULTIPLE PHOTOS
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_upload'])) {
    $uploaded_count = 0;
    if (!empty($_FILES['photos']['name'][0])) {
        foreach ($_FILES['photos']['name'] as $i => $fname) {
            if (!$fname) continue;
            $file = [
                'name'     => $_FILES['photos']['name'][$i],
                'type'     => $_FILES['photos']['type'][$i],
                'tmp_name' => $_FILES['photos']['tmp_name'][$i],
                'error'    => $_FILES['photos']['error'][$i],
                'size'     => $_FILES['photos']['size'][$i],
            ];
            $path = uploadFile($file, 'assets/images/gallery/album_'.$album_id);
            if ($path) {
                $title = pathinfo($fname, PATHINFO_FILENAME);
                $pdo->prepare("INSERT INTO gallery_photos (album_id, title, image_path, sort_order) VALUES (?,?,?,?)")
                    ->execute([$album_id, $title, $path, $i]);
                $uploaded_count++;
            }
        }
    }
    $msg = adminAlert("$uploaded_count foto berhasil diupload.", 'success');
}

// SAVE SINGLE PHOTO (ADD / EDIT)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_photo'])) {
    $photo_id     = $_POST['photo_id'] ?? null;
    $title        = trim($_POST['title'] ?? '');
    $caption      = trim($_POST['caption'] ?? '');
    $sort         = (int)($_POST['sort_order'] ?? 0);
    $existing_img = $_POST['existing_image'] ?? '';
    $image_path   = $existing_img;

    if (!empty($_FILES['photo']['name'])) {
        $uploaded = uploadFile($_FILES['photo'], 'assets/images/gallery/album_'.$album_id);
        if ($uploaded) $image_path = $uploaded;
    }

    if ($photo_id) {
        $pdo->prepare("UPDATE gallery_photos SET title=?,caption=?,image_path=?,sort_order=? WHERE id=? AND album_id=?")
            ->execute([$title, $caption, $image_path, $sort, $photo_id, $album_id]);
        $msg = adminAlert('Foto berhasil diperbarui.');
    } else {
        $pdo->prepare("INSERT INTO gallery_photos (album_id, title, image_path, caption, sort_order) VALUES (?,?,?,?,?)")
            ->execute([$album_id, $title, $image_path, $caption, $sort]);
        $msg = adminAlert('Foto berhasil ditambahkan.', 'success');
    }
}

$photos = $pdo->prepare("SELECT * FROM gallery_photos WHERE album_id=? ORDER BY sort_order ASC, id ASC");
$photos->execute([$album_id]);
$photos = $photos->fetchAll();

include 'partials/header.php';
?>

<!-- Breadcrumb -->
<nav aria-label="breadcrumb" class="mb-3">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
        <li class="breadcrumb-item"><a href="gallery-photos.php">Galeri Album</a></li>
        <li class="breadcrumb-item active"><?= htmlspecialchars($album['title']) ?></li>
    </ol>
</nav>

<!-- Album Info -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <div class="row align-items-center g-3">
            <div class="col-auto">
                <img src="../<?= htmlspecialchars($album['cover_image']??'') ?>" width="80" height="60"
                     style="object-fit:cover;border-radius:8px;"
                     onerror="this.src='https://placehold.co/80x60/e0e0e0/888?text=No+Img'">
            </div>
            <div class="col">
                <h5 class="fw-bold mb-1"><?= htmlspecialchars($album['title']) ?></h5>
                <div class="d-flex flex-wrap gap-2">
                    <span class="badge bg-secondary"><?= htmlspecialchars($album['category']) ?></span>
                    <?php if ($album['location']): ?>
                        <span class="text-muted small"><i class="bi bi-geo-alt me-1"></i><?= htmlspecialchars($album['location']) ?></span>
                    <?php endif; ?>
                    <?php if ($album['project_date']): ?>
                        <span class="text-muted small"><i class="bi bi-calendar3 me-1"></i><?= date('d M Y', strtotime($album['project_date'])) ?></span>
                    <?php endif; ?>
                    <span class="text-muted small"><i class="bi bi-images me-1"></i><?= count($photos) ?> foto</span>
                </div>
            </div>
            <div class="col-auto d-flex gap-2">
                <button class="btn btn-sm btn-outline-dark" data-bs-toggle="modal" data-bs-target="#bulkModal">
                    <i class="bi bi-cloud-upload me-1"></i> Upload Banyak Foto
                </button>
                <button class="btn btn-sm btn-dark" data-bs-toggle="modal" data-bs-target="#photoModal" onclick="resetPhotoForm()">
                    <i class="bi bi-plus-lg me-1"></i> Tambah Foto
                </button>
            </div>
        </div>
    </div>
</div>

<?= $msg ?>

<!-- Photos Grid -->
<?php if (empty($photos)): ?>
    <div class="text-center py-5 text-muted">
        <i class="bi bi-images display-4 d-block mb-3"></i>
        <p>Belum ada foto di album ini.</p>
        <button class="btn btn-dark btn-sm" data-bs-toggle="modal" data-bs-target="#bulkModal">
            <i class="bi bi-cloud-upload me-1"></i> Upload Foto Sekarang
        </button>
    </div>
<?php else: ?>
    <div class="row g-3">
        <?php foreach ($photos as $i => $p): ?>
        <div class="col-sm-6 col-md-4 col-lg-3">
            <div class="card border h-100">
                <div style="position:relative;">
                    <img src="../<?= htmlspecialchars($p['image_path']) ?>" class="card-img-top"
                         style="height:160px;object-fit:cover;"
                         onerror="this.src='https://placehold.co/300x160/e0e0e0/888?text=No+Img'">
                    <span class="badge bg-dark position-absolute top-0 start-0 m-1"><?= $i+1 ?></span>
                </div>
                <div class="card-body p-2">
                    <p class="fw-semibold mb-0 small text-truncate"><?= htmlspecialchars($p['title'] ?: 'Foto '.($i+1)) ?></p>
                    <?php if ($p['caption']): ?>
                        <small class="text-muted"><?= htmlspecialchars(substr($p['caption'],0,50)) ?></small>
                    <?php endif; ?>
                </div>
                <div class="card-footer p-2 d-flex gap-1 justify-content-end">
                    <button class="btn btn-xs btn-outline-secondary" onclick='editPhoto(<?= htmlspecialchars(json_encode($p)) ?>)' title="Edit"><i class="bi bi-pencil"></i></button>
                    <a href="?album_id=<?= $album_id ?>&delete=<?= $p['id'] ?>" class="btn btn-xs btn-outline-danger" onclick="return confirm('Hapus foto ini?')" title="Hapus"><i class="bi bi-trash"></i></a>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<!-- Modal: Bulk Upload -->
<div class="modal fade" id="bulkModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold"><i class="bi bi-cloud-upload me-2"></i>Upload Banyak Foto</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="bulk_upload" value="1">
                <div class="modal-body">
                    <p class="text-muted small mb-3">Pilih beberapa foto sekaligus. Semua foto akan langsung ditambahkan ke album ini.</p>
                    <input type="file" name="photos[]" class="form-control" accept="image/*" multiple required>
                    <div id="bulkPreview" class="row g-2 mt-2"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-dark"><i class="bi bi-upload me-1"></i> Upload Semua</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal: Add/Edit Single Photo -->
<div class="modal fade" id="photoModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold" id="photoModalTitle">Tambah Foto</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="save_photo" value="1">
                <input type="hidden" name="photo_id" id="photoId">
                <input type="hidden" name="existing_image" id="photoExisting">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Foto <span class="text-danger" id="photoRequired">*</span></label>
                        <input type="file" name="photo" id="photoFile" class="form-control" accept="image/*" onchange="previewSingle(this)">
                        <img id="photoPreview" src="" class="mt-2 rounded w-100" style="max-height:180px;object-fit:cover;display:none;">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Judul Foto</label>
                        <input type="text" name="title" id="photoTitle" class="form-control" placeholder="cth: Proses Pemasangan Kulit">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Keterangan</label>
                        <textarea name="caption" id="photoCaption" class="form-control" rows="2" placeholder="Deskripsi singkat foto..."></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Urutan</label>
                        <input type="number" name="sort_order" id="photoSort" class="form-control" value="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-dark"><i class="bi bi-save me-1"></i> Simpan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
$extraJs = <<<JS
<script>
function resetPhotoForm() {
    document.getElementById('photoModalTitle').textContent = 'Tambah Foto';
    document.getElementById('photoId').value = '';
    document.getElementById('photoTitle').value = '';
    document.getElementById('photoCaption').value = '';
    document.getElementById('photoSort').value = '0';
    document.getElementById('photoExisting').value = '';
    document.getElementById('photoFile').required = true;
    document.getElementById('photoRequired').style.display = 'inline';
    document.getElementById('photoPreview').style.display = 'none';
}
function editPhoto(data) {
    document.getElementById('photoModalTitle').textContent = 'Edit Foto';
    document.getElementById('photoId').value = data.id;
    document.getElementById('photoTitle').value = data.title || '';
    document.getElementById('photoCaption').value = data.caption || '';
    document.getElementById('photoSort').value = data.sort_order;
    document.getElementById('photoExisting').value = data.image_path || '';
    document.getElementById('photoFile').required = false;
    document.getElementById('photoRequired').style.display = 'none';
    if (data.image_path) {
        const p = document.getElementById('photoPreview');
        p.src = '../' + data.image_path;
        p.style.display = 'block';
    }
    new bootstrap.Modal(document.getElementById('photoModal')).show();
}
function previewSingle(input) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = e => {
            const p = document.getElementById('photoPreview');
            p.src = e.target.result;
            p.style.display = 'block';
        };
        reader.readAsDataURL(input.files[0]);
    }
}
// Bulk upload preview
document.querySelector('input[name="photos[]"]')?.addEventListener('change', function() {
    const container = document.getElementById('bulkPreview');
    container.innerHTML = '';
    [...this.files].forEach(file => {
        const reader = new FileReader();
        reader.onload = e => {
            const col = document.createElement('div');
            col.className = 'col-4';
            col.innerHTML = '<img src="' + e.target.result + '" class="img-fluid rounded" style="height:80px;object-fit:cover;">';
            container.appendChild(col);
        };
        reader.readAsDataURL(file);
    });
});
</script>
JS;
include 'partials/footer.php';
?>
