<?php
require_once '../config/database.php';
secureSessionStart();
requireLogin();

$conn = getConnection();
$ticket_id = isset($_GET['ticket_id']) ? intval($_GET['ticket_id']) : 0;
$last_id = isset($_GET['last_id']) ? intval($_GET['last_id']) : 0;

if (!$ticket_id) {
    echo json_encode(['success' => false, 'error' => 'No ticket ID']);
    exit();
}

// Check for new messages
$query = "SELECT id, message, sender_type, created_at, DATE_FORMAT(created_at, '%h:%i %p') as time_formatted
          FROM support_messages 
          WHERE ticket_id = '$ticket_id' AND id > '$last_id' AND sender_type = 'user'
          ORDER BY created_at ASC";
$result = mysqli_query($conn, $query);

$messages = [];
while ($row = mysqli_fetch_assoc($result)) {
    $messages[] = [
        'id' => $row['id'],
        'sender_type' => $row['sender_type'],
        'message' => nl2br(htmlspecialchars($row['message'])),
        'time' => $row['time_formatted']
    ];
}

// Mark as read
if (!empty($messages)) {
    mysqli_query($conn, "UPDATE support_messages SET is_read = 1, read_at = NOW() 
                        WHERE ticket_id = '$ticket_id' AND sender_type = 'user' AND is_read = 0");
}

echo json_encode([
    'success' => true,
    'messages' => $messages
]);
exit();
?>