<?php
header('Content-Type: application/json');

require_once '../config/config.php';
require_once '../classes/Database.php';

$db = Database::getInstance();

$ticketId = intval($_GET['ticket_id'] ?? 0);

if ($ticketId == 0) {
    echo json_encode(['error' => 'Invalid ticket ID']);
    exit();
}

try {
    $sql = "SELECT m.*, u.name as sender_name 
            FROM support_messages m
            JOIN users u ON u.id = m.sender_id
            WHERE m.ticket_id = '$ticketId'
            ORDER BY m.created_at ASC";
    
    $messages = $db->fetchAll($sql);
    
    echo json_encode($messages ?? []);
} catch (Exception $e) {
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
