<?php
/**
 * Blog Posts API
 * GET    /api/blogs.php         - Get all posts
 * GET    /api/blogs.php?id=xxx  - Get single post
 * POST   /api/blogs.php         - Create post (auth required)
 * PUT    /api/blogs.php?id=xxx  - Update post (auth required)
 * DELETE /api/blogs.php?id=xxx  - Delete post (auth required)
 */

require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? null;
$db = getDB();

// GET - List all or single post
if ($method === 'GET') {
    if ($id) {
        // Get single post by ID or slug
        $stmt = $db->prepare("SELECT * FROM blog_posts WHERE id = ? OR slug = ?");
        $stmt->execute([$id, $id]);
        $post = $stmt->fetch();
        
        if (!$post) {
            errorResponse('Blog post tidak ditemukan', 404);
        }
        
        // Increment view count
        $db->prepare("UPDATE blog_posts SET views = views + 1 WHERE id = ?")->execute([$post['id']]);
        $post['views'] = $post['views'] + 1;
        
        jsonResponse($post);
    } else {
        // Get all posts
        $status = $_GET['status'] ?? null;
        $limit = (int)($_GET['limit'] ?? 100);
        
        $sql = "SELECT * FROM blog_posts";
        $params = [];
        
        if ($status) {
            $sql .= " WHERE status = ?";
            $params[] = $status;
        }
        
        $sql .= " ORDER BY created_at DESC LIMIT $limit";
        
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $posts = $stmt->fetchAll();
        
        jsonResponse($posts);
    }
}

// POST - Create new post
if ($method === 'POST') {
    requireAuth();
    $input = getJsonInput();
    
    $title = $input['title'] ?? '';
    if (empty($title)) {
        errorResponse('Title harus diisi', 400);
    }
    
    $slug = !empty($input['slug']) ? $input['slug'] : generateSlug($title);
    
    // Check duplicate slug
    $stmt = $db->prepare("SELECT id FROM blog_posts WHERE slug = ?");
    $stmt->execute([$slug]);
    if ($stmt->fetch()) {
        $slug = $slug . '-' . substr(generateUUID(), 0, 8);
    }
    
    $id = generateUUID();
    $content = $input['content'] ?? '';
    $excerpt = $input['excerpt'] ?? '';
    $metaDesc = $input['meta_description'] ?? ($excerpt ? substr($excerpt, 0, 160) : '');
    $metaKeywords = $input['meta_keywords'] ?? '';
    $author = $input['author'] ?? 'Admin';
    $featuredImage = $input['featured_image'] ?? '';
    $status = $input['status'] ?? 'published';
    
    $stmt = $db->prepare("
        INSERT INTO blog_posts (id, title, slug, content, excerpt, meta_description, meta_keywords, author, featured_image, status, views)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)
    ");
    $stmt->execute([$id, $title, $slug, $content, $excerpt, $metaDesc, $metaKeywords, $author, $featuredImage, $status]);
    
    // Return created post
    $stmt = $db->prepare("SELECT * FROM blog_posts WHERE id = ?");
    $stmt->execute([$id]);
    jsonResponse($stmt->fetch(), 201);
}

// PUT - Update post
if ($method === 'PUT') {
    requireAuth();
    
    if (!$id) {
        errorResponse('ID harus disertakan', 400);
    }
    
    // Check exists
    $stmt = $db->prepare("SELECT * FROM blog_posts WHERE id = ?");
    $stmt->execute([$id]);
    $post = $stmt->fetch();
    
    if (!$post) {
        errorResponse('Blog post tidak ditemukan', 404);
    }
    
    $input = getJsonInput();
    
    $title = $input['title'] ?? $post['title'];
    $slug = $input['slug'] ?? $post['slug'];
    $content = $input['content'] ?? $post['content'];
    $excerpt = $input['excerpt'] ?? $post['excerpt'];
    $metaDesc = $input['meta_description'] ?? $post['meta_description'];
    $metaKeywords = $input['meta_keywords'] ?? $post['meta_keywords'];
    $author = $input['author'] ?? $post['author'];
    $featuredImage = $input['featured_image'] ?? $post['featured_image'];
    $status = $input['status'] ?? $post['status'];
    
    $stmt = $db->prepare("
        UPDATE blog_posts 
        SET title = ?, slug = ?, content = ?, excerpt = ?, meta_description = ?, 
            meta_keywords = ?, author = ?, featured_image = ?, status = ?, updated_at = NOW()
        WHERE id = ?
    ");
    $stmt->execute([$title, $slug, $content, $excerpt, $metaDesc, $metaKeywords, $author, $featuredImage, $status, $id]);
    
    // Return updated post
    $stmt = $db->prepare("SELECT * FROM blog_posts WHERE id = ?");
    $stmt->execute([$id]);
    jsonResponse($stmt->fetch());
}

// DELETE - Delete post
if ($method === 'DELETE') {
    requireAuth();
    
    if (!$id) {
        errorResponse('ID harus disertakan', 400);
    }
    
    $stmt = $db->prepare("SELECT id FROM blog_posts WHERE id = ?");
    $stmt->execute([$id]);
    
    if (!$stmt->fetch()) {
        errorResponse('Blog post tidak ditemukan', 404);
    }
    
    $db->prepare("DELETE FROM blog_posts WHERE id = ?")->execute([$id]);
    
    jsonResponse(['message' => 'Blog post berhasil dihapus']);
}

errorResponse('Method not allowed', 405);
