<?php
session_start();

if (empty($_SESSION['namauser']) && empty($_SESSION['passuser'])) {
    echo "<link href='../../css/style_login.css' rel='stylesheet' type='text/css' />
          <div id='login'><h1 class='fail'>Untuk mengakses modul, Anda harus login dulu.</h1>
          <p class='fail'><a href='../../index.php'>LOGIN</a></p></div>";
    exit();
}

include "../../../config/koneksi.php";
include "../../../config/fungsi_seo.php";

$module = $_GET['module'] ?? '';
$act    = $_GET['act'] ?? '';

// Helper Function: Konversi File Gambar Ke Format WEBP
function convertToWebp($tmpPath, $ext, $destinationPath, $quality = 80) {
    $img = false;
    switch ($ext) {
        case 'jpg':
        case 'jpeg':
            $img = @imagecreatefromjpeg($tmpPath);
            break;
        case 'png':
            $img = @imagecreatefrompng($tmpPath);
            if ($img) {
                imagepalettetotruecolor($img);
                imagealphablending($img, true);
                imagesavealpha($img, true);
            }
            break;
        case 'gif':
            $img = @imagecreatefromgif($tmpPath);
            break;
        case 'webp':
            $img = @imagecreatefromwebp($tmpPath);
            break;
    }

    if ($img) {
        imagewebp($img, $destinationPath, $quality);
        imagedestroy($img);
        return true;
    }
    return false;
}

// ==========================================
// ACTION: HAPUS GALERI FOTO
// ==========================================
if ($module == 'galerifoto' && $act == 'hapus') {
    $id    = mysqli_real_escape_string($konek, $_GET['id'] ?? '');
    $query = "SELECT gambar FROM galeri WHERE id_galeri='$id'";
    $hapus = mysqli_query($konek, $query);
    $r     = mysqli_fetch_array($hapus);

    if ($r) {
        if (!empty($r['gambar']) && file_exists("../../../foto_galeri/" . $r['gambar'])) {
            unlink("../../../foto_galeri/" . $r['gambar']);
        }
        mysqli_query($konek, "DELETE FROM galeri WHERE id_galeri='$id'");
    }

    header("location:../../media.php?module=" . $module);
    exit();
}

// ==========================================
// ACTION: INPUT GALERI FOTO (TAMBAH)
// ==========================================
elseif ($module == 'galerifoto' && $act == 'input') {
    $judul_galeri = mysqli_real_escape_string($konek, $_POST['judul_galeri'] ?? '');
    $galeri_seo   = seo_title($_POST['judul_galeri'] ?? '');

    $allowed_ext = array('png', 'jpg', 'jpeg', 'gif', 'webp');
    $folder      = "../../../foto_galeri/";

    if (!empty($_FILES['foto']['name'][0])) {
        foreach ($_FILES['foto']['name'] as $key => $filename) {
            if (empty($filename)) continue;

            $ukuran = $_FILES['foto']['size'][$key];
            $tmp    = $_FILES['foto']['tmp_name'][$key];
            $ext    = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

            if (!in_array($ext, $allowed_ext)) continue;
            if ($ukuran > 3145728) continue; // Maksimal 3MB

            $newname      = "galerifoto_" . time() . "_" . rand(100, 999) . ".webp";
            $destFilePath = $folder . $newname;

            if (convertToWebp($tmp, $ext, $destFilePath, 80)) {
                mysqli_query($konek, "INSERT INTO galeri(judul_galeri, galeri_seo, gambar) 
                                      VALUES('$judul_galeri', '$galeri_seo', '$newname')");
            }
        }
    } else {
        mysqli_query($konek, "INSERT INTO galeri(judul_galeri, galeri_seo, gambar) 
                              VALUES('$judul_galeri', '$galeri_seo', '')");
    }

    header("location:../../media.php?module=" . $module);
    exit();
}

// ==========================================
// ACTION: UPDATE GALERI FOTO (EDIT)
// ==========================================
elseif ($module == 'galerifoto' && $act == 'update') {
    $id           = mysqli_real_escape_string($konek, $_POST['id'] ?? '');
    $judul_galeri = mysqli_real_escape_string($konek, $_POST['judul_galeri'] ?? '');
    $galeri_seo   = seo_title($_POST['judul_galeri'] ?? '');
    $fotoku       = $_POST['fotoku'] ?? '';

    $allowed_ext = array('png', 'jpg', 'jpeg', 'gif', 'webp');
    $filename    = $_FILES['foto']['name'] ?? '';
    $folder      = "../../../foto_galeri/";

    if (empty($filename)) {
        mysqli_query($konek, "UPDATE galeri SET 
                                judul_galeri = '$judul_galeri', 
                                galeri_seo   = '$galeri_seo' 
                              WHERE id_galeri = '$id'");
    } else {
        $ukuran = $_FILES['foto']['size'] ?? 0;
        $tmp    = $_FILES['foto']['tmp_name'] ?? '';
        $ext    = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        if (!in_array($ext, $allowed_ext)) {
            echo "<script>alert('Format file tidak diperbolehkan!'); window.history.back();</script>";
            exit();
        }

        if ($ukuran > 3145728) {
            echo "<script>alert('Ukuran gambar terlalu besar! (Maks 3MB)'); window.history.back();</script>";
            exit();
        }

        // Hapus foto lama jika ada
        if (!empty($fotoku) && file_exists($folder . $fotoku)) {
            unlink($folder . $fotoku);
        }

        $newname      = "galerifoto_" . time() . "_" . rand(100, 999) . ".webp";
        $destFilePath = $folder . $newname;

        if (convertToWebp($tmp, $ext, $destFilePath, 80)) {
            mysqli_query($konek, "UPDATE galeri SET 
                                    judul_galeri = '$judul_galeri', 
                                    galeri_seo   = '$galeri_seo', 
                                    gambar       = '$newname' 
                                  WHERE id_galeri = '$id'");
        }
    }

    header("location:../../media.php?module=" . $module);
    exit();
}
?>