<?php
require_once '../config/database.php';

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

$type = $_GET['type'] ?? '';
$categoryTable = $tables['categories']; // Get table name from config

try {
    if ($type === 'categories') {
        // Get all unique categories with subcategory count
        $stmt = $pdo->prepare("
            SELECT 
                Category,
                COUNT(CASE WHEN SubCategory != '' AND SubCategory IS NOT NULL THEN 1 END) as subcategory_count
            FROM {$categoryTable} 
            WHERE Category != '' AND Category IS NOT NULL
            GROUP BY Category 
            ORDER BY Category ASC
        ");
        $stmt->execute();
        $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'categories' => $categories
        ]);
        
    } elseif ($type === 'subcategories') {
        $categoryFilter = $_GET['category'] ?? '';
        
        $sql = "
            SELECT ID, Category, SubCategory 
            FROM {$categoryTable} 
            WHERE SubCategory != '' AND SubCategory IS NOT NULL
        ";
        
        $params = [];
        if ($categoryFilter) {
            $sql .= " AND Category = ?";
            $params[] = $categoryFilter;
        }
        
        $sql .= " ORDER BY Category ASC, SubCategory ASC";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $subcategories = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        echo json_encode([
            'success' => true,
            'subcategories' => $subcategories
        ]);
        
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid request type'
        ]);
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?> 