<?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();
}

// Set timeout for long polling
set_time_limit(30);
$start_time = time();
$timeout = 25; // 25 seconds timeout

while (time() - $start_time < $timeout) {
    // Check for new messages
    $query = "SELECT m.*, 
                     GROUP_CONCAT(a.id) as attachment_ids,
                     GROUP_CONCAT(a.file_name) as attachment_names,
                     GROUP_CONCAT(a.file_path) as attachment_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);
    
    if (mysqli_num_rows($result) > 0) {
        $messages = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $messages[] = [
                'id' => $row['id'],
                'sender_type' => $row['sender_type'],
                'sender_id' => $row['sender_id'],
                'message' => nl2br(htmlspecialchars($row['message'])),
                'created_at' => $row['created_at'],
                'time_formatted' => date('h:i A', strtotime($row['created_at'])),
                'is_read' => $row['is_read'],
                'attachment_names' => $row['attachment_names'],
                'attachment_paths' => $row['attachment_paths']
            ];
        }
        
        // Mark user messages as read
        $update_query = "UPDATE support_messages SET is_read = 1, read_at = NOW() 
                         WHERE ticket_id = '$ticket_id' AND sender_type = 'user' AND is_read = 0";
        mysqli_query($conn, $update_query);
        
        echo json_encode([
            'success' => true,
            'messages' => $messages,
            'last_id' => end($messages)['id']
        ]);
        exit();
    }
    
    // Check if user is typing (you'll need to implement this feature)
    $typing_query = "SELECT is_typing FROM support_tickets WHERE id = '$ticket_id'";
    $typing_result = mysqli_query($conn, $typing_query);
    $is_typing = mysqli_fetch_assoc($typing_result)['is_typing'] ?? false;
    
    if ($is_typing) {
        echo json_encode([
            'success' => true,
            'messages' => [],
            'is_typing' => true
        ]);
        exit();
    }
    
    // Wait 2 seconds before next check
    sleep(2);
}

// No new messages within timeout
echo json_encode(['success' => true, 'messages' => []]);
exit();
?>