<?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'];

    // Get sub-categories
    $stmt = $conn->prepare("SELECT id, name FROM sub_categories WHERE category_id = ? ORDER BY name");
    $stmt->bind_param("i", $category_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $sub_categories = [];
    while ($row = $result->fetch_assoc()) {
        $sub_categories[] = $row;
    }

    echo json_encode([
        'success' => true,
        'category_name' => $category['name'],
        'item_count' => $item_count,
        'sub_categories' => $sub_categories
    ]);

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