<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

function post_row_to_array(array $row): array {
    return [
        'slug' => $row['slug'],
        'title' => $row['title'],
        'excerpt' => $row['excerpt'] ?? '',
        'content' => $row['content'] ?? '',
        'published' => (bool) $row['published'],
        'date' => $row['post_date'],
    ];
}

/**
 * Same route contract as backend/cloudflare-worker-blog/worker.js:
 *   GET    /posts            -> published posts only (public)
 *   GET    /posts?all=1      -> every post, drafts included (auth required)
 *   GET    /posts/:slug      -> one post; unpublished requires auth
 *   POST   /posts            -> create (auth required)
 *   PUT    /posts/:slug      -> update (auth required)
 *   DELETE /posts/:slug      -> delete (auth required)
 */
function handle_posts_route(array $parts): void {
    $method = $_SERVER['REQUEST_METHOD'];
    $slug = $parts[1] ?? null;

    if ($method === 'GET' && $slug === null) {
        $wantAll = ($_GET['all'] ?? '') === '1';
        if ($wantAll) require_auth();
        if ($wantAll) {
            $rows = db()->query('SELECT * FROM blog_posts ORDER BY post_date DESC, id DESC')->fetchAll();
        } else {
            $rows = db()->query('SELECT * FROM blog_posts WHERE published = 1 ORDER BY post_date DESC, id DESC')->fetchAll();
        }
        json_response(['posts' => array_map('post_row_to_array', $rows)]);
    }

    if ($method === 'GET' && $slug !== null) {
        $stmt = db()->prepare('SELECT * FROM blog_posts WHERE slug = ? LIMIT 1');
        $stmt->execute([$slug]);
        $row = $stmt->fetch();
        if (!$row) json_response(['error' => 'Not found'], 404);
        if (!$row['published'] && !is_authed()) json_response(['error' => 'Not found'], 404);
        json_response(['post' => post_row_to_array($row)]);
    }

    // Everything below mutates data.
    require_auth();

    if ($method === 'POST' && $slug === null) {
        $body = json_decode(file_get_contents('php://input'), true) ?? [];
        $newSlug = trim($body['slug'] ?? '');
        $title = trim($body['title'] ?? '');
        if ($newSlug === '' || $title === '') json_response(['error' => 'slug and title are required'], 400);

        $existing = db()->prepare('SELECT id FROM blog_posts WHERE slug = ? LIMIT 1');
        $existing->execute([$newSlug]);
        if ($existing->fetch()) json_response(['error' => 'A post with this slug already exists'], 409);

        $date = $body['date'] ?? date('Y-m-d');
        $stmt = db()->prepare('INSERT INTO blog_posts (slug, title, excerpt, content, published, post_date) VALUES (?, ?, ?, ?, ?, ?)');
        $stmt->execute([$newSlug, $title, $body['excerpt'] ?? '', $body['content'] ?? '', !empty($body['published']) ? 1 : 0, $date]);
        json_response(['post' => [
            'slug' => $newSlug, 'title' => $title, 'excerpt' => $body['excerpt'] ?? '',
            'content' => $body['content'] ?? '', 'published' => !empty($body['published']), 'date' => $date,
        ]], 201);
    }

    if ($method === 'PUT' && $slug !== null) {
        $stmt = db()->prepare('SELECT * FROM blog_posts WHERE slug = ? LIMIT 1');
        $stmt->execute([$slug]);
        $existing = $stmt->fetch();
        if (!$existing) json_response(['error' => 'Not found'], 404);

        $body = json_decode(file_get_contents('php://input'), true) ?? [];
        $updated = [
            'title' => $body['title'] ?? $existing['title'],
            'excerpt' => array_key_exists('excerpt', $body) ? $body['excerpt'] : $existing['excerpt'],
            'content' => array_key_exists('content', $body) ? $body['content'] : $existing['content'],
            'published' => array_key_exists('published', $body) ? (!empty($body['published']) ? 1 : 0) : $existing['published'],
            'post_date' => $body['date'] ?? $existing['post_date'],
        ];
        $upd = db()->prepare('UPDATE blog_posts SET title = ?, excerpt = ?, content = ?, published = ?, post_date = ? WHERE slug = ?');
        $upd->execute([$updated['title'], $updated['excerpt'], $updated['content'], $updated['published'], $updated['post_date'], $slug]);
        json_response(['post' => [
            'slug' => $slug, 'title' => $updated['title'], 'excerpt' => $updated['excerpt'],
            'content' => $updated['content'], 'published' => (bool) $updated['published'], 'date' => $updated['post_date'],
        ]]);
    }

    if ($method === 'DELETE' && $slug !== null) {
        db()->prepare('DELETE FROM blog_posts WHERE slug = ?')->execute([$slug]);
        json_response(['ok' => true]);
    }

    json_response(['error' => 'Method not allowed'], 405);
}
