<?php
include 'db.php';
include 'auth.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$sub_category_id = $_GET['id'] ?? null;

if (!$sub_category_id) {
    echo json_encode(['success' => false, 'message' => 'Sub-category ID is required']);
    exit;
}

try {
    // Check if sub-category exists
    $stmt = $conn->prepare("SELECT name FROM sub_categories WHERE id = ?");
    $stmt->bind_param("i", $sub_category_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $sub_category = $result->fetch_assoc();

    if (!$sub_category) {
        echo json_encode(['success' => false, 'message' => 'Sub-category not found']);
        exit;
    }

    // Check if sub-category is being used in items
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM items WHERE sub_category_id = ?");
    $stmt->bind_param("i", $sub_category_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $item_count = $result->fetch_assoc()['count'];

    if ($item_count > 0) {
        echo json_encode(['success' => false, 'message' => "Cannot delete sub-category \"{$sub_category['name']}\" because it is being used by {$item_count} item(s). Please reassign or delete those items first."]);
        exit;
    }

    // Delete the sub-category
    $stmt = $conn->prepare("DELETE FROM sub_categories WHERE id = ?");
    $stmt->bind_param("i", $sub_category_id);
    $stmt->execute();

    echo json_encode(['success' => true, 'message' => 'Sub-category deleted successfully']);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?> 