<?php
$admin_title = "Galeri Proyek";
require_once 'includes/header.php';

$error = '';
$success = '';

// Handle Delete Request
if (isset($_GET['delete'])) {
    $del_id = intval($_GET['delete']);
    try {
        $stmt = $pdo->prepare("SELECT image FROM gallery WHERE id = ?");
        $stmt->execute([$del_id]);
        $gal = $stmt->fetch();
        
        if ($gal) {
            $image_path = __DIR__ . '/../uploads/' . $gal['image'];
            if (!empty($gal['image']) && file_exists($image_path)) {
                @unlink($image_path);
            }
            
            $stmt = $pdo->prepare("DELETE FROM gallery WHERE id = ?");
            $stmt->execute([$del_id]);
            $success = "Foto proyek berhasil dihapus.";
        }
    } catch (Exception $e) {
        $error = "Gagal menghapus foto proyek: " . $e->getMessage();
    }
}

// Handle Add / Upload Request
if (isset($_POST['upload_gallery'])) {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    
    if (empty($title)) {
        $error = "Judul foto wajib diisi.";
    } elseif (!isset($_FILES['image']) || $_FILES['image']['error'] != UPLOAD_ERR_OK) {
        $error = "Harap pilih file gambar yang ingin diunggah.";
    } else {
        $file_tmp = $_FILES['image']['tmp_name'];
        $file_name = $_FILES['image']['name'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        $allowed_exts = ['jpg', 'jpeg', 'png', 'webp'];
        
        if (in_array($file_ext, $allowed_exts)) {
            $new_file_name = uniqid('gal_', true) . '.' . $file_ext;
            $dest_dir = __DIR__ . '/../uploads/';
            
            if (!is_dir($dest_dir)) {
                mkdir($dest_dir, 0777, true);
            }
            
            if (move_uploaded_file($file_tmp, $dest_dir . $new_file_name)) {
                try {
                    $stmt = $pdo->prepare("INSERT INTO gallery (title, description, image) VALUES (?, ?, ?)");
                    $stmt->execute([$title, $description, $new_file_name]);
                    $success = "Foto proyek berhasil diunggah!";
                    $_POST = array(); // Clear input
                } catch (Exception $e) {
                    $error = "Gagal menyimpan ke database: " . $e->getMessage();
                }
            } else {
                $error = "Gagal memindahkan file gambar yang diunggah.";
            }
        } else {
            $error = "Format file tidak didukung. Harap unggah format JPG, JPEG, PNG, atau WEBP.";
        }
    }
}

// Fetch all gallery items
try {
    $stmt = $pdo->prepare("SELECT * FROM gallery ORDER BY id DESC");
    $stmt->execute();
    $gallery = $stmt->fetchAll();
} catch (Exception $e) {
    $gallery = [];
}
?>

<?php if (!empty($error)): ?>
    <div style="background-color: rgba(239, 68, 68, 0.15); border: 1px solid var(--error); color: #f87171; padding: 12px 15px; border-radius: 6px; font-size: 13px; margin-bottom: 20px;">
        <i class="fas fa-exclamation-circle" style="margin-right: 5px;"></i> <?php echo $error; ?>
    </div>
<?php endif; ?>

<?php if (!empty($success)): ?>
    <div style="background-color: rgba(16, 185, 129, 0.15); border: 1px solid var(--success); color: #34d399; padding: 12px 15px; border-radius: 6px; font-size: 13px; margin-bottom: 20px;">
        <i class="fas fa-check-circle" style="margin-right: 5px;"></i> <?php echo $success; ?>
    </div>
<?php endif; ?>

<div class="form-row">
    
    <!-- Upload Form Card -->
    <div class="form-card" style="margin-bottom: 40px; height: fit-content;">
        <h2 style="font-size: 16px; font-weight: 700; color: var(--secondary); margin-bottom: 20px;">Tambah Foto Proyek Baru</h2>
        <form action="" method="POST" enctype="multipart/form-data">
            <div class="form-group">
                <label for="title">Judul / Nama Proyek *</label>
                <input type="text" id="title" name="title" class="form-control" placeholder="Contoh: Pemasangan Dinding Fasad Kemang" required value="<?php echo isset($_POST['title']) ? htmlspecialchars($_POST['title']) : ''; ?>">
            </div>
            
            <div class="form-group">
                <label for="description">Deskripsi Singkat</label>
                <input type="text" id="description" name="description" class="form-control" placeholder="Contoh: Menggunakan Batu Andesit Polos Bakar 30x60" value="<?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?>">
            </div>
            
            <div class="form-group">
                <label for="image">File Gambar *</label>
                <input type="file" id="image" name="image" class="form-control" accept="image/*" required>
                <span style="font-size: 11px; color: var(--text-muted); margin-top: 5px; display: block;">Format file didukung: JPG, JPEG, PNG, WEBP. Maksimal ukuran 2MB.</span>
            </div>
            
            <button type="submit" name="upload_gallery" class="btn-submit" style="width: 100%;">Unggah Foto Proyek</button>
        </form>
    </div>
    
    <!-- List Gallery Card -->
    <div class="data-card" style="height: fit-content;">
        <div class="data-card-header">
            <h2>Daftar Foto Proyek</h2>
        </div>
        <div class="table-responsive">
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>Foto</th>
                        <th>Judul Proyek</th>
                        <th>Deskripsi</th>
                        <th>Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($gallery) > 0): ?>
                        <?php foreach ($gallery as $g): ?>
                            <tr>
                                <td>
                                    <?php 
                                    $img_src = '../assets/images/' . $g['image'];
                                    if (!empty($g['image']) && file_exists('../uploads/' . $g['image'])) {
                                        $img_src = '../uploads/' . $g['image'];
                                    }
                                    ?>
                                    <img src="<?php echo $img_src; ?>" alt="Thumb" class="thumbnail" onerror="this.src='https://images.unsplash.com/photo-1600585154526-990dced4db0d?auto=format&fit=crop&w=100&q=80'">
                                </td>
                                <td><strong><?php echo htmlspecialchars($g['title']); ?></strong></td>
                                <td style="font-size: 13px; color: var(--text-muted);"><?php echo htmlspecialchars($g['description']); ?></td>
                                <td class="action-btns">
                                    <a href="gallery.php?delete=<?php echo $g['id']; ?>" class="btn-action delete" title="Hapus" onclick="return confirm('Apakah Anda yakin ingin menghapus foto proyek ini?');"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="4" style="text-align: center; color: var(--text-muted); padding: 30px;">Belum ada foto proyek diunggah.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>
