<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

require_once 'connect.php';

try {
    $conn = getDatabaseConnection();

    $query = "
        SELECT 
            c.id, 
            c.name, 
            COUNT(bc.blog_id) as blog_count
        FROM 
            categories c
        LEFT JOIN 
            categories_blog bc ON c.id = bc.category_id
        LEFT JOIN 
            blogs b ON bc.blog_id = b.id AND b.status = 'active'
        GROUP BY 
            c.id, c.name
        ORDER BY 
            c.name ASC
    ";

    $stmt = $conn->prepare($query);
    $stmt->execute();

    $categories = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $categories[] = [
            'id' => (int) $row['id'],
            'name' => $row['name'],
            'blog_count' => (int) $row['blog_count'],
        ];
    }

    http_response_code(200);
    echo json_encode([
        'success' => true,
        'data' => $categories,
        'count' => count($categories),
    ]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to fetch categories: ' . $e->getMessage(),
    ]);
}
?>