<?php
session_start();

// Validasi Login 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";

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

// ==========================================
// 1. ACTION: HAPUS PROFIL
// ==========================================
if ($module == 'profil' && $act == 'hapus') {
    $id    = mysqli_real_escape_string($konek, $_GET['id']);
    $query = "SELECT gambar FROM profil WHERE id_profil='$id'";
    $hapus = mysqli_query($konek, $query);
    $r     = mysqli_fetch_array($hapus);

    // Hapus fisik gambar jika ada
    if (!empty($r['gambar'])) {
        $path_file = "../../../foto_profil/" . $r['gambar'];
        if (file_exists($path_file)) {
            unlink($path_file);
        }
    }

    // Hapus data dari database
    mysqli_query($konek, "DELETE FROM profil WHERE id_profil='$id'");
    header("location:../../media.php?module=" . $module);
    exit();
}

// ==========================================
// 2. ACTION: INPUT PROFIL BARU
// ==========================================
elseif ($module == 'profil' && $act == 'input') {
    $judul_profil = mysqli_real_escape_string($konek, $_POST['judul_profil']);
    $profil_seo   = seo_title($_POST['judul_profil']);
    $isi_profil   = mysqli_real_escape_string($konek, $_POST['isi_profil']);

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

    // Jika tanpa upload gambar
    if (empty($filename)) {
        mysqli_query($konek, "INSERT INTO profil (judul_profil, profil_seo, isi_profil, gambar) 
                              VALUES ('$judul_profil', '$profil_seo', '$isi_profil', '')");
        header("location:../../media.php?module=" . $module);
        exit();
    } 
    // Jika mengunggah gambar
    else {
        if (!in_array($ext, $allowed_ext)) {
            echo "<script>alert('Format gambar tidak didukung!'); window.history.back();</script>";
            exit();
        }

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

        // Generate nama file unik & konversi ke WEBP
        $newname = "HAL_" . time() . "_" . rand(100, 999) . ".webp";
        $img     = null;

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

        if ($img) {
            imagewebp($img, $folder . $newname, 80);
            imagedestroy($img);
        } else {
            // Fallback jika GD library gagal konversi WebP
            move_uploaded_file($tmp_name, $folder . $newname);
        }

        mysqli_query($konek, "INSERT INTO profil (judul_profil, profil_seo, isi_profil, gambar) 
                              VALUES ('$judul_profil', '$profil_seo', '$isi_profil', '$newname')");
        header("location:../../media.php?module=" . $module);
        exit();
    }
}

// ==========================================
// 3. ACTION: UPDATE PROFIL
// ==========================================
elseif ($module == 'profil' && $act == 'update') {
    $id           = mysqli_real_escape_string($konek, $_POST['id']);
    $judul_profil = mysqli_real_escape_string($konek, $_POST['judul_profil']);
    $profil_seo   = seo_title($_POST['judul_profil']);
    $isi_profil   = mysqli_real_escape_string($konek, $_POST['isi_profil']);
    $fotoku       = mysqli_real_escape_string($konek, $_POST['fotoku'] ?? ''); // nama file lama

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

    // Jika gambar TIDAK diganti
    if (empty($filename)) {
        mysqli_query($konek, "UPDATE profil SET 
                                judul_profil = '$judul_profil',
                                profil_seo   = '$profil_seo',
                                isi_profil   = '$isi_profil'
                              WHERE id_profil = '$id'");
        header("location:../../media.php?module=" . $module);
        exit();
    } 
    // Jika gambar DIGANTI
    else {
        if (!in_array($ext, $allowed_ext)) {
            echo "<script>alert('Format gambar tidak didukung!'); window.history.back();</script>";
            exit();
        }

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

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

        // Konversi gambar baru ke WEBP & kompres 80%
        $newname = "HAL_" . time() . "_" . rand(100, 999) . ".webp";
        $img     = null;

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

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

        mysqli_query($konek, "UPDATE profil SET 
                                judul_profil = '$judul_profil',
                                profil_seo   = '$profil_seo',
                                isi_profil   = '$isi_profil',
                                gambar       = '$newname'
                              WHERE id_profil = '$id'");

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