<?php
session_start();

// Guard Session Login
if (empty($_SESSION['namauser']) && empty($_SESSION['passuser'])) {
    echo "<script>alert('Akses ditolak! Silahkan login terlebih dahulu.'); window.location='../../index.php';</script>";
    exit();
}

include "../../../config/koneksi.php";

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

// Path folder gambar (Disesuaikan dengan hirarki folder)
$target_dir = "../../../foto_banner/";

// ================= HAPUS BANNER =================
if ($module == 'banner' && $act == 'hapus') {
    $id = mysqli_real_escape_string($konek, $_GET['id'] ?? '');

    if (!empty($id)) {
        // Ambil nama gambar sebelum dihapus dari database
        $query = "SELECT gambar FROM banner WHERE id_banner='$id'";
        $hapus = mysqli_query($konek, $query);
        $r     = mysqli_fetch_array($hapus);

        if (!empty($r['gambar']) && file_exists($target_dir . $r['gambar'])) {
            unlink($target_dir . $r['gambar']);
        }

        // Hapus record dari DB
        mysqli_query($konek, "DELETE FROM banner WHERE id_banner='$id'");
    }

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

// ================= INPUT BANNER =================
elseif ($module == 'banner' && $act == 'input') {
    $judul      = mysqli_real_escape_string($konek, $_POST['judul'] ?? '');
    $isi_banner = mysqli_real_escape_string($konek, $_POST['isi_banner'] ?? '');

    $filename   = $_FILES['foto']['name'] ?? '';
    $ukuran     = $_FILES['foto']['size'] ?? 0;
    $tmp        = $_FILES['foto']['tmp_name'] ?? '';
    $ext        = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

    $ekstensi_diperbolehkan = array('png', 'jpg', 'jpeg', 'gif', 'webp');

    // Jika tidak ada gambar yang diupload
    if (empty($filename)) {
        mysqli_query($konek, "INSERT INTO banner(judul, isi_banner, gambar) VALUES('$judul', '$isi_banner', '')");
        header("location:../../media.php?module=" . $module);
        exit();
    }

    // Validasi Ekstensi
    if (!in_array($ext, $ekstensi_diperbolehkan)) {
        echo "<script>alert('Format gambar tidak valid! Gunakan JPG, PNG, GIF, atau WEBP.'); history.back();</script>";
        exit();
    }

    // Validasi Ukuran (Max 2MB)
    if ($ukuran > 2048000) {
        echo "<script>alert('Upload gagal, ukuran file terlalu besar! (Max 2MB)'); history.back();</script>";
        exit();
    }

    // Generate Nama Random WebP
    $newfile = bin2hex(random_bytes(8)) . ".webp";

    // Konversi ke WebP
    $img = false;
    if ($ext == 'jpg' || $ext == 'jpeg') $img = @imagecreatefromjpeg($tmp);
    elseif ($ext == 'png')               $img = @imagecreatefrompng($tmp);
    elseif ($ext == 'gif')               $img = @imagecreatefromgif($tmp);
    elseif ($ext == 'webp')              $img = @imagecreatefromwebp($tmp);

    if ($img) {
        imagewebp($img, $target_dir . $newfile, 80);
        imagedestroy($img);
    } else {
        // Fallback jika GD konversi gagal, pakai move_uploaded_file biasa
        $newfile = bin2hex(random_bytes(8)) . "." . $ext;
        move_uploaded_file($tmp, $target_dir . $newfile);
    }

    mysqli_query($konek, "INSERT INTO banner(judul, isi_banner, gambar) VALUES('$judul', '$isi_banner', '$newfile')");
    header("location:../../media.php?module=" . $module);
    exit();
}

// ================= UPDATE BANNER =================
elseif ($module == 'banner' && $act == 'update') {
    $id         = mysqli_real_escape_string($konek, $_POST['id'] ?? '');
    $judul      = mysqli_real_escape_string($konek, $_POST['judul'] ?? '');
    $isi_banner = mysqli_real_escape_string($konek, $_POST['isi_banner'] ?? ''); // Perbaikan: Variabel yang sebelumnya terlewat
    $fotoku     = mysqli_real_escape_string($konek, $_POST['fotoku'] ?? '');

    $filename   = $_FILES['foto']['name'] ?? '';
    $ukuran     = $_FILES['foto']['size'] ?? 0;
    $tmp        = $_FILES['foto']['tmp_name'] ?? '';
    $ext        = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

    $ekstensi_diperbolehkan = array('png', 'jpg', 'jpeg', 'gif', 'webp');

    // Jika gambar tidak diganti
    if (empty($filename)) {
        mysqli_query($konek, "UPDATE banner SET judul='$judul', isi_banner='$isi_banner' WHERE id_banner='$id'");
        header("location:../../media.php?module=" . $module);
        exit();
    }

    // Validasi Ekstensi
    if (!in_array($ext, $ekstensi_diperbolehkan)) {
        echo "<script>alert('Format gambar tidak valid! Gunakan JPG, PNG, GIF, atau WEBP.'); history.back();</script>";
        exit();
    }

    // Validasi Ukuran (Max 2MB)
    if ($ukuran > 2048000) {
        echo "<script>alert('Upload gagal, ukuran file terlalu besar! (Max 2MB)'); history.back();</script>";
        exit();
    }

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

    // Generate Nama Random WebP
    $newfile = bin2hex(random_bytes(8)) . ".webp";

    // Konversi ke WebP
    $img = false;
    if ($ext == 'jpg' || $ext == 'jpeg') $img = @imagecreatefromjpeg($tmp);
    elseif ($ext == 'png')               $img = @imagecreatefrompng($tmp);
    elseif ($ext == 'gif')               $img = @imagecreatefromgif($tmp);
    elseif ($ext == 'webp')              $img = @imagecreatefromwebp($tmp);

    if ($img) {
        imagewebp($img, $target_dir . $newfile, 80);
        imagedestroy($img);
    } else {
        $newfile = bin2hex(random_bytes(8)) . "." . $ext;
        move_uploaded_file($tmp, $target_dir . $newfile);
    }

    mysqli_query($konek, "UPDATE banner SET judul='$judul', isi_banner='$isi_banner', gambar='$newfile' WHERE id_banner='$id'");
    header("location:../../media.php?module=" . $module);
    exit();
}
?>