<?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__ . '/notifications_lib.php';

mocker_admin_require_permission('notifications');

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, body, link_url, is_published, created_at, created_by
         FROM site_notifications
         ORDER BY created_at DESC, id DESC
         LIMIT 200'
    );
    $items = [];
    foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $item = mocker_notification_row_to_public($row, false);
        $item['isPublished'] = (int) $row['is_published'] === 1;
        $item['createdBy'] = (string) $row['created_by'];
        $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'] ?? ''));
    $body = trim((string) ($input['body'] ?? ''));
    if ($title === '' || $body === '') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'title_body'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $linkUrl = mocker_notification_normalize_link((string) ($input['linkUrl'] ?? ''));
    $isPublished = !empty($input['isPublished']) ? 1 : 0;
    $now = time();
    $adminName = trim((string) ($_SESSION['mocker_admin_username'] ?? $_SESSION['mocker_admin_display'] ?? ''));

    $st = $pdo->prepare(
        'INSERT INTO site_notifications (title, body, link_url, is_published, created_at, created_by)
         VALUES (:title, :body, :link, :pub, :c, :by)'
    );
    $st->execute([
        ':title' => $title,
        ':body' => $body,
        ':link' => $linkUrl,
        ':pub' => $isPublished,
        ':c' => $now,
        ':by' => $adminName,
    ]);

    echo json_encode(['ok' => true, 'id' => (int) $pdo->lastInsertId()], 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_notifications 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;
}

if ($action === 'toggle_publish') {
    $id = (int) ($input['id'] ?? 0);
    $isPublished = !empty($input['isPublished']) ? 1 : 0;
    if ($id <= 0) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'id'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $st = $pdo->prepare('UPDATE site_notifications SET is_published = :p WHERE id = :id');
    $st->execute([':p' => $isPublished, ':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);
