<?php
session_start();

// Guard Akses Session
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/library.php";
include "../../../config/fungsi_seo.php";
include "../../../config/fungsi_thumbnail.php";

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

// ==========================================
// HAPUS LAYANAN (BERIKUT PDF & GALERI)
// ==========================================
if ($module == 'layanan' && $act == 'hapus') {
    $id = mysqli_real_escape_string($konek, $_GET['id'] ?? '');

    

    // 3. Hapus File Gambar Galeri dari Folder foto_layanan
    $ambil_gambar = mysqli_query($konek, "SELECT nama_file FROM semua_gambar WHERE id_layanan='$id'");
    while ($img = mysqli_fetch_array($ambil_gambar)) {
        $file = $img['nama_file'];
        if (!empty($file)) {
            $path_gambar = "../../../foto_layanan/" . $file;
            if (file_exists($path_gambar)) {
                @unlink($path_gambar);
            }
        }
    }

    // 4. Hapus Record Gambar dari Database
    mysqli_query($konek, "DELETE FROM semua_gambar WHERE id_layanan='$id'");

    // 5. Hapus Record Layanan dari Database
    mysqli_query($konek, "DELETE FROM layanan WHERE id_layanan='$id'");

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

// ==========================================
// INPUT LAYANAN BARU
// ==========================================
elseif ($module == 'layanan' && $act == 'input') {
    $judul       = mysqli_real_escape_string($konek, $_POST['judul'] ?? '');
    $judul_seo   = seo_title($_POST['judul'] ?? '');
    $isi_layanan = mysqli_real_escape_string($konek, $_POST['isi_layanan'] ?? '');

    // Insert ke tabel layanan (Koma ekstra dihapus)
    mysqli_query($konek, "INSERT INTO layanan(
        judul,
        judul_seo,
        isi_layanan
    ) VALUES(
        '$judul',
        '$judul_seo',
        '$isi_layanan'
    )");

    $id_layanan = mysqli_insert_id($konek);

    // Proses Multiple Upload Foto
    $ekstensi = array('png', 'jpg', 'jpeg', 'gif', 'webp');
    $folder   = "../../../foto_layanan/";

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

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

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

            $rand           = rand(100, 999);
            $nama_file_webp = time() . '_' . $rand . '.webp';
            $target_file    = $folder . $nama_file_webp;
            $image          = false;

            switch ($ext) {
                case 'jpg':
                case 'jpeg':
                    $image = @imagecreatefromjpeg($tmp_file);
                    break;
                case 'png':
                    $image = @imagecreatefrompng($tmp_file);
                    if ($image) {
                        imagepalettetotruecolor($image);
                        imagealphablending($image, true);
                        imagesavealpha($image, true);
                    }
                    break;
                case 'gif':
                    $image = @imagecreatefromgif($tmp_file);
                    break;
                case 'webp':
                    $image = @imagecreatefromwebp($tmp_file);
                    break;
            }

            if ($image) {
                imagewebp($image, $target_file, 60);
                imagedestroy($image);
                $gambar_simpan = $nama_file_webp;
            } else {
                $nama_asli     = time() . '_' . $rand . '_' . basename($filename);
                move_uploaded_file($tmp_file, $folder . $nama_asli);
                $gambar_simpan = $nama_asli;
            }

            // Insert ke tabel semua_gambar
            mysqli_query($konek, "INSERT INTO semua_gambar(
                id_layanan,
                nama_file
            ) VALUES(
                '$id_layanan',
                '$gambar_simpan'
            )");
        }
    }

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

// ==========================================
// UPDATE LAYANAN
// ==========================================
elseif ($module == 'layanan' && $act == 'update') {
    $id          = mysqli_real_escape_string($konek, $_POST['id'] ?? '');
    $judul       = mysqli_real_escape_string($konek, $_POST['judul'] ?? '');
    $judul_seo   = seo_title($_POST['judul'] ?? '');
    $isi_layanan = mysqli_real_escape_string($konek, $_POST['isi_layanan'] ?? '');

    // Update data utama layanan (Koma ekstra dihapus)
    mysqli_query($konek, "UPDATE layanan SET
        judul       = '$judul',
        judul_seo   = '$judul_seo',
        isi_layanan = '$isi_layanan'
    WHERE id_layanan = '$id'");

    // Tambah Gambar Baru Jika Ada
    $ekstensi = array('png', 'jpg', 'jpeg', 'gif', 'webp');
    $folder   = "../../../foto_layanan/";

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

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

            if (!in_array($ext, $ekstensi)) continue;
            if ($ukuran > 3145728) continue;

            $rand           = rand(100, 999);
            $nama_file_webp = time() . '_' . $rand . '.webp';
            $target_file    = $folder . $nama_file_webp;
            $image          = false;

            switch ($ext) {
                case 'jpg':
                case 'jpeg':
                    $image = @imagecreatefromjpeg($tmp_file);
                    break;
                case 'png':
                    $image = @imagecreatefrompng($tmp_file);
                    if ($image) {
                        imagepalettetotruecolor($image);
                        imagealphablending($image, true);
                        imagesavealpha($image, true);
                    }
                    break;
                case 'gif':
                    $image = @imagecreatefromgif($tmp_file);
                    break;
                case 'webp':
                    $image = @imagecreatefromwebp($tmp_file);
                    break;
            }

            if ($image) {
                imagewebp($image, $target_file, 60);
                imagedestroy($image);
                $gambar_simpan = $nama_file_webp;
            } else {
                $nama_asli     = time() . '_' . $rand . '_' . basename($filename);
                move_uploaded_file($tmp_file, $folder . $nama_asli);
                $gambar_simpan = $nama_asli;
            }

            mysqli_query($konek, "INSERT INTO semua_gambar(
                id_layanan,
                nama_file
            ) VALUES(
                '$id',
                '$gambar_simpan'
            )");
        }
    }

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

// ==========================================
// HAPUS SATUAN GAMBAR FOTO PRODUK
// ==========================================
elseif ($module == 'layanan' && $act == 'hapusgambar') {
    $id_gambar  = mysqli_real_escape_string($konek, $_GET['id'] ?? '');
    $id_layanan = mysqli_real_escape_string($konek, $_GET['layanan'] ?? '');

    $data = mysqli_fetch_array(mysqli_query($konek, "SELECT * FROM semua_gambar WHERE id_gambar='$id_gambar'"));

    if ($data) {
        $file = "../../../foto_layanan/" . $data['nama_file'];
        if (file_exists($file)) {
            @unlink($file);
        }
        mysqli_query($konek, "DELETE FROM semua_gambar WHERE id_gambar='$id_gambar'");
    }

    header("location:../../media.php?module=layanan&act=editlayanan&id=" . $id_layanan);
    exit();
}
?>