<?php
session_start();

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

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

// Tangkap & Amankan Input Data
$id             = mysqli_real_escape_string($konek, $_POST['id'] ?? '');
$nama_pemilik   = mysqli_real_escape_string($konek, $_POST['nama_pemilik'] ?? '');
$judul_website  = mysqli_real_escape_string($konek, $_POST['judul_website'] ?? '');
$alamat_website = mysqli_real_escape_string($konek, $_POST['alamat_website'] ?? '');
$meta_deskripsi = mysqli_real_escape_string($konek, $_POST['meta_deskripsi'] ?? '');
$meta_keyword   = mysqli_real_escape_string($konek, $_POST['meta_keyword'] ?? '');
$googleplus     = mysqli_real_escape_string($konek, $_POST['googleplus'] ?? '');

// Detail Upload File
$lokasi_file = $_FILES['foto']['tmp_name'] ?? '';
$nama_file   = $_FILES['foto']['name'] ?? '';
$error_file  = $_FILES['foto']['error'] ?? 4;

// ==================================================
// 1. UPDATE TANPA GANTI LOGO/FAVICON
// ==================================================
if ($error_file === 4 || empty($lokasi_file)) {
    $edit = "UPDATE identitas SET 
                nama_pemilik   = '$nama_pemilik',
                judul_website  = '$judul_website',
                alamat_website = '$alamat_website',
                meta_deskripsi = '$meta_deskripsi',
                meta_keyword   = '$meta_keyword',
                googleplus     = '$googleplus'
            WHERE id_identitas = '$id'";

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

// ==================================================
// 2. PROSES UPLOAD & KONVERSI WEBP
// ==================================================
$folder = "../../../foto_icon/";
if (!file_exists($folder)) {
    mkdir($folder, 0777, true);
}

// A. Cari & Hapus Favicon Lama berdasarkan Database
$query_old = mysqli_query($konek, "SELECT favicon FROM identitas WHERE id_identitas='$id'");
$data_old  = mysqli_fetch_array($query_old);

if (!empty($data_old['favicon'])) {
    $old_filepath = $folder . $data_old['favicon'];
    if (file_exists($old_filepath)) {
        unlink($old_filepath);
    }
}

// B. Prepare Penamaan WebP Baru
$nama_file_webp = uniqid("favicon-", true) . ".webp";
$target_webp    = $folder . $nama_file_webp;
$ext            = strtolower(pathinfo($nama_file, PATHINFO_EXTENSION));

// C. Konversi Gambar ke Format WebP
$img = null;

if ($ext == 'jpg' || $ext == 'jpeg') {
    $img = imagecreatefromjpeg($lokasi_file);
} elseif ($ext == 'png') {
    $img = imagecreatefrompng($lokasi_file);
    imagepalettetotruecolor($img);
    imagealphablending($img, true);
    imagesavealpha($img, true);
} elseif ($ext == 'gif') {
    $img = imagecreatefromgif($lokasi_file);
} elseif ($ext == 'webp') {
    move_uploaded_file($lokasi_file, $target_webp);
} else {
    echo "<script>alert('Format file tidak didukung! Gunakan JPG, PNG, GIF, atau WEBP'); history.back();</script>";
    exit();
}

// Jika dari format JPG/PNG/GIF, simpan sebagai WebP
if ($img) {
    imagewebp($img, $target_webp, 85);
    imagedestroy($img);
}

// ==================================================
// 3. UPDATE DATABASE DENGAN LOGO BARU
// ==================================================
$edit = "UPDATE identitas SET 
            nama_pemilik   = '$nama_pemilik',
            judul_website  = '$judul_website',
            alamat_website = '$alamat_website',
            meta_deskripsi = '$meta_deskripsi',
            meta_keyword   = '$meta_keyword',
            googleplus     = '$googleplus',
            favicon        = '$nama_file_webp'
        WHERE id_identitas = '$id'";

mysqli_query($konek, $edit);

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