<?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 sc.name, c.name as category_name FROM sub_categories sc JOIN categories c ON sc.category_id = c.id WHERE sc.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'];

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

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