<?php
declare(strict_types=1);

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

mocker_admin_require_permission('news');

header('Content-Type: application/json; charset=utf-8');

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

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

if ($method === 'GET') {
    $st = $pdo->query(
        'SELECT id, title, summary, body, image_url, published_at, is_published, sort_order, created_at, updated_at
         FROM site_news
         ORDER BY sort_order DESC, published_at DESC, id DESC'
    );
    $items = [];
    foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $item = mocker_news_row_to_public($row, true);
        $item['isPublished'] = (int) $row['is_published'] === 1;
        $item['createdAt'] = (int) $row['created_at'];
        $item['updatedAt'] = (int) $row['updated_at'];
        $items[] = $item;
    }
    echo json_encode(['ok' => true, 'items' => $items], JSON_UNESCAPED_UNICODE);
    exit;
}

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

mocker_require_csrf_post();

$input = json_decode((string) file_get_contents('php://input'), true) ?: [];
$action = (string) ($input['action'] ?? '');

if ($action === 'create') {
    $title = trim((string) ($input['title'] ?? ''));
    if ($title === '') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'title'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $now = time();
    $publishedAt = mocker_news_parse_published_at($input['publishedAt'] ?? null);
    $isPublished = !empty($input['isPublished']) ? 1 : 0;
    $sortOrder = (int) ($input['sortOrder'] ?? 0);

    $st = $pdo->prepare(
        'INSERT INTO site_news (title, summary, body, image_url, published_at, is_published, sort_order, created_at, updated_at)
         VALUES (:title, :summary, :body, :image, :pub, :isp, :sort, :c, :u)'
    );
    $st->execute([
        ':title' => $title,
        ':summary' => trim((string) ($input['summary'] ?? '')),
        ':body' => trim((string) ($input['body'] ?? '')),
        ':image' => trim((string) ($input['imageUrl'] ?? '')),
        ':pub' => $publishedAt,
        ':isp' => $isPublished,
        ':sort' => $sortOrder,
        ':c' => $now,
        ':u' => $now,
    ]);

    echo json_encode(['ok' => true, 'id' => (int) $pdo->lastInsertId()], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'update') {
    $id = (int) ($input['id'] ?? 0);
    if ($id <= 0) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'id'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $title = trim((string) ($input['title'] ?? ''));
    if ($title === '') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'title'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $publishedAt = mocker_news_parse_published_at($input['publishedAt'] ?? null);
    $isPublished = !empty($input['isPublished']) ? 1 : 0;
    $sortOrder = (int) ($input['sortOrder'] ?? 0);
    $now = time();

    $st = $pdo->prepare(
        'UPDATE site_news SET
            title = :title,
            summary = :summary,
            body = :body,
            image_url = :image,
            published_at = :pub,
            is_published = :isp,
            sort_order = :sort,
            updated_at = :u
         WHERE id = :id'
    );
    $st->execute([
        ':title' => $title,
        ':summary' => trim((string) ($input['summary'] ?? '')),
        ':body' => trim((string) ($input['body'] ?? '')),
        ':image' => trim((string) ($input['imageUrl'] ?? '')),
        ':pub' => $publishedAt,
        ':isp' => $isPublished,
        ':sort' => $sortOrder,
        ':u' => $now,
        ':id' => $id,
    ]);

    if ($st->rowCount() === 0) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    echo json_encode(['ok' => true], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($action === 'delete') {
    $id = (int) ($input['id'] ?? 0);
    if ($id <= 0) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'id'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $st = $pdo->prepare('DELETE FROM site_news WHERE id = :id');
    $st->execute([':id' => $id]);
    if ($st->rowCount() === 0) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'not_found'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    echo json_encode(['ok' => true], JSON_UNESCAPED_UNICODE);
    exit;
}

http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'action'], JSON_UNESCAPED_UNICODE);
