@extends('layouts.setting')

<title>Inbox</title>

@section('content')

<style>
    div.chat-inbox>.chat-content-wrapper>.chat-message>.single-message-chat>.user-message{
        max-width:90%!important;
    }
    
    .receiver-message{
        word-break: break-all;
    }
</style>

<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($single_ticket->id == $ticket->id) 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">{!! \Illuminate\Support\Str::limit(strip_tags($ticket?->lastResponse?->message) ?? '', 90) !!}</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>-->
      
      
      <!-- Canned Response Modal -->
<!-- Canned Response Modal -->
<div id="cannedResponseModal" class="modal">
  <div class="modal-content">
    <span class="close-button">&times;</span>
    <h2>Canned Responses</h2>
    <ul>
        
        @if(count($canned_response) > 0)
                    @foreach($canned_response as $index => $value)
                    
                    @php
                    
                    $result = json_decode($value->value);
                    
                    @endphp
        
      <li><button class="canned-response" data-response="{{$result->text}}">{{$result->name}}</button></li>
      @endforeach
                    @endif
    </ul>
  </div>
</div>
      
      
      
      
      
      
      <script>
        //CKEDITOR.replace('editor1');
        
       CKEDITOR.plugins.add('addcannedresponse', {
    init: function(editor) {
        editor.addCommand('addCannedResponseCmd', {
            exec: function(editor) {
               document.getElementById('cannedResponseModal').style.display = 'block';
            }
        });
        editor.ui.addButton('AddCannedResponse', {
            label: 'Insert Canned Response',
            command: 'addCannedResponseCmd',
            icon: 'https://kundesone.no/images/canned.png', // Use an accessible icon URL or local path
            toolbar: 'insert,0'
        });
    }
});

CKEDITOR.replace('editor1', {
    extraPlugins: 'addcannedresponse', // Ensure your plugin is added to extraPlugins
    // Optionally customize your toolbar further, or use the default configuration
    toolbarGroups: [
        { name: 'clipboard',   groups: [ 'clipboard', 'undo' ] },
        { name: 'editing',     groups: [ 'find', 'selection', 'spellchecker' ] },
        { name: 'links' },
        { name: 'insert' },
        { name: 'forms' },
        { name: 'tools' },
        { name: 'document',	   groups: [ 'mode', 'document', 'doctools' ] },
        { name: 'others' },
        '/',
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'paragraph',   groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
        { name: 'styles' },
        { name: 'colors' },
        { name: 'about' }
    ]
});


        // Get the modal
        var modal = document.getElementById("cannedResponseModal");
        
        // Get the button that opens the modal
        var btn = document.getElementsByClassName("canned-response");
        
        // Get the <span> element that closes the modal
        var span = document.getElementsByClassName("close-button")[0];
        
        // When the user clicks on <span> (x), close the modal
        span.onclick = function() {
            modal.style.display = "none";
        }
        
        // When the user clicks anywhere outside of the modal, close it
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }
        
        // Add event listeners to canned response buttons
        Array.from(btn).forEach(function(element) {
          element.addEventListener('click', function() {
            var response = this.getAttribute('data-response');
            CKEDITOR.instances.editor1.insertHtml(response);
            modal.style.display = "none";
          });
        });
        
        
        
        
      </script>

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

<!-- Tagify CSS -->
<link href="https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.css" rel="stylesheet">

<!-- Tagify JS -->
<script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.min.js"></script>



<style>
    #cke_editor1{
        width:100%!important;
    }
    
    div.chat-inbox.chat-box{
        display: flex;
    flex-direction: column;
    justify-content: space-between;
    }
    

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0,0,0,0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 100%;
  max-width: 600px;
}

.close-button {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
  background:;#748c62 !important
}

.close-button:hover,
.close-button:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}


#cannedResponseModal ul {
  list-style: none;
  padding: 0;
}

#cannedResponseModal li {
  padding: 8px 0; /* Spacing between buttons */
}

.canned-response {
  width: 100%;
  padding: 10px;
  font-size: 16px;
  border: none;
  background-color: #4CAF50;
  color: white;
  cursor: pointer;
  border-radius: 5px;
  transition: background-color 0.3s, box-shadow 0.3s;
}

.canned-response:hover {
  background-color: #45a049;
  box-shadow: 0 2px 4px 0 rgba(0,0,0,0.24);
}



</style>




<!--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() === '') {
                toastr.error('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