@extends('layouts.setting')

<title>Inbox</title>

@section('content')

<div class="inbox-content-wrapper w-100 ">
    <div class="inbox-inner-wrapper w-100  d-flex">

      <!-- User Box -->
      <div class="box user-box">
        <ul>
            @foreach($tickets as $key => $ticket)
          <li style="cursor:pointer;" class="chat-detail-item @if($key == 0) active @endif inbox-user-box d-flex" data-ticket-id="{{ $ticket->id }}">
            <div class="chat-user-img inbox position-relative">
              <img src="{{ asset('images/Avatar.png') }}" alt="User">
              <div class="chat-status-icon rounded-circle text-center align-content-center position-absolute">
                <img src="{{ asset('images/icons/chat-round.svg') }}" alt="Chat Round">
              </div>
            </div>
            <div class="chat-message-info d-flex align-self-baseline">

              <div class="chat-ticket-row align-items-center d-flex justify-content-between">
                <div class="ticket-status d-flex flex-column">
                  <p class="color-dark-green receiver-name">{{$ticket->sender_name}}</p>
                  <p class="receiver-message">{!! strip_tags($ticket?->lastResponse?->message) ?? '' !!}</p>
                </div>
                <p class=" bold message-time">{{\Carbon\Carbon::parse($ticket?->lastResponse?->created_at)->format('h:i A') ?? ''}}</p>
              </div>
            </div>
          </li>
          @endforeach
        </ul>
      </div>

      <!-- Chat Box -->
      <div class="chat-inbox chat-box">
          <div class="chat-content-wrapper">
          </div>
        <!-- Send Message Input -->
        <div class="message-input-box">
          <!--<div class="select-user-row mt-2">-->
          <!--  <p>To:</p>-->
    
          <!--  <select name="skills" multiple="" class="ui fluid dropdown user-select-dropdown">-->
          <!--    <option value="">Select User</option>-->
          <!--    <option value="angular">Angular</option>-->
          <!--    <option value="css">CSS</option>-->
          <!--  </select>-->
          <!--</div>-->
          <div class="input-box-row">
            <div class="ui card inbox-send-message-card w-100">
              <!--<div class="content input-options bg-dark-green-color">-->
              <!--  <div class="input-option-row ">-->
              <!--    <img src="{{ asset('images/icons/B.png') }}" alt="">-->
              <!--    <img src="{{ asset('images/icons/I.png') }}" alt="">-->
              <!--    <img src="{{ asset('images/icons/Vector (5).png') }}" alt="">-->
              <!--    <img src="{{ asset('images/icons/Vector (6).png') }}" alt="">-->
              <!--    <img src="{{ asset('images/icons/Vector (8).png') }}" alt="">-->
              <!--    <img src="{{ asset('images/icons/drive.png') }}" alt="">-->
              <!--    <img src="{{ asset('images/icons/Vector (5).png') }}" alt="">-->
              <!--    <img src="{{ asset('images/icons/Vector (6).png') }}" alt="">-->
              <!--  </div>-->
              <!--</div>-->
              <div class="content d-flex align-items-end flex-column message-writing-content-area">
                <textarea rows="7" placeholder="Your Message"
                  class="form-control input-reply-textarea" id="editor1" required></textarea>
                <button class="ui button bg-light-green-color mt-4 color-light saveReply">
                  Reply
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--wysywyg editor-->
      <script src="https://cdn.ckeditor.com/4.16.0/standard/ckeditor.js"></script>
      <script>
        CKEDITOR.replace('editor1');
      </script>

      <!-- Action Box -->
      <div class="action-box">
        
      </div>
    </div>
</div>

<!--Script Tag-->
<script>
    $(document).ready(function(){
        var activeTicketId = $('.chat-detail-item.active').data('ticket-id');

        // Load chat messages for the active ticket on page load
        loadChatMessages(activeTicketId);
        loadActionBox(activeTicketId);

        // Click event to switch between tickets
        $('.chat-detail-item').on('click', function() {
            $('.chat-detail-item').removeClass('active');
            $(this).addClass('active');
            activeTicketId = $(this).data('ticket-id');
            loadChatMessages(activeTicketId);
            loadActionBox(activeTicketId);
        });

        // Function to load chat messages for a specific ticket
        function loadChatMessages(ticketId) {
            $.ajax({
                url: 'fetch-chat-messages/' + ticketId,
                method: 'GET',
                success: function(response) {
                    // Update chat box with fetched messages
                    $('.chat-content-wrapper').html(response);
                },
                error: function(error) {
                    console.log('Error loading messages:', error);
                }
            });
        }
        // Function to load action box for a specific ticket
        function loadActionBox(ticketId) {
            $.ajax({
                url: '/fetch-action-box/' + ticketId,
                method: 'GET',
                success: function(response) {
                    // Update action box with fetched content
                    $('.action-box').html(response);
                },
                error: function(error) {
                    console.log('Error fetching action box content:', error);
                }
            });
        }

        // Save reply
        $('.saveReply').on('click', function(){
            var message = CKEDITOR.instances.editor1.getData();
            if(message.trim() === '') {
                alert('Message cannot be empty');
                return;
            }
            $.ajax({
                url: '/store/response',
                method: 'POST',
                data: {
                    ticket_id: activeTicketId,
                    message: message,
                    _token: '{{ csrf_token() }}'
                },
                success: function(response) {
                    // Reload chat messages for the active ticket
                    loadChatMessages(activeTicketId);
                    loadActionBox(activeTicketId);
                    // Update the last response in the ticket list
                    var ticketElement = $('.chat-detail-item[data-ticket-id="' + activeTicketId + '"]');
                    ticketElement.find('.receiver-message').text(response.message);
                    ticketElement.find('.message-time').text(response.created_at);
                    // Clear the editor
                    CKEDITOR.instances.editor1.setData('');
                    
                    // window.location.reload();
                },
                error: function(error) {
                    console.log('Error creating a response:', error);
                }
            });
        });
    });
</script>
<script>
    $(document).ready(function(){
        $('.chat-detail-item').on('click', function(){
            $('.chat-detail-item').removeClass('active');
            $(this).addClass('active');
            var ticketId = $(this).data('ticket-id');
            fetchChatMessages(ticketId);
            updateActionBox(ticketId);
        });

        // Function to fetch and display chat messages for a ticket
        function fetchChatMessages(ticketId) {
            $.ajax({
                url: '/fetch-chat-messages/' + ticketId,
                method: 'GET',
                success: function(response) {
                    // Update chat box with fetched messages
                    $('.chat-content-wrapper').html(response);
                },
                error: function(error) {
                    console.log('Error fetching chat messages:', error);
                }
            });
        }

        // Function to update the action box for a ticket
        function updateActionBox(ticketId) {
            $.ajax({
                url: '/fetch-action-box/' + ticketId,
                method: 'GET',
                success: function(response) {
                    // Update action box with fetched content
                    $('.action-box').html(response);
                },
                error: function(error) {
                    console.log('Error fetching action box content:', error);
                }
            });
        }
    });
</script>


@endsection