<script>
    function loadMessages() {
        $.getJSON('fetch_messages.php', { requisition_id: <?= $requisition_id ?> }, function(messages) {
            let chatBox = $('#chat-box');
            chatBox.empty();
            messages.forEach(msg => {
                chatBox.append('<div><strong>'+msg.sender_name+':</strong> '+msg.message+'</div>');
            });
            chatBox.scrollTop(chatBox[0].scrollHeight);
        });
    }
    // Poll every 3 seconds for new messages
    setInterval(loadMessages, 3000);
    loadMessages();

    $('#send-btn').on('click', function() {
        let message = $('#chat-message').val();
        $.post('send_message.php', {
            requisition_id: <?= $requisition_id ?>,
            sender_id: <?= $current_user_id ?>,
            receiver_id: <?= $other_user_id ?>,
            message: message
        }, function(response) {
            if (response.status === 'success') {
                $('#chat-message').val('');
                loadMessages();
            }
        }, 'json');
    });
  </script>