<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);
}
.close-button {
    color: #aaa;
    /* float: right; */
    font-size: 28px;
    font-weight: bold;
    background: ;
    display: flex !important;
    justify-content: flex-end !important;
        margin-top: -14px;
            font-size: 32px;
}



</style>

<!-- Custom Modal post -->
<div id="customModal" class="modal">
  <div class="modal-content">
    <span class="modal-close">&times;</span>
    <h5>Assign Post</h5>
    <form id="assignForm">
        <input type="hidden" id="ticket-ids" name="ticket_ids">
      <div class="mb-3">
        <label for="recipient-name" class="col-form-label">Recipient:</label>
        @php
        $companyId = getSelectedCompany();
        $company_users = get_company_users($companyId);
        @endphp
        <select name="user_assigned" class="form-control" required>
            <option>Select User</option>
            @foreach($company_users as $company_user)
            <option value="{{$company_user->user->id}}">{{$company_user->user->name}}</option>
            @endforeach
        </select>
      </div>
      <div class="mb-3">
        <label for="message-text" class="col-form-label">Message:</label>
        <textarea class="form-control" id="message-text" name="message" required></textarea>
      </div>
    </form>
    <button type="button" class="btn btn-primary assign-post">Send</button>
  </div>
</div>
<!-- Custom Modal move-->
<div id="customModal2" class="modal">
  <div class="modal-content">
    <span class="modal-close">&times;</span>
    <h5>Move</h5>
    <form>
      <div class="mb-3">
        <label for="recipient-name" class="col-form-label">Conversation moved:</label>
        <input type="text" class="form-control" id="recipient-name" placeholder="Inbox">
      </div>
     
    </form>
    <button type="button" class="btn btn-primary">Confirm</button>
  </div>
</div>
<!-- Custom Modal Replay to multiple-->
<div id="customModal3" class="modal">
  <div class="modal-content">
    <span class="modal-close">&times;</span>
    <h5>Reply to multiple</h5>
    <form>
      <div class="content d-flex align-items-end flex-column message-writing-content-area">
        <textarea name="email_signature" id="editor1" rows="10" placeholder="Your Message"
            class="form-control input-reply-textarea" required></textarea>
        
      </div>
      <div style="display: flex;flex-direction: row-reverse;">
        <button type="button" class="btn btn-primary reply-to-multiple">Reply</button>
      </div>
     
    </form>

  </div>
</div>

<!-- Canned Response Modal -->
<div id="cannedResponseModal" class="modal">
  <div class="modal-content">
    <span class="close-button">&times;</span>
    <h2>Canned Responses</h2>
    <ul>
        @php
        $companyId = getSelectedCompany();
        $canned_response = \App\Models\CompanyMeta::where('company_id', $companyId)->where('key', 'canned_responses')->get();
        $email_signature = \App\Models\CompanyMeta::where('company_id', $companyId)->where('type', 'Email Signature')->first()?->value;
        @endphp
        @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) {
        // Command for inserting canned response
        editor.addCommand('addCannedResponseCmd', {
            exec: function(editor) {
                // Show your modal or handle canned response insertion
                document.getElementById('cannedResponseModal').style.display = 'block';
            }
        });

        // Command for inserting signature
        editor.addCommand('addSignatureCmd', {
            exec: function(editor) {
                var signatureHtml = `<br>{!! $email_signature !!}`; // Signature content
                CKEDITOR.instances.editor1.insertHtml(signatureHtml);
            }
        });

        // Add "Insert Canned Response" button
        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'
        });

        // Add "Insert Signature" button
        editor.ui.addButton('AddSignature', {
            label: 'Insert Signature',
            command: 'addSignatureCmd',
            icon: 'https://kundesone.no/images/signature-icon.png', // Placeholder icon URL, replace with a valid one
            toolbar: 'insert,1'
        });
    }
});

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>


<script>
$(document).ready(function() {
    var $handleMultipleButton = $('.handle-multiple-btn');
    var $selectAllCheckbox = $('#select-all');
    var $ticketCheckboxes = $('.ticket-checkbox');
    var $actionButtons = $('.handle_multiple__options .tags button');
    
    // Function to toggle button states
    function updateButtonStates() {
        var selectedCount = $ticketCheckboxes.filter(':checked').length;
        $actionButtons.prop('disabled', selectedCount === 0);
    }

    // Toggle checkboxes visibility
    $handleMultipleButton.on('click', function() {
        $('.content').toggleClass('handle-multiple-active');
    });

    // Toggle all checkboxes based on 'Select all'
    $selectAllCheckbox.on('change', function() {
        $ticketCheckboxes.prop('checked', $selectAllCheckbox.prop('checked'));
        updateButtonStates();
    });

    // Toggle button states when individual checkboxes change
    $ticketCheckboxes.on('change', function() {
        updateButtonStates();
    });

    // Initialize button states
    updateButtonStates();
});

</script>

<!--Assigned Post Start-->
<script>
$(document).ready(function() {
    $('.assign-post').on('click', function() {
        
        var selectedTickets = [];
        $('.ticket-checkbox:checked').each(function() {
            selectedTickets.push($(this).attr('id').replace('ticket-', ''));
        });
        $('#ticket-ids').val(selectedTickets.join(','));

        // SweetAlert2 confirmation dialog
        Swal.fire({
            title: 'Are you sure?',
            text: 'You are about to send this message.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, send it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Get form data
                var formData = $('#assignForm').serialize();

                // AJAX request to submit the form
                $.ajax({
                    url: 'assign/ticket',
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': "{{ csrf_token() }}"
                    },
                    data: formData,
                    success: function(response) {
                        // Show success notification
                        Swal.fire(
                            'Assigned!',
                            'Post Assigned Successfully!',
                            'success'
                        );
                        
                        location.reload();
                        // Hide the modal
                        $('#customModal').modal('hide');
                    },
                    error: function(xhr) {
                        // Show error notification
                        Swal.fire(
                            'Error!',
                            'An error occurred. Please try again.',
                            'error'
                        );
                    }
                });
            }
        });
    });
});
</script>

<!--Assigned Post End-->

<!--Delete Post Start-->
<script>
$(document).ready(function() {
    $('#delete-posts').on('click', function() {
        
        var selectedTickets = [];
        $('.ticket-checkbox:checked').each(function() {
            selectedTickets.push($(this).attr('id').replace('ticket-', ''));
        });

        var ticket_ids = selectedTickets.join(',');

        // SweetAlert2 confirmation dialog
        Swal.fire({
            title: 'Are you sure?',
            text: 'You are about to delete selected tickets.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete them!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // AJAX request to delete the tickets
                $.ajax({
                    url: 'delete/tickets',
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': "{{ csrf_token() }}"
                    },
                    data: {
                        ticket_ids: ticket_ids
                    },
                    success: function(response) {
                        // Show success notification
                        Swal.fire(
                            'Deleted!',
                            'Tickets have been deleted successfully.',
                            'success'
                        );
                        // Reload the page or update the UI as needed
                        location.reload();
                    },
                    error: function(xhr) {
                        // Show error notification
                        Swal.fire(
                            'Error!',
                            'An error occurred. Please try again.',
                            'error'
                        );
                    }
                });
            }
        });
    });
});
</script>

<!--Delete Post End-->

<!--Update Status Start-->
<script>
$(document).ready(function() {
    $('.update-posts-status').on('click', function() {
        
        var status = $(this).data('status');
        
        var selectedTickets = [];
        $('.ticket-checkbox:checked').each(function() {
            selectedTickets.push($(this).attr('id').replace('ticket-', ''));
        });

        var ticket_ids = selectedTickets.join(',');

        // SweetAlert2 confirmation dialog
        Swal.fire({
            title: 'Are you sure?',
            text: 'You are about to update the status of selected tickets.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, update it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // AJAX request to submit the form
                $.ajax({
                    url: 'update/ticket/status',
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': "{{ csrf_token() }}"
                    },
                    data: {
                        ticket_ids: ticket_ids,
                        status: status
                    },
                    success: function(response) {
                        // Show success notification
                        Swal.fire(
                            'Updated!',
                            'Tickets status has been updated successfully.',
                            'success'
                        );
                        // Optionally reload or update the page
                        location.reload();
                    },
                    error: function(xhr) {
                        // Show error notification
                        Swal.fire(
                            'Error!',
                            'An error occurred. Please try again.',
                            'error'
                        );
                    }
                });
            }
        });
    });
});
</script>

<!--Update Status End-->

<!-- Reply to Multiple Start -->
<script>
    $(document).ready(function() {
        $('.reply-to-multiple').on('click', function(){
            var message = CKEDITOR.instances.editor1.getData();
            if(message.trim() === '') {
                toastr.error('Message cannot be empty');
                return;
            }
            
            var selectedTickets = [];
            $('.ticket-checkbox:checked').each(function() {
                selectedTickets.push($(this).attr('id').replace('ticket-', ''));
            });
    
            var ticket_ids = selectedTickets.join(',');
            console.log(ticket_ids);
            
            // SweetAlert2 confirmation dialog
            Swal.fire({
                title: 'Are you sure?',
                text: 'are you sure to send reply?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, send it!',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: '/store/response',
                        method: 'POST',
                        data: {
                            ticket_id: ticket_ids,
                            message: message,
                            _token: '{{ csrf_token() }}'
                        },
                        success: function(response) {
                            
                            // Show success notification
                            Swal.fire(
                                'Updated!',
                                'Reply has been sent successfully.',
                                'success'
                            );
                            // Optionally reload or update the page
                            location.reload();
                        },
                        error: function(xhr) {
                            // Show error notification
                            Swal.fire(
                                'Error!',
                                'An error occurred. Please try again.',
                                'error'
                            );
                        }
                    });
                }
            });
        });
    });
</script>

<!-- Reply to Multiple End -->