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

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'kader') {
    header("Location: ../login.php"); exit;
}

$id_posyandu = $_SESSION['posyandu'];
$message = "";

// --- FUNGSI HAPUS FOTO ---
if (isset($_GET['hapus'])) {
    $id_foto = (int)$_GET['hapus'];
    $stmt = $pdo->prepare("SELECT foto FROM galeri WHERE id_foto = ? AND id_posyandu = ?");
    $stmt->execute([$id_foto, $id_posyandu]);
    $f = $stmt->fetch();
    
    if ($f) {
        $path = "../uploads/gallery/" . $f['foto'];
        if (file_exists($path)) { @unlink($path); }
        $del = $pdo->prepare("DELETE FROM galeri WHERE id_foto = ?");
        $del->execute([$id_foto]);
        $message = "<div class='alert alert-danger p-2 small mb-2'>Foto berhasil dihapus!</div>";
    }
}

// --- PROSES UNGGAH ---
if (isset($_POST['upload']) && isset($_FILES['foto'])) {
    $bulan = $_POST['bulan'];
    $tahun = $_POST['tahun'];
    $ket = $_POST['keterangan'];
    $file_tmp = $_FILES["foto"]["tmp_name"];
    
    $target_dir = "../uploads/gallery/";
    if (!file_exists($target_dir)) { 
        mkdir($target_dir, 0777, true); 
    }

    $ext = pathinfo($_FILES["foto"]["name"], PATHINFO_EXTENSION);
    $file_name = "GAL_" . time() . "." . $ext;
    $target_file = $target_dir . $file_name;

    // Cek apakah fungsi GD Library tersedia untuk kompresi
    if (function_exists('imagecreatefromjpeg')) {
        // PROSES DENGAN KOMPRESI
        list($width, $height, $type) = getimagesize($file_tmp);
        $source = null;
        if ($type == IMAGETYPE_JPEG) $source = imagecreatefromjpeg($file_tmp);
        elseif ($type == IMAGETYPE_PNG) $source = imagecreatefrompng($file_tmp);
        elseif ($type == IMAGETYPE_GIF) $source = imagecreatefromgif($file_tmp);

        if ($source) {
            imagejpeg($source, $target_file, 60); // Kompres 60%
            imagedestroy($source);
        } else {
            move_uploaded_file($file_tmp, $target_file); // Gagal olah, upload biasa
        }
    } else {
        // JIKA GD LIBRARY TIDAK ADA, UPLOAD BIASA (Mencegah Error 500)
        move_uploaded_file($file_tmp, $target_file);
    }

    $stmt = $pdo->prepare("INSERT INTO galeri (id_posyandu, bulan, tahun, foto, keterangan) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([$id_posyandu, $bulan, $tahun, $file_name, $ket]);
    $message = "<div class='alert alert-success p-2 small mb-2'>Foto berhasil diunggah!</div>";
}

// FILTER
$f_bulan = $_GET['f_bulan'] ?? date('m');
$f_tahun = $_GET['f_tahun'] ?? date('Y');

$stmt_g = $pdo->prepare("SELECT * FROM galeri WHERE id_posyandu = ? AND bulan = ? AND tahun = ? ORDER BY id_foto DESC");
$stmt_g->execute([$id_posyandu, $f_bulan, $f_tahun]);
$fotos = $stmt_g->fetchAll();
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Galeri Kegiatan</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background: #f4f7fe; font-family: 'Segoe UI', sans-serif; }
        .card-custom { border: none; border-radius: 15px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); }
        .img-container { position: relative; overflow: hidden; }
        .img-preview { width: 100%; height: 120px; object-fit: cover; border-radius: 10px; }
        .btn-delete { 
            position: absolute; top: 5px; right: 5px; 
            background: rgba(255, 255, 255, 0.9); 
            color: #dc3545; border: none; 
            width: 28px; height: 28px; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
        }
    </style>
</head>
<body>

<div class="container py-3">
    <div class="d-flex align-items-center mb-3">
        <a href="dashboard.php" class="btn btn-white shadow-sm rounded-circle me-3" style="background:white; width:35px; height:35px; display:flex; align-items:center; justify-content:center;">
            <i class="fa fa-arrow-left text-primary"></i>
        </a>
        <h5 class="fw-bold mb-0">Unggah Dokumentasi</h5>
    </div>

    <?= $message ?>

    <div class="card card-custom mb-4">
        <div class="card-body p-3">
            <form method="POST" enctype="multipart/form-data">
                <div class="row g-2 mb-2">
                    <div class="col-6">
                        <select name="bulan" class="form-select form-select-sm">
                            <?php for($m=1;$m<=12;$m++){ $v=sprintf('%02d',$m); echo "<option value='$v'".($f_bulan==$v?' selected':'').">Bulan $m</option>"; } ?>
                        </select>
                    </div>
                    <div class="col-6">
                        <input type="number" name="tahun" class="form-control form-control-sm" value="<?= date('Y') ?>">
                    </div>
                </div>
                <input type="file" name="foto" class="form-control form-control-sm mb-2" accept="image/*" required>
                <input type="text" name="keterangan" class="form-control form-control-sm mb-2" placeholder="Keterangan, ex: Foto timbang badan...">
                <button type="submit" name="upload" class="btn btn-primary btn-sm w-100 fw-bold">SIMPAN DOKUMENTASI</button>
            </form>
        </div>
    </div>

    <div class="d-flex justify-content-between mb-3 align-items-center">
        <h6 class="fw-bold mb-0 small">Bulan <?= $f_bulan ?>/<?= $f_tahun ?></h6>
        <form method="GET">
            <select name="f_bulan" onchange="this.form.submit()" class="form-select form-select-sm" style="width:80px;">
                <?php for($m=1;$m<=12;$m++){ $v=sprintf('%02d',$m); echo "<option value='$v'".($f_bulan==$v?' selected':'').">$m</option>"; } ?>
            </select>
        </form>
    </div>

    <div class="row g-2">
        <?php if(empty($fotos)): ?>
            <div class="col-12 text-center text-muted py-4">Belum ada foto.</div>
        <?php endif; ?>
        <?php foreach($fotos as $f): ?>
        <div class="col-6">
            <div class="bg-white p-1 rounded shadow-sm img-container">
                <img src="../uploads/gallery/<?= $f['foto'] ?>" class="img-preview" onerror="this.src='https://placehold.co/400x300?text=Gambar+Hilang'">
                <a href="?hapus=<?= $f['id_foto'] ?>&f_bulan=<?= $f_bulan ?>" class="btn-delete" onclick="return confirm('Hapus foto ini?')">
                    <i class="fa fa-trash"></i>
                </a>
                <p class="small text-truncate mb-0 mt-1 px-1" style="font-size: 10px; color:#555;"><?= $f['keterangan'] ?></p>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

</body>
</html>