<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

header('Content-Type: application/json');
hw_require_auth(['admin']);

$method = $_SERVER['REQUEST_METHOD'];
$pdo = hw_db();

try {
    if ($method === 'GET') {
        // Get all blog posts
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
        $offset = ($page - 1) * $limit;
        
        $stmt = $pdo->prepare('
            SELECT id, title, slug, excerpt, featured_image, status, published_at, view_count, updated_at
            FROM content_articles
            WHERE status IN ("published", "draft")
            ORDER BY published_at DESC, created_at DESC
            LIMIT ? OFFSET ?
        ');
        $stmt->execute([$limit, $offset]);
        $posts = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get total count
        $countStmt = $pdo->prepare('SELECT COUNT(*) as total FROM content_articles WHERE status IN ("published", "draft")');
        $countStmt->execute();
        $total = $countStmt->fetch()['total'];
        
        echo json_encode([
            'success' => true,
            'posts' => $posts,
            'pagination' => [
                'total' => $total,
                'page' => $page,
                'limit' => $limit,
                'pages' => ceil($total / $limit)
            ]
        ]);
    } 
    else if ($method === 'POST') {
        // Create/Update blog post
        $input = json_decode(file_get_contents('php://input'), true);
        $authUser = hw_get_auth_user();
        
        $id = $input['id'] ?? null;
        $title = $input['title'] ?? '';
        $slug = $input['slug'] ?? '';
        $excerpt = $input['excerpt'] ?? '';
        $content = $input['content'] ?? '';
        $featured_image = $input['featured_image'] ?? null;
        $status = $input['status'] ?? 'draft';
        $category_id = $input['category_id'] ?? null;
        
        if (!$title || !$slug) {
            echo json_encode(['success' => false, 'error' => 'Title and slug are required']);
            exit;
        }
        
        if ($id) {
            // Update
            $stmt = $pdo->prepare('
                UPDATE content_articles
                SET title = ?, slug = ?, excerpt = ?, content = ?, featured_image = ?, 
                    status = ?, category_id = ?, updated_at = NOW(),
                    published_at = CASE WHEN status = "published" AND published_at IS NULL THEN NOW() ELSE published_at END
                WHERE id = ?
            ');
            $stmt->execute([$title, $slug, $excerpt, $content, $featured_image, $status, $category_id, $id]);
            echo json_encode(['success' => true, 'message' => 'Blog post updated', 'id' => $id]);
        } else {
            // Create
            $stmt = $pdo->prepare('
                INSERT INTO content_articles 
                (title, slug, excerpt, content, featured_image, author_id, category_id, status, published_at, created_at, updated_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
            ');
            $publishedAt = ($status === 'published') ? 'NOW()' : null;
            $stmt->execute([$title, $slug, $excerpt, $content, $featured_image, $authUser['id'], $category_id, $status, $publishedAt]);
            echo json_encode(['success' => true, 'message' => 'Blog post created', 'id' => $pdo->lastInsertId()]);
        }
    } 
    else if ($method === 'DELETE') {
        // Delete blog post
        $input = json_decode(file_get_contents('php://input'), true);
        $id = $input['id'] ?? 0;
        
        $stmt = $pdo->prepare('DELETE FROM content_articles WHERE id = ?');
        $stmt->execute([$id]);
        
        echo json_encode(['success' => true, 'message' => 'Blog post deleted']);
    }
    else {
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
