<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/news_lib.php';

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: public, max-age=60');
header('X-Content-Type-Options: nosniff');

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'GET') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($id > 0) {
    $st = $pdo->prepare(
        'SELECT id, title, summary, body, image_url, published_at, sort_order
         FROM site_news
         WHERE id = :id AND is_published = 1
         LIMIT 1'
    );
    $st->execute([':id' => $id]);
    $row = $st->fetch(PDO::FETCH_ASSOC);
    if (!$row) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    echo json_encode(['ok' => true, 'item' => mocker_news_row_to_public($row, true)], JSON_UNESCAPED_UNICODE);
    exit;
}

$st = $pdo->query(
    'SELECT id, title, summary, body, image_url, published_at, sort_order
     FROM site_news
     WHERE is_published = 1
     ORDER BY sort_order DESC, published_at DESC, id DESC
     LIMIT 100'
);
$items = [];
foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $items[] = mocker_news_row_to_public($row, false);
}

echo json_encode(['ok' => true, 'items' => $items], JSON_UNESCAPED_UNICODE);
