<?php
session_start();
include '../../koneksi.php'; // Pastikan koneksi tersedia

if ($_SERVER["REQUEST_METHOD"] == "POST") { 

    $id_seo = $_POST['id_seo'];
    $id_user = $_SESSION['user_id'];
    $judul_seo = trim($_POST['judul_seo']);
    $deskripsi_seo = trim($_POST['deskripsi_seo']);
    $meta_keyword = trim($_POST['meta_keyword']);

    if (empty($judul_seo) || empty($deskripsi_seo) || empty($meta_keyword)) {
        $_SESSION['error'] = "Semua bidang wajib diisi!";
        header("Location: ../seo/");
        exit();
    }

    // Ambil slug_url lama sebelum diubah
    $query = "SELECT slug_url FROM landingpage WHERE id_user = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $id_user);
    $stmt->execute();
    $stmt->bind_result($old_slug);
    $stmt->fetch();
    $stmt->close();

    // Buat slug baru berdasarkan judul_seo
    $slug_url = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $judul_seo), '-'));

    // Update tabel seo
    $sql = "UPDATE seo SET judul_seo = ?, deskripsi_seo = ?, katakunci_seo = ? WHERE id_seo = ? AND id_user = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssii", $judul_seo, $deskripsi_seo, $meta_keyword, $id_seo, $id_user);
    if ($stmt->execute()) {
        $_SESSION['success'] = "Pengaturan SEO berhasil diperbarui!";
    } else {
        $_SESSION['error'] = "Gagal memperbarui Pengaturan SEO!";
        header("Location: ../seo/");
        exit();
    }
    $stmt->close();

    // Jika judul_seo berubah, update slug_url pada landingpage dan rename folder
    if ($old_slug !== $slug_url) {
        $update_slug = "UPDATE landingpage SET slug_url = ? WHERE id_user = ?";
        $stmt = $conn->prepare($update_slug);
        $stmt->bind_param("si", $slug_url, $id_user);
        if ($stmt->execute()) {
            // Rename folder pada page/
            $old_folder = "../../page/" . $old_slug;
            $new_folder = "../../page/" . $slug_url;
            if (is_dir($old_folder)) {
                rename($old_folder, $new_folder);
            }
        }
        $stmt->close();
    }

    header("Location: ../seo/");
    exit();
}
?>
