<?php
require_once __DIR__ . '/../config/helpers.php';
cors();

$method = $_SERVER['REQUEST_METHOD'];
$db     = db();

if ($method === 'GET') {
    $payload = require_auth();
    if ($payload['role'] === 'admin') {
        $rows = $db->query('SELECT * FROM suggestions ORDER BY submitted_at DESC')->fetchAll();
    } else {
        $stmt = $db->prepare(
            "SELECT * FROM suggestions WHERE user_id = ? AND is_anonymous = 0
             ORDER BY submitted_at DESC"
        );
        $stmt->execute([$payload['uid']]);
        $rows = $stmt->fetchAll();
    }
    json_ok(['suggestions' => $rows]);
}

if ($method === 'POST') {
    $payload  = require_auth();
    $b        = body();
    $text     = trim($b['text'] ?? '');
    $anon     = !empty($b['is_anonymous']);

    if ($text === '') json_err('Text required');

    $id = uuid();
    $db->prepare(
        'INSERT INTO suggestions (id, user_id, display_name, text, is_anonymous)
         VALUES (?, ?, ?, ?, ?)'
    )->execute([
        $id,
        $anon ? null : $payload['uid'],
        $anon ? null : ($b['display_name'] ?? ''),
        $text,
        $anon ? 1 : 0,
    ]);
    json_ok(['id' => $id], 201);
}

json_err('Method not allowed', 405);
