@extends('layouts.app')

@section('content')
<div class="container">
    <h4>Chat with {{ $receiver->name }}</h4>
    <div id="chat-box" style="height: 300px; overflow-y: scroll; border: 1px solid #ccc;" class="mb-3 p-3">
        @foreach($messages as $msg)
            <div class="{{ $msg->sender_id == auth()->id() ? 'text-end' : 'text-start' }}">
                <p class="mb-1"><strong>{{ $msg->sender->name }}:</strong></p>
                <p>{{ $msg->message }}</p>
            </div>
        @endforeach
    </div>

    <form id="chat-form">
        @csrf
        <input type="hidden" name="receiver_id" value="{{ $receiver->id }}">
        <div class="input-group">
            <input type="text" name="message" id="message" class="form-control" placeholder="Type a message...">
            <button class="btn btn-primary" type="submit">Send</button>
        </div>
    </form>
</div>
@endsection

@section('scripts')
<script>
    $('#chat-form').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
            url: "{{ route('chat.send') }}",
            method: 'POST',
            data: $(this).serialize(),
            success: function(response) {
                $('#chat-box').append(
                    `<div class="text-end"><p class="mb-1"><strong>You:</strong></p><p>${response.message.message}</p></div>`
                );
                $('#message').val('');
                $('#chat-box').scrollTop($('#chat-box')[0].scrollHeight);
            }
        });
    });
</script>
@endsection
