<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { exit(0); }
header('Content-Type: application/json');

include_once '../config/Database.php';
include_once '../middleware/auth.php';

$database = new Database();
$db = $database->connect();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $data = json_decode(file_get_contents("php://input"));
    $query = 'INSERT INTO messages (name, email, message) VALUES (:name, :email, :message)';
    $stmt = $db->prepare($query);
    $stmt->bindParam(':name', $data->name);
    $stmt->bindParam(':email', $data->email);
    $stmt->bindParam(':message', $data->message);
    if ($stmt->execute()) {
        echo json_encode(['message' => 'Message sent']);
    } else {
        http_response_code(500);
        echo json_encode(['message' => 'Message not sent']);
    }
} elseif ($method === 'GET') {
    $user = get_user_from_token();
    if (!$user) {
        http_response_code(401);
        echo json_encode(['message' => 'Unauthorized']);
        exit();
    }
    $query = 'SELECT id, name, email, message, status, createdAt FROM messages ORDER BY createdAt DESC';
    $stmt = $db->prepare($query);
    $stmt->execute();
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($messages);
}
?>