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

$pageTitle = 'Galeri Album';
$activePage = 'gallery_photos';
$msg = '';

// DELETE ALBUM
if (isset($_GET['delete'])) {
    $stmt = $pdo->prepare("SELECT cover_image FROM gallery_albums WHERE id=?");
    $stmt->execute([$_GET['delete']]);
    $row = $stmt->fetch();
    if ($row && $row['cover_image'] && file_exists(dirname(__DIR__).'/'.$row['cover_image'])) @unlink(dirname(__DIR__).'/'.$row['cover_image']);
    $pdo->prepare("DELETE FROM gallery_albums WHERE id=?")->execute([$_GET['delete']]);
    $msg = adminAlert('Album berhasil dihapus.');
}

// TOGGLE ACTIVE
if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE gallery_albums SET is_active = 1 - is_active WHERE id=?")->execute([$_GET['toggle']]);
    header('Location: gallery-photos.php'); exit;
}

// SAVE ALBUM (ADD / EDIT)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id           = $_POST['id'] ?? null;
    $title        = trim($_POST['title'] ?? '');
    $description  = trim($_POST['description'] ?? '');
    $category     = $_POST['category'] ?? 'general';
    $location     = trim($_POST['location'] ?? '');
    $project_date = $_POST['project_date'] ?? null;
    $sort         = (int)($_POST['sort_order'] ?? 0);
    $active       = isset($_POST['is_active']) ? 1 : 0;
    $existing_img = $_POST['existing_image'] ?? '';
    $cover_image  = $existing_img;

    if (!empty($_FILES['cover_image']['name'])) {
        $uploaded = uploadFile($_FILES['cover_image'], 'assets/images/gallery/albums');
        if ($uploaded) $cover_image = $uploaded;
    }

    if ($id) {
        $pdo->prepare("UPDATE gallery_albums SET title=?,description=?,cover_image=?,category=?,location=?,project_date=?,sort_order=?,is_active=? WHERE id=?")
            ->execute([$title, $description, $cover_image, $category, $location, $project_date ?: null, $sort, $active, $id]);
        $msg = adminAlert('Album berhasil diperbarui.');
    } else {
        $pdo->prepare("INSERT INTO gallery_albums (title,description,cover_image,category,location,project_date,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?)")
            ->execute([$title, $description, $cover_image, $category, $location, $project_date ?: null, $sort, $active]);
        $msg = adminAlert('Album berhasil ditambahkan.', 'success');
    }
}

// Fetch albums with photo count
$albums = $pdo->query("
    SELECT a.*, COUNT(p.id) AS photo_count
    FROM gallery_albums a
    LEFT JOIN gallery_photos p ON p.album_id = a.id
    GROUP BY a.id
    ORDER BY a.sort_order ASC, a.created_at DESC
")->fetchAll();

include 'partials/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="fw-bold mb-0">Galeri Album</h4>
        <small class="text-muted">Kelola album foto proyek</small>
    </div>
    <button class="btn btn-dark btn-sm" data-bs-toggle="modal" data-bs-target="#albumModal">
        <i class="bi bi-plus-lg me-1"></i> Tambah Album
    </button>
</div>

<?= $msg ?>

<div class="card border-0 shadow-sm">
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th>Cover</th>
                    <th>Judul Album</th>
                    <th>Kategori</th>
                    <th>Lokasi</th>
                    <th>Tanggal</th>
                    <th class="text-center">Foto</th>
                    <th class="text-center">Status</th>
                    <th class="text-center">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($albums as $a): ?>
                <tr>
                    <td>
                        <img src="../<?= htmlspecialchars($a['cover_image']??'') ?>" width="64" height="48"
                             style="object-fit:cover;border-radius:6px;"
                             onerror="this.src='https://placehold.co/64x48/e0e0e0/888?text=No+Img'">
                    </td>
                    <td>
                        <strong><?= htmlspecialchars($a['title']) ?></strong><br>
                        <small class="text-muted"><?= htmlspecialchars(substr($a['description']??'',0,60)) ?>...</small>
                    </td>
                    <td><span class="badge bg-secondary"><?= htmlspecialchars($a['category']) ?></span></td>
                    <td><small><?= htmlspecialchars($a['location']??'-') ?></small></td>
                    <td><small><?= $a['project_date'] ? date('d M Y', strtotime($a['project_date'])) : '-' ?></small></td>
                    <td class="text-center">
                        <a href="gallery-album-detail.php?album_id=<?= $a['id'] ?>" class="badge bg-primary text-decoration-none">
                            <?= $a['photo_count'] ?> foto
                        </a>
                    </td>
                    <td class="text-center">
                        <a href="?toggle=<?= $a['id'] ?>" class="badge <?= $a['is_active']?'bg-success':'bg-secondary' ?> text-decoration-none">
                            <?= $a['is_active']?'Aktif':'Nonaktif' ?>
                        </a>
                    </td>
                    <td class="text-center">
                        <a href="gallery-album-detail.php?album_id=<?= $a['id'] ?>" class="btn btn-xs btn-outline-primary me-1" title="Kelola Foto"><i class="bi bi-images"></i></a>
                        <button class="btn btn-xs btn-outline-secondary me-1" onclick="editAlbum(<?= htmlspecialchars(json_encode($a)) ?>)" title="Edit"><i class="bi bi-pencil"></i></button>
                        <a href="?delete=<?= $a['id'] ?>" class="btn btn-xs btn-outline-danger" onclick="return confirm('Hapus album dan semua fotonya?')" title="Hapus"><i class="bi bi-trash"></i></a>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($albums)): ?>
                <tr><td colspan="8" class="text-center py-4 text-muted">Belum ada album. Tambahkan album pertama Anda.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Modal Add/Edit Album -->
<div class="modal fade" id="albumModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold" id="modalTitle">Tambah Album</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="id" id="formId">
                <input type="hidden" name="existing_image" id="formExistingImg">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-12">
                            <label class="form-label fw-semibold">Judul Album <span class="text-danger">*</span></label>
                            <input type="text" name="title" id="formTitle" class="form-control" required placeholder="cth: Proyek Kursi Budiman Motor">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Kategori</label>
                            <select name="category" id="formCategory" class="form-select">
                                <option value="automotive">Automotive</option>
                                <option value="interior">Interior</option>
                                <option value="marine">Marine</option>
                                <option value="general">General</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Tanggal Proyek</label>
                            <input type="date" name="project_date" id="formDate" class="form-control">
                        </div>
                        <div class="col-12">
                            <label class="form-label fw-semibold">Lokasi</label>
                            <input type="text" name="location" id="formLocation" class="form-control" placeholder="cth: Bandung, Jawa Barat">
                        </div>
                        <div class="col-12">
                            <label class="form-label fw-semibold">Deskripsi</label>
                            <textarea name="description" id="formDesc" class="form-control" rows="3"></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Cover Image</label>
                            <input type="file" name="cover_image" class="form-control" accept="image/*" onchange="previewImg(this,'coverPreview')">
                            <img id="coverPreview" src="" class="mt-2 rounded" style="max-height:100px;display:none;">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-semibold">Urutan</label>
                            <input type="number" name="sort_order" id="formSort" class="form-control" value="0">
                        </div>
                        <div class="col-md-3 d-flex align-items-end">
                            <div class="form-check mb-2">
                                <input class="form-check-input" type="checkbox" name="is_active" id="formActive" checked>
                                <label class="form-check-label" for="formActive">Aktif</label>
                            </div>
                        </div>
                    </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 editAlbum(data) {
    document.getElementById('modalTitle').textContent = 'Edit Album';
    document.getElementById('formId').value = data.id;
    document.getElementById('formTitle').value = data.title;
    document.getElementById('formDesc').value = data.description || '';
    document.getElementById('formCategory').value = data.category;
    document.getElementById('formLocation').value = data.location || '';
    document.getElementById('formDate').value = data.project_date ? data.project_date.substring(0,10) : '';
    document.getElementById('formSort').value = data.sort_order;
    document.getElementById('formActive').checked = data.is_active == 1;
    document.getElementById('formExistingImg').value = data.cover_image || '';
    if (data.cover_image) {
        const p = document.getElementById('coverPreview');
        p.src = '../' + data.cover_image;
        p.style.display = 'block';
    }
    new bootstrap.Modal(document.getElementById('albumModal')).show();
}
function previewImg(input, previewId) {
    const preview = document.getElementById(previewId);
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = e => { preview.src = e.target.result; preview.style.display = 'block'; };
        reader.readAsDataURL(input.files[0]);
    }
}
</script>
JS;
include 'partials/footer.php';
?>
