<?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;
}

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

if (!$category_id) {
    echo json_encode(['success' => false, 'message' => 'Category ID is required']);
    exit;
}

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

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

    // Check if category is being used in items
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM items WHERE category_id = ?");
    $stmt->bind_param("i", $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 category \"{$category['name']}\" because it is being used by {$item_count} item(s). Please reassign or delete those items first."]);
        exit;
    }

    // Start transaction
    $conn->begin_transaction();

    // Delete sub-categories first
    $stmt = $conn->prepare("DELETE FROM sub_categories WHERE category_id = ?");
    $stmt->bind_param("i", $category_id);
    $stmt->execute();

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

    // Commit transaction
    $conn->commit();

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

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