@extends('admin/layouts.app')
@section('title', 'Booking Details')

@push('styles')
    <link rel="stylesheet" href="{{ asset('public/assets/css/chat.css') }}" />
@endpush
@section('content')
       <!-- Page content-->
        <div class="container-fluid">
          <div class="content-wrapper" id="dashboard">
            <div class="row">
                <div class="col-12">
                  <div class="header">
                    <div class="d-block d-sm-flex align-items-center justify-content-between">
                      <p class="fs-18 mb-0 d-flex align-items-center bg-transparent titlebrown">
                        <span class="menu-icons">
            <svg id="fi_2460737" enable-background="new 0 0 512 512"  width="23" height="23"  viewBox="0 0 512 512" width="512" xmlns="http://www.w3.org/2000/svg"><g><path d="m456.832 32.133h-41.232v-17.133c0-8.284-6.716-15-15-15s-15 6.716-15 15v17.133h-66.4v-17.133c0-8.284-6.716-15-15-15s-15 6.716-15 15v17.133h-66.4v-17.133c0-8.284-6.716-15-15-15s-15 6.716-15 15v17.133h-66.4v-17.133c0-8.284-6.716-15-15-15s-15 6.716-15 15v17.133h-41.234c-30.418 0-55.166 24.747-55.166 55.167v369.533c0 30.419 24.748 55.167 55.166 55.167h401.666c30.419 0 55.168-24.748 55.168-55.167v-369.533c0-30.42-24.749-55.167-55.168-55.167zm-401.666 30h41.234v17.134c0 8.284 6.716 15 15 15s15-6.716 15-15v-17.134h66.398v17.134c0 8.284 6.716 15 15 15s15-6.716 15-15v-17.134h66.4v17.134c0 8.284 6.716 15 15 15s15-6.716 15-15v-17.134h66.4v17.134c0 8.284 6.716 15 15 15s15-6.716 15-15v-17.134h41.232c13.879 0 25.17 11.29 25.17 25.167v41.233h-452v-41.233c0-13.877 11.29-25.167 25.166-25.167zm401.666 419.867h-401.666c-13.876 0-25.166-11.29-25.166-25.167v-298.3h452v298.3c0 13.877-11.291 25.167-25.168 25.167z"></path><path d="m151.566 208.867h-64.267c-8.284 0-15 6.716-15 15v64.266c0 8.284 6.716 15 15 15h64.268c8.284 0 15-6.716 15-15v-64.266c-.001-8.284-6.716-15-15.001-15zm-15 64.266h-34.268v-34.266h34.268z"></path><path d="m424.699 208.867h-64.266c-8.284 0-15 6.716-15 15v64.266c0 8.284 6.716 15 15 15h64.266c8.284 0 15-6.716 15-15v-64.266c0-8.284-6.716-15-15-15zm-15 64.266h-34.266v-34.266h34.266z"></path><path d="m151.566 337.4h-64.267c-8.284 0-15 6.716-15 15v64.266c0 8.284 6.716 15 15 15h64.268c8.284 0 15-6.716 15-15v-64.266c-.001-8.284-6.716-15-15.001-15zm-15 64.266h-34.268v-34.266h34.268z"></path><path d="m424.699 337.4h-64.266c-8.284 0-15 6.716-15 15v64.266c0 8.284 6.716 15 15 15h64.266c8.284 0 15-6.716 15-15v-64.266c0-8.284-6.716-15-15-15zm-15 64.266h-34.266v-34.266h34.266z"></path><path d="m288.133 337.4h-64.268c-8.284 0-15 6.716-15 15v64.266c0 8.284 6.716 15 15 15h64.268c8.284 0 15-6.716 15-15v-64.266c0-8.284-6.716-15-15-15zm-15 64.266h-34.268v-34.266h34.268z"></path><path d="m279.475 222.673-34.834 34.836-12.116-12.116c-5.857-5.858-15.355-5.858-21.213 0s-5.858 15.355 0 21.213l22.723 22.723c2.813 2.813 6.628 4.394 10.606 4.394 3.979 0 7.794-1.581 10.607-4.394l45.441-45.443c5.857-5.858 5.857-15.355 0-21.213-5.859-5.858-15.356-5.858-21.214 0z"></path></g></svg>
            </span>
                        <span class="mt-1 ms-2">Booking Details</span>
                      </p>
                    </div>
                  </div>
                </div>
              </div>

            <div class="row pt-4">
              <div class="col-lg-6">
                <div class="border-0">
                    <div class="card global-shadow p-4 w-100">
                        <ul class="list-group">
                            <li class="list-group-item d-flex justify-content-between align-items-center py-3 border-0 border-bottom fs-14 px-2 flex-lg-row flex-column text-capitalize">Pick Up<span class="fw-600 text-capitalize listing-text">{{ $BookingDetails->pickup_location }}</span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center py-3 border-0 border-bottom fs-14 px-2 flex-lg-row flex-column text-capitalize">Drop off<span class="fw-600 text-capitalize listing-text">@if( $BookingDetails->drop_points->isNotEmpty() )
                                            @foreach( $BookingDetails->drop_points as $dropPoints )
                                            {{ $dropPoints->drop_location }}
                                            @break;
                                            @endforeach
                                            @else
                                            no location available
                                            @endif</span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center py-3 border-0 border-bottom fs-14 px-2 flex-lg-row flex-column text-capitalize">Date<span class="fw-600 text-capitalize">{{ \Carbon\Carbon::parse($BookingDetails->pickup_date)->format('jS F Y') }}</span>
                            </li>
                              <li class="list-group-item d-flex justify-content-between align-items-center py-3 border-0 border-bottom fs-14 px-2 flex-lg-row flex-column text-capitalize">Time<span class="fw-600 text-capitalize">{{ \Carbon\Carbon::parse($BookingDetails->pickup_time)->format('H:i:s') }}</span>
                              </li>
                              <li class="list-group-item d-flex justify-content-between align-items-center py-3 border-0 border-bottom fs-14 px-2 flex-lg-row flex-column text-capitalize">Ride Amount<span class="fw-600 text-capitalize">${{ $BookingDetails->total_fare }}</span>
                              </li>
                              <li class="list-group-item d-flex justify-content-between align-items-center py-3 border-0 border-bottom fs-14 px-2 flex-lg-row flex-column text-capitalize">Rider Name<span class="fw-600 text-capitalize">{{ $BookingDetails->rider->first_name ?? '' }} {{ $BookingDetails->rider->last_name ?? '' }}
                              </span>
                              </li>
                               <li class="list-group-item d-flex justify-content-between align-items-center py-3 border-0 border-bottom fs-14 px-2 flex-lg-row flex-column text-capitalize">Driver Name<span class="fw-600 text-capitalize">{{$BookingDetails->driver->first_name ?? '' }} {{ $BookingDetails->driver->last_name ?? '' }}
                              </span>
                              </li>
                              <li class="list-group-item d-flex justify-content-between align-items-center py-3 border-0 border-bottom fs-14 px-2 flex-lg-row flex-column text-capitalize">Booking Status<span class="fw-600 text-capitalize">
                                 @php
                                    switch($BookingDetails->status) {
                                        case 0:
                                            $status = 'Pending';
                                            break;
                                        case 1:
                                            $status = 'Accepted';
                                            break;
                                        case 2:
                                            $status = 'Delayed';
                                            break;
                                        case 3:
                                            $status = 'Completed';
                                            break;
                                        case 4:
                                            $status = 'Cancelled';
                                            break;
                                        case 5:
                                            $status = 'Refunded';
                                            break;
                                        default:
                                            $status = 'Unknown';
                                    }
                                @endphp
                                  {{ $status }}</span>
                              </li>
                            </ul>
                    </div>
                  </div>
                </div>

                <div class="col-lg-6">
                    <div class="border-0">
                        <div class="card global-shadow  w-100">
                            <div class="row justify-content-center h-100">
                              <div class="col-md-12 col-xl-12 chat">
                                <div class="card">
                                  <div class="card-header msg_head">
                                    <div class="d-flex bd-highlight">
                                      <div class="user_info pr-0">
                                        <span>Group Chat</span>
                                        <!-- <p>1767 Messages</p> -->
                                      </div>
                                  
                                    </div>
                             
                                  </div>
                                  <div class="card-body msg_card_body">
                                      
                                      @if($messages->isNotEmpty())
                                        @foreach($messages as $message)
                                            @php
                                                $liClass = $message->isAdmin == 1 ? 'justify-content-end' : 'justify-content-start';
                                                
                                                    if( $message->isAdmin == 1){
                                                       $imgSrc =  asset('public/assets/images/admin/admin.png');
                                                    }else{
                                                        //check if user driver then set user image to source image 
                                                        if ($message->source_user_id == $BookingDetails->driver_id) {
                                                            $imgSrc = $BookingDetails->driver->profile_pic 
                                                                ?  asset('public/storage/' . $BookingDetails->driver->profile_pic) 
                                                                : 'https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg';
                                                        } else {
                                                            // Assuming the message sender is the rider
                                                            $imgSrc = $BookingDetails->rider->profile_pic 
                                                                ?  asset('public/storage/' . $BookingDetails->rider->profile_pic) : 'https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg';
                                                        }
                                                         
                                                    
                                                    }
                                                $createdAt = \Carbon\Carbon::parse($message->created_at);
                                    
                                                $displayDate = $createdAt->isToday() 
                                                    ? 'Today' 
                                                    : $createdAt->format('l');
                                    
                                                $time = $createdAt->format('g:i A'); 
                                            @endphp
                                            
                                            <div class="d-flex {{ $liClass }} mb-4">
                                                @if($message->MessageType == 'image')
                                                    <div class="img_cont_msg">
                                                        <img src="{{ $imgSrc }}" class="rounded-circle user_img_msg">
                                                    </div>
                                                    <div class="msg_cotainer">
                                                        <img src="{{ asset('storage/' . $message->message) }}">
                                                        <span class="msg_time">{{ $time }}, {{ $displayDate }}</span>
                                                    </div>
                                                @elseif($message->MessageType == 'audio')
                                                    <div class="img_cont_msg">
                                                        <img src="{{ $imgSrc }}" class="rounded-circle user_img_msg">
                                                    </div>
                                                    <div class="msg_cotainer">
                                                        <audio controls>
                                                            <source src="{{ asset('storage/' . $message->message) }}" type="audio/wav">
                                                            Your browser does not support the audio element.
                                                        </audio>
                                                        <span class="msg_time">{{ $time }}, {{ $displayDate }}</span>
                                                    </div>
                                                @elseif($message->MessageType == 'file')
                                                    <div class="img_cont_msg">
                                                        <img src="{{ $imgSrc }}" class="rounded-circle user_img_msg">
                                                    </div>
                                                    <div class="msg_cotainer">
                                                        @php
                                                            $fileName = basename($message->message);
                                                        @endphp
                                                        <a id="fileDownload" href="{{ asset('storage/' . $message->message) }}" download>
                                                            <img src="{{ asset('assets/images/document.svg') }}" alt="File Icon">
                                                            <span>{{ $fileName }}</span>
                                                        </a>
                                                        <span class="msg_time">{{ $time }}, {{ $displayDate }}</span>
                                                    </div>
                                                @else
                                                    <div class="img_cont_msg">
                                                        <img src="{{ $imgSrc }}" class="rounded-circle user_img_msg">
                                                    </div>
                                                    <div class="msg_cotainer">
                                                        {{ $message->message }}
                                                        <span class="msg_time">{{ $time }}, {{ $displayDate }}</span>
                                                    </div>
                                                @endif
                                            </div>
                                        @endforeach
                                    @else
                                        <div class="text-center text-muted mt-3">
                                            <p>No recent chat</p>
                                        </div>
                                    @endif

                                  </div>
                                  <div class="card-footer">
                                    <div class="input-group">
                                       <form id="sendMessageForm">
                                        <div class="d-flex align-items-center justify-content-between gap-2">
                                            <div class="w-100">
                                        <input type="hidden" id="roomID" name="roomID">
                                        <input type="hidden" id="receiverID" name="receiverID" value="">
                                         <div id="imageContainer" style="display:none;">
                                            <img id="imagePreview" src="" alt="Image Preview" class="img-fluid mt-2"/>
                                            <span id="removeImage" style="cursor:pointer; color:red; font-size:20px; position:absolute;">×</span>
                                        </div>
                                        
                                        <div id="audioContainer" style="display: none;">
                                            <audio id="audioPreview" controls></audio>
                                           <span id="removeAudio" style="cursor:pointer; color:red; font-size:20px; position:absolute;">×</span>
                                        </div>
                                       <p id="recordingStatus" style="color: red; display: none; font-weight: bold;"><span id="timer">00:00</span> Recording...</p>
                                      <textarea id="message" name="message" class="form-control type_msg" placeholder="Type your message..."></textarea>
                                         
                                            </div>
                                            <div class="d-flex align-items-center gap-2">
                                           
                                        
                                       <span class="voice-record">
                                            <img id="startRecord" src="{{ asset('public/assets/images/record.svg') }}" alt="Start Recorder" style="cursor: pointer;">
                                            <img id="stopRecord" src="{{ asset('public/assets/images/stop.svg') }}" alt="Stop Recorder" style="cursor: pointer; display: none;">
                                        </span>
        
    
                                       <div class="file_uploader">
                                                <input type="file" id="file" name="file" accept="image/*,application/pdf" class="form-control">
                                                <div class="file_upload">
                                                    <svg width="22" height="22" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                        <path d="M11.6482 6.35203C11.7005 6.40427 11.742 6.46631 11.7703 6.5346C11.7986 6.60288 11.8131 6.67608 11.8131 6.75C11.8131 6.82392 11.7986 6.89712 11.7703 6.96541C11.742 7.03369 11.7005 7.09573 11.6482 7.14797L7.14817 11.648C7.09591 11.7002 7.03386 11.7417 6.96558 11.77C6.8973 11.7983 6.82411 11.8128 6.7502 11.8128C6.67629 11.8128 6.6031 11.7983 6.53482 11.77C6.46654 11.7417 6.40449 11.7002 6.35223 11.648C6.29997 11.5957 6.25851 11.5337 6.23023 11.4654C6.20195 11.3971 6.18739 11.3239 6.18739 11.25C6.18739 11.1761 6.20195 11.1029 6.23023 11.0346C6.25851 10.9663 6.29997 10.9043 6.35223 10.852L10.8522 6.35203C10.9045 6.29973 10.9665 6.25824 11.0348 6.22994C11.1031 6.20163 11.1763 6.18706 11.2502 6.18706C11.3241 6.18706 11.3973 6.20163 11.4656 6.22994C11.5339 6.25824 11.5959 6.29973 11.6482 6.35203ZM15.1596 2.84063C14.7939 2.47495 14.3599 2.18488 13.8821 1.98698C13.4044 1.78908 12.8923 1.68722 12.3752 1.68722C11.8581 1.68722 11.346 1.78908 10.8683 1.98698C10.3905 2.18488 9.95646 2.47495 9.59083 2.84063L7.47723 4.95352C7.37168 5.05907 7.31239 5.20222 7.31239 5.35149C7.31239 5.50075 7.37168 5.64391 7.47723 5.74945C7.58278 5.855 7.72593 5.9143 7.8752 5.9143C8.02447 5.9143 8.16762 5.855 8.27317 5.74945L10.3868 3.64008C10.9161 3.12233 11.6283 2.83424 12.3688 2.83832C13.1092 2.8424 13.8182 3.13832 14.3419 3.66186C14.8655 4.18541 15.1615 4.89433 15.1658 5.63479C15.17 6.37525 14.882 7.08749 14.3643 7.61696L12.25 9.73055C12.1445 9.836 12.0852 9.97907 12.0851 10.1283C12.085 10.2775 12.1442 10.4206 12.2497 10.5261C12.3551 10.6317 12.4982 10.691 12.6474 10.6911C12.7966 10.6911 12.9397 10.6319 13.0453 10.5265L15.1596 8.40938C15.5252 8.04374 15.8153 7.60966 16.0132 7.13191C16.2111 6.65417 16.313 6.14212 16.313 5.625C16.313 5.10789 16.2111 4.59584 16.0132 4.11809C15.8153 3.64035 15.5252 3.20626 15.1596 2.84063ZM9.72723 12.2498L7.61364 14.3634C7.35354 14.6294 7.04326 14.8411 6.70078 14.9863C6.3583 15.1315 5.99042 15.2073 5.61843 15.2094C5.24645 15.2114 4.87775 15.1396 4.53369 14.9982C4.18963 14.8568 3.87704 14.6485 3.61403 14.3855C3.35102 14.1224 3.1428 13.8098 3.00144 13.4657C2.86007 13.1216 2.78837 12.7529 2.79049 12.3809C2.7926 12.0089 2.86849 11.6411 3.01375 11.2986C3.15902 10.9562 3.37078 10.6459 3.63676 10.3859L5.74965 8.27297C5.8552 8.16742 5.9145 8.02427 5.9145 7.875C5.9145 7.72573 5.8552 7.58258 5.74965 7.47703C5.64411 7.37149 5.50095 7.31219 5.35169 7.31219C5.20242 7.31219 5.05926 7.37149 4.95372 7.47703L2.84083 9.59063C2.10236 10.3291 1.6875 11.3307 1.6875 12.375C1.6875 13.4193 2.10236 14.4209 2.84083 15.1594C3.57929 15.8978 4.58086 16.3127 5.6252 16.3127C6.66954 16.3127 7.67111 15.8978 8.40958 15.1594L10.5232 13.0451C10.6286 12.9395 10.6878 12.7964 10.6878 12.6472C10.6877 12.498 10.6284 12.3549 10.5228 12.2495C10.4173 12.144 10.2742 12.0848 10.125 12.0849C9.97575 12.085 9.83269 12.1443 9.72723 12.2498Z" fill="black"/>
                                                    </svg>

                                                </div>
                                            </div>
                                      <div class="input-group-append">
                                        <button type="submit" class="btn"><span class="input-group-text send_btn"><i class="fas fa-location-arrow">Send</i></span></button>
                                      </div>

                                            </div>
                                        </div>
                                       
                                       
                                      </form>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                    </div>
                      </div>
                    </div>
              </div>
        </div>
      </div>
@endsection

@section('js_scripts')
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.8.1/socket.io.js" integrity="sha512-8BHxHDLsOHx+flIrQ0DrZcea7MkHqRU5GbTHmbdzMRnAaoCIkZ97PqZcXJkKZckMMhqfoeaJE+DNUVuyoQsO3Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
  let counter = 0;
    // Establish socket connection
    const socket = io('https://php.parastechnologies.in:8072/?token=bsrnZIM5f3');

    socket.on('connect', () => {
      console.log('Connected to server with ID:', socket.id);
    });

    socket.on('connect_error', (err) => {
      console.error('Connection error:', err);
    });
</script>

<script>

   let mediaRecorder;
   let audioChunks = [];
   let recordingTimer;
   let seconds = 0;
    $(document).ready(function() 
    {
                const startIcon = $("#startRecord");
                const stopIcon = $("#stopRecord");
                const recordingStatus = $("#recordingStatus");
                const timer = $("#timer");
                const audioPreview = $("#audioPreview");
                const removeAudio = $("#removeAudio");
                const audioContainer = $("#audioContainer");
            
        
         function scrollToBottom() {
            const chatContainer = document.querySelector('.msg_card_body'); // Select the chat container by class
            if (chatContainer) {
                chatContainer.scrollTop = chatContainer.scrollHeight; // Scroll to the bottom
            }
        }
         // Scroll on page load
        scrollToBottom();
    
        // Safely pass PHP data to JavaScript
        const bookingDetails = @json($BookingDetails);

        const data = {
            roomID: `${bookingDetails.rider_id}-${bookingDetails.driver_id}`, // Construct dynamically
            userID: "{{ $admin->id}}",
        };

        // Emit createRoomEvent to the server with the data
        socket.emit('joinRoomEvent', data, (response) => {
            // console.log('Room created:sdf', response);
            // console.log(response , "1");
            if (response.success) {
                
                console.log(`Room ${response.roomName} created successfully.`);
            } else {
                console.error(`Failed to create room: ${response.message}`);
            }
        });
        
        
          socket.on('joinRoom', (response) => {
                console.log('Room created:', response);
                
                const roomID = data.roomID;
                const driverID = bookingDetails.driver_id;
                
                
                $('#roomID').val(roomID);
                $('#receiverID').val(driverID);
                if(response.status === 400){
                    // alert("No Recent Chat");
                    console.log("No Recent Chat");
                    
                }
                if(response.status === 200)
                {
                    console.log(response.data);
                }
                // const roomID = response.data.roomID;
                // $('#roomID').val(roomID);
                // console.log(roomID, "roomID");
               
            });
            
         $('#sendMessageForm').on('submit', function(e) {
            e.preventDefault();
        
            const message = $('#message').val();
            const roomID = $('#roomID').val();
            const receiverID = $('#receiverID').val();
            const fileInput = $('#file')[0].files[0]; 
        
            let fileType = '';
            let filePath = ''; 
        
            if (fileInput) {
                console.log("File detected in form submission");
        
                if (fileInput.type.startsWith('image/')) {
                    fileType = 'image';
                    filePath = $('#imagePreview').attr('src'); // Use the value from `imagePreview`
                } else if (fileInput.type.startsWith('audio/')) {
                    fileType = 'audio';
                    filePath = audioPreview.attr('src'); // Use the audio source path
                } else {
                    fileType = 'file';
                    filePath = $('#file').attr('src'); 
                }
                if (!filePath) {
                    alert('No file to Attach!');
                    return;
                }
        
                // Extract the file path after `/storage/`
                const extractedFilePath = filePath.split('/storage/')[1];
        
                if (!extractedFilePath) {
                    alert('Invalid file path!');
                    return;
                }
        
                sendMessage(extractedFilePath, roomID, receiverID, fileType); // Send file data
                alert("File sent successfully!");
            } else if (message) {
                // Call function to emit event
                sendMessage(message, roomID, receiverID, "Text"); // Send only the text message
            } else {
                alert('Please select an image or write a message.');
            }
        });
        
        
        function sendMessage(content, roomID, receiverID, fileType) {
            // const datetime = new Date().toISOString().slice(0, 19).replace('T', ' ');//Utc Time
            
            const now = new Date();
            const offset = now.getTimezoneOffset(); // Get the time zone offset in minutes
            const localTime = new Date(now.getTime() - offset * 60000) // Adjust to the local time zone
                .toISOString()
                .slice(0, 19)
                .replace('T', ' ');

            // console.log(localTime);
            
            // console.log(datetime);
            // console.log(content, roomID, receiverID, fileType);
            let data = {
                senderID: "{{$admin->id}}",
                receiverID: receiverID,
                roomID: roomID,
                bookingID: `${bookingDetails.id}`,
                message: content,
                MessageType: fileType,
                isAdmin: 1,
                createdTime: localTime,
                // Initialize message here
            };
               
               data.message = content; // Use the text message
               console.log(data,"data");
                socket.emit('SendMessage', data, (response) => {
                    console.log(response, "message sent");
                    if (response.success) {
                        console.log(`Message sent: ${response.message}`);
                    } else {
                        console.error(`Failed to send message: ${response.message}`);
                    }
                });
                
            /*
            if (isFile) {
                const fileInput = $('#file')[0].files[0]; // Get the file input
                const reader = new FileReader();

                reader.onload = function(event) {
                    // Prepare the file object for the server
                    data.file = {
                        originalname: fileInput.name, // The original file name
                        buffer: event.target.result // The file data (base64 encoded)
                    };
                    socket.emit('SendMessage', data, (response) => {
                        if (response.success) {
                            console.log(`Message sent: ${response.message}`);
                        } else {
                            console.error(`Failed to send message: ${response.message}`);
                    }
                    });
                };
                reader.readAsArrayBuffer(fileInput); // Read file as ArrayBuffer
            } else {
                */
             
            /*}*/
        }
        
        
        
          
       // Listener for sendMessageEvent
        socket.on('sendMessage', (response) => {
            console.log(response, "send message response");
        
            // Clear the input field if the message is sent
                $('#message').val(''); // Clear the file input
                $('#file').val(''); // Clear the file input
                $('#imagePreview').hide(); // Hide the image preview
                $('#imageContainer').hide(); // Hide the container with image and remove icon
                audioPreview.hide().removeAttr("src"); // Hide and clear audio preview
                audioContainer.hide();
                $('#message').show();
            
            const msg = response.data[0];
            console.log(msg);
        
            // Determine alignment based on the sender (isAdmin)
            const liClass = msg.isAdmin === 1 ? 'justify-content-end' : 'justify-content-start';
            const imgSrc = msg.isAdmin === 1 ? 'https://php.parastechnologies.in/valo/public/assets/images/admin/admin.png' : 'https://static.turbosquid.com/Preview/001292/481/WV/_D.jpg';
            
            const createdAt = new Date(msg.created_at);
                const time = createdAt.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true });
                const today = new Date();
                let displayDate = '';
        
                if (createdAt.toDateString() === today.toDateString()) {
                    displayDate = 'Today';
                } else if (
                    createdAt.toDateString() === 
                    new Date(today.setDate(today.getDate() - 1)).toDateString()
                ) {
                    displayDate = 'Yesterday';
                } else {
                    displayDate = createdAt.toLocaleDateString('en-US', { weekday: 'long' }); // Day name (e.g., Monday)
                }
            // Select the chat body container
            const chatBody = $('.card-body.msg_card_body');
            console.log(chatBody);
              
            if (msg.MessageType === "Text") {
                // Format the message timestamp
             
        
                // Append the new message to the chat body
                chatBody.append(`
                    <div class="d-flex ${liClass} mb-4">
                        <div class="img_cont_msg">
                            <img src="${imgSrc}" class="rounded-circle user_img_msg">
                        </div>
                        <div class="msg_cotainer">
                            ${msg.message}
                            <span class="msg_time">${time}, ${displayDate}</span>
                        </div>
                    </div>
                `);
        
                // Scroll to the bottom of the chat
                chatBody.scrollTop(chatBody.prop("scrollHeight"));
            } else if (msg.MessageType === "image"){
                  // Append the new message to the chat body
                chatBody.append(`
                    <div class="d-flex ${liClass} mb-4">
                        <div class="img_cont_msg">
                            <img src="${imgSrc}" class="rounded-circle user_img_msg">
                        </div>
                        <div class="msg_cotainer">
                            <img src="https://php.parastechnologies.in/valo/public/storage/${msg.message}" >
                            <span class="msg_time">${time}, ${displayDate}</span>
                        </div>
                    </div>
                `);
            }else if (msg.MessageType === "audio"){
                // Append the new message to the chat body
                chatBody.append(`
                    <div class="d-flex ${liClass} mb-4">
                        <div class="img_cont_msg">
                            <img src="${imgSrc}" class="rounded-circle user_img_msg">
                        </div>
                        <div class="msg_cotainer">
                           <audio controls>
                                        <source src="https://php.parastechnologies.in/valo/public/storage/${msg.message}" type="audio/wav">
                                        Your browser does not support the audio element.
                                    </audio>
                            <span class="msg_time">${time}, ${displayDate}</span>
                        </div>
                    </div>
                `);
            }else if (msg.MessageType === "file") {
                // Append the new message to the chat body
                chatBody.append(`
                    <div class="d-flex ${liClass} mb-4">
                        <div class="img_cont_msg">
                            <img src="${imgSrc}" class="rounded-circle user_img_msg">
                        </div>
                        <div class="msg_cotainer">
                            <a id="fileDownload" href="https://php.parastechnologies.in/valo/public/storage/${msg.message}" download>
                                <img src="https://php.parastechnologies.in/valo/public/assets/images/document.svg" alt="File Icon" style="width: 40px; height: 40px;">
                                <span class="">${getFileName(msg.message)}</span>
                            </a>
                            <span class="msg_time">${time}, ${displayDate}</span>
                        </div>
                    </div>
                `);
            }

        });
        
        // extract the file name
        function getFileName(filePath) {
            return filePath.split('/').pop(); 
        }
        
        
       $('#removeImage').on('click', function () {
             // in case file type is pdf we get its actual path from file input
            const documentFile =   $('#file').attr('src');
            if(documentFile){
                filePath = documentFile;
            }else{
                // Get the file path from the image preview
                const filePath = $('#imagePreview').attr('src'); // Assuming 'src' contains the full URL
            }
            if (!filePath) {
                alert('No file to remove!');
                return;
            }
        
            // Extract the file path after `/storage/`
            const extractedFilePath = filePath.split('/storage/')[1];
        
            if (!extractedFilePath) {
                alert('Invalid file path!');
                return;
            }
        
            // Call AJAX to delete the file
            $.ajax({
                url: '/valo/api/delete-file', // API endpoint
                type: 'POST', // Use POST for file deletion
                data: {
                    file_path: extractedFilePath
                },
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') // Add CSRF token for security
                },
                success: function (response) {
                    if (response.success) {
                        // Clear file input and hide image preview
                        $('#file').val(''); 
                        $('#imagePreview').hide(); 
                        $('#imageContainer').hide();
                        $('#message').show(); 
        
                        alert('File removed successfully!');
                    } else {
                        alert('Error: ' + response.message);
                    }
                },
                error: function (xhr, status, error) {
                    console.error('AJAX Error:', error);
                    alert('Failed to delete the file. Please try again.');
                }
            });
        });

        
        
        $('#file').on('change', function (e) {
            const fileInput = e.target.files[0]; // Get the file
            
            console.log(fileInput, "fileInput");
            const roomID = $('#roomID').val();
            const receiverID = $('#receiverID').val();
            
            // Check if file is selected and valid
            if (fileInput && (fileInput.type.startsWith('image/') || fileInput.type === 'application/pdf' || fileInput.type.startsWith('audio/'))) {
               console.log("filetsdfs");
                 const tempURL = URL.createObjectURL(fileInput);
                $('#message').hide(); // Hide the textarea
               
        
                let fileType = '';
                if (fileInput.type.startsWith('image/')) {
                    $('#imagePreview').attr('src', tempURL).show();
                    $('#imageContainer').show();
                    
                    fileType = 'image';
                } else if (fileInput.type.startsWith('audio/')) {
                    fileType = 'audio';
                } else {
                    $('#imagePreview').attr('src', "{{ asset('public/assets/images/document.svg') }}").show();
                    $('#imageContainer').show();
                    fileType = 'file';
                }
        
                // Call the API to upload the file
                const formData = new FormData();
                formData.append('file', fileInput); // Add the file
                formData.append('type', fileType); // Add the file type
        
                $.ajax({
                    url: '/valo/api/upload-file', // API endpoint
                    type: 'POST',
                    data: formData,
                    processData: false, // Prevent jQuery from automatically transforming the FormData object
                    contentType: false, // Use the FormData object as-is
                    success: function (response) {
                        console.log(response, "API Response");
        
                        if (response.success) {
                            const fileUrl = response.data.path; // URL returned by the API
                            console.log(fileUrl);
                            // Handle file preview
                            if (fileType === 'image') {
                                console.log(fileType);
                                fullPath = 'https://php.parastechnologies.in/valo/public/storage/'+fileUrl;
                                
                                // sendMessage(fileUrl, roomID, receiverID, "image");
                                // console.log(sendMessage);
                                $('#imagePreview').attr('src', fullPath).show(); // Show the uploaded image
                            } else if (fileType === 'audio') {
                                console.log("audio file type",fileUrl);
                                fullPath = 'https://php.parastechnologies.in/valo/public/storage/'+fileUrl;
                                $('#imagePreview').hide();
                                $('#imageContainer').hide();
                                audioPreview.attr("src", fullPath);
                                audioPreview.attr("src", fullPath).show(); 
                                // fullPath
                                
                                // $('#audioContainer').html(`
                                //     <audio controls>
                                //         <source src="${fileUrl}" type="${fileInput.type}">
                                //         Your browser does not support the audio element.
                                //     </audio>
                                // `).show();
                            } else if (fileType === 'file') {
                                 fullPath = 'https://php.parastechnologies.in/valo/public/storage/'+fileUrl;
                                 
                                $('#file').attr('src',fullPath);
                                // $('#imagePreview').attr('src', "{{ asset('public/assets/images/document.svg') }}").show(); // Show a placeholder for files like PDF
                            }
                            
                            alert('File is ready to Send!');
                            
                        } else {
                            alert(response.message || 'File upload failed!');
                            $('#message').show();
                            $('#imageContainer').hide();
                            $('#imagePreview').hide();
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('Error:', error);
                        alert('An error occurred while uploading the file.');
                        $('#message').show();
                        $('#imageContainer').hide();
                        $('#imagePreview').hide();
                    },
                });
            } else {
                $('#message').show(); // Show the textarea
                $('#imageContainer').hide();
                $('#imagePreview').hide(); // Hide the image preview
                alert('Please select a valid image, audio, or PDF file.');
            }
        });
        
        
             // Format time as MM:SS
            function formatTime(seconds) {
                const minutes = Math.floor(seconds / 60).toString().padStart(2, '0');
                const remainingSeconds = (seconds % 60).toString().padStart(2, '0');
                return `${minutes}:${remainingSeconds}`;
            }
        
            // Start Timer
            function startTimer() {
                seconds = 0;
                timer.text(formatTime(seconds));
                recordingTimer = setInterval(() => {
                    seconds++;
                    timer.text(formatTime(seconds));
                }, 1000);
            }
        
            // Stop Timer
            function stopTimer() {
                clearInterval(recordingTimer);
            }
        
        
        
        
          // Start Recording
            startIcon.on("click", async function () {
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                    mediaRecorder = new MediaRecorder(stream);
        
                    mediaRecorder.ondataavailable = (event) => {
                        audioChunks.push(event.data);
                    };
        
                    mediaRecorder.onstop = () => {
                         stopTimer();
                         
                        const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
                        audioChunks = [];
        
                        // Create an object URL for the audio blob
                        const audioUrl = URL.createObjectURL(audioBlob);
                        $('#imagePreview').hide();
                        $('#imageContainer').hide();
                        audioContainer.show();
                        audioPreview.attr("src", audioUrl);
                        audioPreview.attr("src", audioUrl).show(); // Show audio preview
                        recordingStatus.hide(); // Hide recording status
                        uploadFile(audioBlob); //upload file 
                        // uploadAudio(audioBlob); // Upload audio to server
                    };
        
                    mediaRecorder.start();
                    $('#message').hide();
                    startIcon.hide(); // Hide start recording icon
                    stopIcon.show(); // Show stop recording icon
                    recordingStatus.show(); // Show recording status
                    startTimer(); // Start recording timer
                } catch (error) {
                    console.error("Error accessing microphone:", error);
                    alert("Microphone access is required to record voice notes.");
                }
            });
        
            // Stop Recording
            stopIcon.on("click", function () {
                mediaRecorder.stop();
                stopIcon.hide(); // Hide stop recording icon
                startIcon.show(); // Reset to start recording icon
            });
            
            
               // Remove Audio
            removeAudio.on("click", function () {
                     // Get the file path from the image preview
                    const filePath = audioPreview.attr('src'); // Assuming 'src' contains the full URL
                
                    if (!filePath) {
                        alert('No file to remove!');
                        return;
                    }
                    // Extract the file path after `/storage/`
                    const extractedFilePath = filePath.split('/storage/')[1];
                
                    if (!extractedFilePath) {
                        alert('Invalid file path!');
                        return;
                    }
                          // Call AJAX to delete the file
                    $.ajax({
                        url: '/valo/api/delete-file', // API endpoint
                        type: 'POST', // Use POST for file deletion
                        data: {
                            file_path: extractedFilePath
                        },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') // Add CSRF token for security
                        },
                        success: function (response) {
                            if (response.success) {
                                // Clear file input and hide image preview
                                $('#file').val(''); 
                                audioPreview.hide().removeAttr("src"); // Hide and clear audio preview
                                audioContainer.hide(); // Hide remove button
                                $('#message').show(); 
                
                                alert('File removed successfully!');
                            } else {
                                alert('Error: ' + response.message);
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('AJAX Error:', error);
                            alert('Failed to delete the file. Please try again.');
                        }
                    });
            });
            //End audio remove
    
            
            
            // Upload File
            function uploadFile(audioBlob) {
                if (!audioBlob) {
                    console.error("No audioBlob provided.");
                    return;
                }
            
                // Create a File object from the Blob
                const audioFile = new File([audioBlob], "voice_note.wav", {
                    type: "audio/wav",
                });
            
                // Create a DataTransfer object to hold the file
                const dataTransfer = new DataTransfer();
                dataTransfer.items.add(audioFile);
            
                // Assign the file to the file input
                const fileInput = $("#file")[0];
                fileInput.files = dataTransfer.files;
            
                // Trigger the change event
                $("#file").trigger("change");
            }
        
            // Upload Audio
            function uploadAudio(audioBlob) {
                const formData = new FormData();
            
                // Generate a timestamp
                // const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); // Replaces ':' and '.' with '-'
            
                // Append the audio file with a timestamp in the file name
                // const fileName = `voice_note_${timestamp}.wav`;
                const fileName = `voice_note.wav`;
                formData.append("file", audioBlob, fileName);
                formData.append('type', 'audio');
                
                $.ajax({
                    url: '/valo/api/upload-file', 
                    type: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                    headers: {
                        "X-CSRF-TOKEN": "{{ csrf_token() }}"
                    },
                    success: function (response) {
                        
                        console.log(response, 'audio upload');
                        
                        alert("audio note ready to send.");
                        console.log(response);
                    },
                    error: function (error) {
                        alert("Failed to upload audio.");
                        console.error(error);
                    }
                });
            }
        
        
        
            $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
                url: "{{url('/admin/chat')}}",
                method: 'POST',
                data: { roomID: roomID },
                success: function(response) {
                  /*  if (response.status === 200) {
                        const messages = response.data;
                        const chatBody = $('.msg-body ul');
                        chatBody.empty();

                        messages.forEach(msg => {
                            const liClass = msg.senderID === userId ? 'sender' : 'repaly';
                            chatBody.append(`<li class="${liClass}"><p>${msg.message}</p><span class="time">${msg.created_at}</span></li>`);
                        });

                        // chatBody.scrollTop(chatBody.prop("scrollHeight"));
                        $('.chatbox .modal-body').scrollTop($('.chatbox .modal-body ul').innerHeight());
                    } else {
                        console.log(response.message);
                    }
                    */
                },
                error: function(xhr, status, error) {
                    console.log('Error:', error);
                }
            });
        
    });
</script>

@endsection


