<?php
// Start output buffering to prevent header issues
ob_start();

// Database configuration
require_once '../config/database.php';

try {
    $pdo = getDBConnection();
} catch(Exception $e) {
    ob_clean();
    header('Content-Type: application/json');
    echo json_encode([
        'status' => 'error',
        'message' => 'Database connection failed: ' . $e->getMessage()
    ]);
    exit();
}

// Set headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

// Get request method and parameters
$method = $_SERVER['REQUEST_METHOD'];
$id = isset($_GET['id']) ? (int)$_GET['id'] : null;
$category = isset($_GET['category']) ? $_GET['category'] : null;

try {
    switch($method) {
        case 'GET':
            if ($id) {
                // Get single blog post by ID
                $stmt = $pdo->prepare("SELECT * FROM blog_posts WHERE id = ? AND is_active = 1");
                $stmt->execute([$id]);
                $post = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($post) {
                    echo json_encode([
                        'status' => 'success',
                        'data' => $post
                    ]);
                } else {
                    echo json_encode([
                        'status' => 'error',
                        'message' => 'Blog post not found'
                    ]);
                }
            } elseif ($category) {
                // Get blog posts by category
                $stmt = $pdo->prepare("SELECT * FROM blog_posts WHERE category = ? AND is_active = 1 ORDER BY created_at DESC");
                $stmt->execute([$category]);
                $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode([
                    'status' => 'success',
                    'data' => $posts
                ]);
            } else {
                // Get all blog posts
                $stmt = $pdo->prepare("SELECT * FROM blog_posts WHERE is_active = 1 ORDER BY created_at DESC");
                $stmt->execute();
                $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode([
                    'status' => 'success',
                    'data' => $posts
                ]);
            }
            break;
            
        default:
            echo json_encode([
                'status' => 'error',
                'message' => 'Method not allowed'
            ]);
            break;
    }
} catch(PDOException $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage()
    ]);
} catch(Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Error: ' . $e->getMessage()
    ]);
}

// Clean output buffer
ob_end_flush();
?>
