<?php
session_start();

// Security Guard: Batasi akses jika session login tidak valid
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";
include "../../../config/fungsi_thumbnail.php";
include "../../../config/library.php";

// Penanganan opsional jika variabel $tgl_sekarang belum terdefinisi dari library.php
if (empty($tgl_sekarang)) {
    $tgl_sekarang = date('Y-m-d');
}

$module = isset($_GET['module']) ? $_GET['module'] : '';
$act    = isset($_GET['act']) ? $_GET['act'] : '';
$folder = "../../../foto_blog/";

// Pastikan direktori penampung foto tersedia
if (!file_exists($folder)) {
    mkdir($folder, 0755, true);
}

// =========================================================================
// 1. HAPUS BLOG
// =========================================================================
if ($module == 'blog' && $act == 'hapus') {
    $id = mysqli_real_escape_string($konek, $_GET['id'] ?? '');

    if (!empty($id)) {
        // Ambil nama file gambar terlebih dahulu
        $query  = "SELECT gambar FROM blog WHERE id_blog='$id'";
        $result = mysqli_query($konek, $query);
        $r      = mysqli_fetch_array($result);

        // Hapus fisik file foto jika ada
        if (!empty($r['gambar']) && file_exists($folder . $r['gambar'])) {
            unlink($folder . $r['gambar']);
        }

        // Hapus record dari database
        mysqli_query($konek, "DELETE FROM blog WHERE id_blog='$id'");
    }

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

// =========================================================================
// 2. INPUT / TAMBAH BLOG
// =========================================================================
elseif ($module == 'blog' && $act == 'input') {
    $judul_blog = mysqli_real_escape_string($konek, $_POST['judul_blog'] ?? '');
    $blog_seo   = seo_title($_POST['judul_blog'] ?? '');
    $isi_blog   = mysqli_real_escape_string($konek, $_POST['isi_blog'] ?? '');

    $filename    = $_FILES['foto']['name'] ?? '';
    $ukuran      = $_FILES['foto']['size'] ?? 0;
    $tmp         = $_FILES['foto']['tmp_name'] ?? '';
    $allowed_ext = array('png', 'jpg', 'jpeg', 'gif', 'webp');
    $ext         = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

    // Opsi A: Tanpa Unggah Gambar
    if (empty($filename)) {
        $queryInsert = "INSERT INTO blog (judul_blog, blog_seo, isi_blog, tgl_posting, gambar) 
                        VALUES ('$judul_blog', '$blog_seo', '$isi_blog', '$tgl_sekarang', '')";
        
        mysqli_query($konek, $queryInsert);
        header("Location: ../../media.php?module=" . $module);
        exit();
    } 
    // Opsi B: Dengan Unggah & Konversi Gambar
    else {
        if (!in_array($ext, $allowed_ext)) {
            echo "<script>alert('Ekstensi gambar tidak diperbolehkan!'); window.history.back();</script>";
            exit();
        }

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

        $newname = "BLOG_" . time() . "_" . rand(100, 999) . ".webp";
        $img     = null;

        // Load image resource berdasarkan tipe file
        switch ($ext) {
            case 'jpg':
            case 'jpeg':
                $img = @imagecreatefromjpeg($tmp);
                break;
            case 'png':
                $img = @imagecreatefrompng($tmp);
                if ($img) {
                    imagepalettetotruecolor($img);
                    imagealphablending($img, true);
                    imagesavealpha($img, true);
                }
                break;
            case 'gif':
                $img = @imagecreatefromgif($tmp);
                break;
            case 'webp':
                $img = @imagecreatefromwebp($tmp);
                break;
        }

        if ($img) {
            // Simpan gambar yang sudah dikonversi ke format WebP
            imagewebp($img, $folder . $newname, 80);
            imagedestroy($img);
        } else {
            // Fallback: Jika GD Library gagal, pindahkan berkas asli
            move_uploaded_file($tmp, $folder . $newname);
        }

        $queryInsert = "INSERT INTO blog (judul_blog, blog_seo, isi_blog, tgl_posting, gambar) 
                        VALUES ('$judul_blog', '$blog_seo', '$isi_blog', '$tgl_sekarang', '$newname')";
        
        mysqli_query($konek, $queryInsert);
        header("Location: ../../media.php?module=" . $module);
        exit();
    }
}

// =========================================================================
// 3. UPDATE / EDIT BLOG
// =========================================================================
elseif ($module == 'blog' && $act == 'update') {
    $id         = mysqli_real_escape_string($konek, $_POST['id'] ?? '');
    $judul_blog = mysqli_real_escape_string($konek, $_POST['judul_blog'] ?? '');
    $blog_seo   = seo_title($_POST['judul_blog'] ?? '');
    $isi_blog   = mysqli_real_escape_string($konek, $_POST['isi_blog'] ?? '');
    $fotoku     = mysqli_real_escape_string($konek, $_POST['fotoku'] ?? ''); // Gambar lama

    $filename    = $_FILES['foto']['name'] ?? '';
    $ukuran      = $_FILES['foto']['size'] ?? 0;
    $tmp         = $_FILES['foto']['tmp_name'] ?? '';
    $allowed_ext = array('png', 'jpg', 'jpeg', 'gif', 'webp');
    $ext         = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

    // Opsi A: Gambar Tidak Diganti (Perbarui Tanggal Ke Hari Ini)
    if (empty($filename)) {
        $queryUpdate = "UPDATE blog SET 
                            judul_blog  = '$judul_blog', 
                            blog_seo    = '$blog_seo', 
                            isi_blog    = '$isi_blog',
                            tgl_posting = '$tgl_sekarang' 
                        WHERE id_blog   = '$id'";

        mysqli_query($konek, $queryUpdate);
        header("Location: ../../media.php?module=" . $module);
        exit();
    } 
    // Opsi B: Gambar Diganti (Perbarui Gambar & Tanggal Ke Hari Ini)
    else {
        if (!in_array($ext, $allowed_ext)) {
            echo "<script>alert('Ekstensi gambar tidak diperbolehkan!'); window.history.back();</script>";
            exit();
        }

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

        // Hapus fisik gambar lama dari folder
        if (!empty($fotoku) && file_exists($folder . $fotoku)) {
            unlink($folder . $fotoku);
        }

        $newname = "BLOG_" . time() . "_" . rand(100, 999) . ".webp";
        $img     = null;

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

        if ($img) {
            imagewebp($img, $folder . $newname, 80);
            imagedestroy($img);
        } else {
            move_uploaded_file($tmp, $folder . $newname);
        }

        $queryUpdate = "UPDATE blog SET 
                            judul_blog  = '$judul_blog', 
                            blog_seo    = '$blog_seo', 
                            isi_blog    = '$isi_blog', 
                            tgl_posting = '$tgl_sekarang',
                            gambar      = '$newname' 
                        WHERE id_blog   = '$id'";

        mysqli_query($konek, $queryUpdate);
        header("Location: ../../media.php?module=" . $module);
        exit();
    }
}
?>