<?php
include '../auth.php';
include '../../koneksi.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $id = $_POST['id']; // ID artikel
    $judul = $_POST['judul'];
    $konten = $_POST['konten'];
    $kategori = $_POST['kategori'];
    $meta_deskripsi = $_POST['meta_deskripsi'];
    $meta_keyword = $_POST['meta_keyword'];

    // Generate slug dari judul
    function buatSlug($text) {
        $text = strtolower($text);
        $text = preg_replace('/[^a-z0-9]+/i', '-', $text);
        $text = trim($text, '-');
        return $text;
    }

    $slug = buatSlug($judul);

    // Cek apakah slug sudah ada di database
    $slug_check = $slug;
    $counter = 1;
    while (true) {
        $querySlug = "SELECT id_detail_artikel FROM detail_artikel WHERE slug = ? AND id_detail_artikel != ?";
        $stmt = $conn->prepare($querySlug);
        $stmt->bind_param("si", $slug_check, $id);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows == 0) {
            break; // Slug unik
        } else {
            $slug_check = $slug . '-' . $counter;
            $counter++;
        }
    }
    $slug = $slug_check;
    $stmt->close();

    // Ambil id_seo_artikel dari detail_artikel
    $querySeo = "SELECT id_seo_artikel, gambar_artikel FROM detail_artikel WHERE id_detail_artikel = ?";
    $stmt = $conn->prepare($querySeo);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($id_seo_artikel, $gambar_lama);
    $stmt->fetch();
    $stmt->close();

    // Update SEO Artikel
    $querySeoUpdate = "UPDATE seo_artikel SET katakunci_seo=?, deskripsi_seo=? WHERE id_seo_artikel=?";
    $stmt = $conn->prepare($querySeoUpdate);
    $stmt->bind_param("ssi", $meta_keyword, $meta_deskripsi, $id_seo_artikel);
    $stmt->execute();
    $stmt->close();

    // Periksa apakah ada gambar baru
    if ($_FILES['gambar']['name']) {
        $gambar_baru = $_FILES['gambar']['name'];
        $gambar_tmp = $_FILES['gambar']['tmp_name'];
        $path_upload = "../../uploads/artikel/" . $gambar_baru;

        // **VALIDASI FORMAT GAMBAR**
        $allowed_types = ['image/jpeg', 'image/jpg', 'image/png'];
        $file_mime = mime_content_type($gambar_tmp);

        if (!in_array($file_mime, $allowed_types)) {
            $_SESSION['error'] = "Format gambar tidak valid! Gunakan JPG, JPEG, atau PNG.";
            header("Location: ../artikel/update.php?id=$id");
            exit();
        }

        // Hapus gambar lama jika ada
        if ($gambar_lama && file_exists("../../uploads/artikel/" . $gambar_lama)) {
            unlink("../../uploads/artikel/" . $gambar_lama);
        }

        // Pindahkan gambar baru ke folder
        move_uploaded_file($gambar_tmp, $path_upload);
    } else {
        $gambar_baru = $gambar_lama; // Jika tidak ada gambar baru, gunakan yang lama
    }

    // Update Detail Artikel
    $query = "UPDATE detail_artikel SET judul_artikel=?, slug=?, deskripsi_artikel=?, kategori=?, gambar_artikel=? WHERE id_detail_artikel =?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("sssssi", $judul, $slug, $konten, $kategori, $gambar_baru, $id);

    if ($stmt->execute()) {
        $_SESSION['success'] = "Artikel berhasil diperbarui!";
        header("Location: ../artikel");
    } else {
        $_SESSION['error'] = "Gagal memperbarui artikel!";
        header("Location: ../artikel");
    }

    $stmt->close();
    $conn->close();
}
?>
