<?php
// Database connection
include "connection.php";

// Check connection
if ($conn->connect_error) {
    die(json_encode(["status" => "error", "message" => "Database connection failed"]));
}

// Fetch all messages ordered by created_at
$query = "SELECT * FROM messages ORDER BY created_at ASC";
$result = $conn->query($query);

if (!$result) {
    echo json_encode(["status" => "error", "message" => "Failed to fetch messages"]);
    exit();
}

// Fetch messages into an array
$messages = [];
while ($row = $result->fetch_assoc()) {
    $messages[] = $row;
}

// Return JSON response
header("Content-Type: application/json");
echo json_encode($messages);

$conn->close();
?>
