<?php
// Start by setting the correct header for JSON
header("Content-Type: application/json");
session_start();
require_once '../config/db.php'; 

$response = ["success" => false, "message" => "An unknown error occurred."];

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

    // 1. Fetch paths BEFORE deleting database records
    $query = "SELECT s.thumbnail_image, s.sub_category_name, c.category_name 
              FROM sub_categories s 
              JOIN categories c ON s.cat_id = c.id 
              WHERE s.id = $id";
    $res = $conn->query($query);

    if ($res && $res->num_rows > 0) {
        $data = $res->fetch_assoc();
        
        // Prepare file/folder paths
        $thumbnail = "../" . $data['thumbnail_image']; 
        $cat_folder = preg_replace('/[^A-Za-z0-9_\-]/', '_', $data['category_name']);
        $sub_folder = preg_replace('/[^A-Za-z0-9_\-]/', '_', $data['sub_category_name']);
        $full_dir = "../uploads/templates/$cat_folder/$sub_folder/";

        // 2. Cleanup Filesystem
        if (!empty($data['thumbnail_image']) && file_exists($thumbnail)) {
            @unlink($thumbnail);
        }

        if (is_dir($full_dir)) {
            deleteDirectory($full_dir);
        }

        // 3. Database Cleanup
        // Explicitly clear permissions first if not using CASCADE
        $conn->query("DELETE FROM sub_category_permissions WHERE sub_cat_id_pk = $id");
        $delete = $conn->query("DELETE FROM sub_categories WHERE id = $id");

        if ($delete) {
            $response = [
                "success" => true, 
                "message" => "Sub-category '" . $data['sub_category_name'] . "' and assets deleted successfully."
            ];
        } else {
            $response = ["success" => false, "message" => "Database Error: " . $conn->error];
        }
    } else {
        $response = ["success" => false, "message" => "Sub-category not found in the network."];
    }
} else {
    $response = ["success" => false, "message" => "Invalid Request: ID missing."];
}

// 4. Send the JSON response
echo json_encode($response);
exit();

/**
 * Helper function to delete a directory and all its contents
 */
function deleteDirectory($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir)) return unlink($dir);

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