<?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;
$is_admin = isset($_GET['admin']) ? true : false;

if ($ticket_id <= 0) {
    echo json_encode(['success' => false, 'messages' => []]);
    exit();
}

// Get new messages
$query = "SELECT m.*, 
                 GROUP_CONCAT(a.file_name) as attachments, 
                 GROUP_CONCAT(a.file_path) as file_paths
          FROM support_messages m
          LEFT JOIN support_attachments a ON m.id = a.message_id
          WHERE m.ticket_id = '$ticket_id' AND m.id > '$last_id'
          GROUP BY m.id
          ORDER BY m.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' => $row['message'],
        'created_at' => $row['created_at'],
        'is_read' => $row['is_read'],
        'file_name' => $row['attachments'],
        'file_path' => $row['file_paths']
    ];
}

// If admin, mark user messages as read
if ($is_admin && !empty($messages)) {
    $message_ids = implode(',', array_column($messages, 'id'));
    mysqli_query($conn, "UPDATE support_messages SET is_read = 1, read_at = NOW() 
                          WHERE id IN ($message_ids) AND sender_type = 'user'");
}

// Check if user is typing (you'd need to implement this with WebSockets or a polling mechanism)
$is_typing = false; // Implement based on your real-time system

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

mysqli_close($conn);
?>