<?php
session_start();
require_once '../config/db.php';

if (isset($_GET['id'])) {
    $cat_id = intval($_GET['id']);

    // 1. Get Category Name to locate the physical folder
    $cat_res = $conn->query("SELECT category_name FROM categories WHERE id = $cat_id");
    
    if ($cat_res && $cat_res->num_rows > 0) {
        $cat_data = $cat_res->fetch_assoc();
        $folder_name = preg_replace('/[^A-Za-z0-9_\-]/', '_', $cat_data['category_name']);
        $cat_path = "../uploads/templates/" . $folder_name;

        // 2. Wipe out all Sub-category Thumbnails first
        // We find all sub-categories belonging to this parent category
        $sub_res = $conn->query("SELECT thumbnail_image FROM sub_categories WHERE cat_id = $cat_id");
        while ($sub_row = $sub_res->fetch_assoc()) {
            if (!empty($sub_row['thumbnail_image'])) {
                $thumb_file = "../" . $sub_row['thumbnail_image'];
                if (file_exists($thumb_file)) {
                    unlink($thumb_file); // Delete physical thumb image
                }
            }
        }

        // 3. Recursively Delete the Category Folder (and all template layers inside)
        if (is_dir($cat_path)) {
            deleteDirRecursive($cat_path);
        }

        // 4. Delete Database Record 
        // Note: If you set up FOREIGN KEY CASCADE, sub_categories and permissions 
        // will vanish automatically. If not, we do it manually:
        $conn->query("DELETE FROM sub_categories WHERE cat_id = $cat_id");
        $conn->query("DELETE FROM category_permissions WHERE category_id_pk = $cat_id");
        $conn->query("DELETE FROM categories WHERE id = $cat_id");

        $_SESSION['msg'] = "Category, sub-categories, and all server files wiped successfully.";
        $_SESSION['msg_type'] = "success";
    } else {
        $_SESSION['msg'] = "Category not found.";
        $_SESSION['msg_type'] = "error";
    }
}

header("Location: manage-categories.php");
exit();

/**
 * Robust function to delete a folder and everything inside it
 */
function deleteDirRecursive($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir)) return unlink($dir);

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') continue;
        if (!deleteDirRecursive($dir . DIRECTORY_SEPARATOR . $item)) return false;
    }
    return rmdir($dir);
}