<?php
require_once __DIR__ . '/../../cors.php'; // Enable CORS for React Native
// GET   /api/admin/messages — list contact messages
// PATCH /api/admin/messages — mark message as read
require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../middleware/auth.php';

requireAdmin();
$db = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $msgs = $db->query('SELECT * FROM messages ORDER BY created_at DESC')->fetchAll();
    jsonResponse($msgs);
}

if ($_SERVER['REQUEST_METHOD'] === 'PATCH') {
    $body = getBody();
    $id   = $body['id'] ?? '';
    if (!$id) jsonError('id is required');
    $db->prepare('UPDATE messages SET is_read = 1 WHERE id = ?')->execute([$id]);
    $stmt = $db->prepare('SELECT * FROM messages WHERE id = ?');
    $stmt->execute([$id]);
    jsonResponse($stmt->fetch());
}

jsonError('Method not allowed', 405);
