<?php
session_start();
include '../../koneksi.php'; // Koneksi ke database

if (!isset($_SESSION['user_id'])) {
    header("Location: ../../login/"); // Redirect ke login jika belum login
    exit();
}

if (isset($_GET['id'])) {
    $id_landingpage = mysqli_real_escape_string($conn, $_GET['id']);

    // Cek apakah slug ada di database
    $query = "SELECT id_user, slug_url FROM landingpage WHERE id_landingpage = '$id_landingpage'";
    $result = mysqli_query($conn, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        $id_user = $row['id_user'];
        $slug = $row['slug_url'];

        // Update status user menjadi 'disabled'
        $delete_landingpage_query = "DELETE FROM landingpage WHERE slug_url = '$slug'";

         // Update status user menjadi 'disabled'
         $update_query = "UPDATE users SET status = 'disabled' WHERE id_user = '$id_user'";

        //delete gambar landingpage
        $assetsQuery = "SELECT gambar_utama, gambar_tentang, gambar_keunggulan FROM landingpage WHERE id_user = '$id_user'";
        $assetsResult = mysqli_query($conn, $assetsQuery);

        if ($assetsResult && mysqli_num_rows($assetsResult) > 0) {
            while ($row = mysqli_fetch_assoc($assetsResult)) {
                $assetsPaths = [
                    "../../uploads/assets/" . $row['gambar_utama'],
                    "../../uploads/assets/" . $row['gambar_tentang'],
                    "../../uploads/assets/" . $row['gambar_keunggulan']
                ];

                // Hapus file jika ada
                foreach ($assetsPaths as $path) {
                    if (file_exists($path) && is_file($path)) {
                        unlink($path);
                    }
                }
            }
        }

         // Hapus data dari tabel landingpage berdasarkan id_landingpage
         $delete_landingpage_query = "DELETE FROM landingpage WHERE id_landingpage = '$id_landingpage'";
 
         if (mysqli_query($conn, $update_query) && mysqli_query($conn, $delete_landingpage_query)) {
             $folder_path = "../../page/" . $slug;
             if (is_dir($folder_path)) {
                 deleteFolder($folder_path); 
             }
 
             $_SESSION['success'] = "Data Landing page berhasil dinonaktifkan!";
         } else {
             $_SESSION['error'] = "Gagal menonaktifkan landing page!";
         }
     } else {
        $_SESSION['error'] = "Landing page tidak ditemukan!";
    }
} else {
    $_SESSION['error'] = "Slug tidak valid!";
}

header("Location: ../landingpage");
exit();

function deleteFolder($folder) {
    if (!is_dir($folder)) return;

    $files = array_diff(scandir($folder), array('.', '..'));
    foreach ($files as $file) {
        $filePath = "$folder/$file";
        if (is_dir($filePath)) {
            deleteFolder($filePath); 
        } else {
            unlink($filePath); 
        }
    }
    rmdir($folder); 
}
?>

