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

// Check if category_id is provided
if (!isset($_GET['category_id'])) {
    echo json_encode(['error' => 'Category ID is required']);
    exit;
}

$category_id = $_GET['category_id'];

// Fetch subcategories
if ($category_id === 'all') {
    // Get all subcategories
    $query = "SELECT id, name, category_id FROM sub_categories ORDER BY name ASC";
    $result = $conn->query($query);
} else {
    // Get subcategories for specific category
    $category_id = intval($category_id);
    $query = "SELECT id, name, category_id FROM sub_categories WHERE category_id = ? ORDER BY name ASC";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $category_id);
    $stmt->execute();
    $result = $stmt->get_result();
}

$subcategories = [];
while ($row = $result->fetch_assoc()) {
    $subcategories[] = $row;
}

// Return JSON response
header('Content-Type: application/json');
echo json_encode($subcategories);
?>
