<?php
session_start();

// 1. Session Guard (Akses Keamanan)
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;
}

// 2. Load Koneksi Database
include "../../../config/koneksi.php";

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

// 3. Sanitasi Input untuk Mencegah SQL Injection & Error
$id      = mysqli_real_escape_string($konek, $_POST['id'] ?? '');
$wa      = mysqli_real_escape_string($konek, $_POST['wa'] ?? '');
$tlp     = mysqli_real_escape_string($konek, $_POST['tlp'] ?? '');
$email   = mysqli_real_escape_string($konek, $_POST['email'] ?? '');
$alamat  = mysqli_real_escape_string($konek, $_POST['alamat'] ?? '');
$maps    = mysqli_real_escape_string($konek, $_POST['maps'] ?? '');
$fb      = mysqli_real_escape_string($konek, $_POST['fb'] ?? '');
$tw      = mysqli_real_escape_string($konek, $_POST['tw'] ?? '');
$ig      = mysqli_real_escape_string($konek, $_POST['ig'] ?? '');
$lingked = mysqli_real_escape_string($konek, $_POST['lingked'] ?? '');
$tiktok  = mysqli_real_escape_string($konek, $_POST['tiktok'] ?? '');

// 4. Cek File Logo Upload
$lokasi_file = $_FILES['logo']['tmp_name'] ?? '';
$nama_file   = $_FILES['logo']['name'] ?? '';
$error_file  = $_FILES['logo']['error'] ?? UPLOAD_ERR_NO_FILE;

// ==================================================
// SKENARIO A: TIDAK ADA LOGO DIUPLOAD → UPDATE DATA SAJA
// ==================================================
if ($error_file === UPLOAD_ERR_NO_FILE || empty($nama_file)) {
    $query = "UPDATE kontak SET 
                wa      = '$wa',
                tlp     = '$tlp',
                email   = '$email',
                alamat  = '$alamat',
                maps    = '$maps',
                fb      = '$fb',
                tw      = '$tw',
                ig      = '$ig',
                lingked = '$lingked',
                tiktok  = '$tiktok'
              WHERE id_kontak = '$id'";

    mysqli_query($konek, $query);

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

// ==================================================
// SKENARIO B: ADA LOGO DIUPLOAD → PROSES ALUR FOTO
// ==================================================
$folder = "../../../foto_icon/";
if (!file_exists($folder)) {
    mkdir($folder, 0777, true);
}

// Nama file WebP unik
$nama_file_webp = uniqid("logo-", true) . ".webp";
$target_webp    = $folder . $nama_file_webp;
$ext            = strtolower(pathinfo($nama_file, PATHINFO_EXTENSION));

// 1. Hapus Logo Lama dari Server
$q   = mysqli_query($konek, "SELECT logo FROM kontak WHERE id_kontak='$id'");
$old = mysqli_fetch_assoc($q);
if (!empty($old['logo']) && file_exists($folder . $old['logo'])) {
    unlink($folder . $old['logo']);
}

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

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

// Jika gambar berhasil diproses dari format JPG/PNG/GIF, simpan sebagai WebP
if ($img) {
    imagewebp($img, $target_webp, 88);
    imagedestroy($img); // Bebaskan memory GD
}

// 3. Update Database Berkelanjutan
$query_full = "UPDATE kontak SET 
                wa      = '$wa',
                tlp     = '$tlp',
                email   = '$email',
                alamat  = '$alamat',
                maps    = '$maps',
                fb      = '$fb',
                tw      = '$tw',
                ig      = '$ig',
                tiktok  = '$tiktok',
                lingked = '$lingked',
                logo    = '$nama_file_webp'
              WHERE id_kontak = '$id'";

mysqli_query($konek, $query_full);

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