<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet">


<div class="box-top-area">
  <div class="box-heading-row d-flex justify-content-between align-items-center">
    <p class="heading color-dark-green">Administrate</p>
    <div class="close-icon d-flex justify-content-center align-items-center"><img class="pointer"
        src="{{ asset('images/icons/Frame.png') }}" alt="Close"></div>
  </div>
  <div class="button-row d-flex justify-content-between  align-items-center">
    <button class="action-btn status-btn @if($ticket->status == 'open') active @endif" data-status="open">Open</button>
    <button class="action-btn status-btn @if($ticket->status == 'waiting') active @endif" data-status="waiting">Waiting</button>
    <button class="action-btn status-btn @if($ticket->status == 'done') active @endif" data-status="done">Done</button>
  </div>
</div>

<div class="box-body-area">
  <ul class="inbox-chat-options">
    <li class="single-option d-flex justify-content-between">
      <p><b>Assign:</b></p>
      <p class="dev-custom-select">
          <select class="aw-select" name="user_assigned">
              <option>(Assign)</option>
              @foreach($companyUsers as $companyUser)
              <option value="{{$companyUser->user_id}}" @if($ticket->user_assigned == $companyUser->user_id) selected @endif>{{$companyUser->user->name}}</option>
              @endforeach
          </select>
          </p>
      <p class="aw-done bg-light-green-color" id="save-ticket" data-ticket_id="{{$ticket->id}}"><i class="fas fa-check"></i></p>
    </li>
    <li class="single-option d-flex justify-content-between">
      <p><b>Priority:</b></span></p>
      
      <p class="dev-custom-select">
          <select class="aw-select" name="priority">
              <option>(Choose Priority)</option>
              <option value="low" @if($ticket->priority == 'low') selected @endif>Low</option>
              <option value="medium" @if($ticket->priority == 'medium') selected @endif>Medium</option>
              <option value="high" @if($ticket->priority == 'high') selected @endif>High</option>
          </select>
          </p>
       <p class="aw-done bg-light-green-color" id="save-priority" data-ticket_id="{{$ticket->id}}"><i class="fas fa-check"></i></p>
      <!--<p><img src="{{ asset('images/icons/Frame (1).png') }}" alt="Chevron Right"></p>-->
    </li>
    <li class="single-option">
      <p>Tags <span>(Choose Tags)</span></p>
      
<!--save user assigned-->
<script>
$(document).ready(function() {
    $('#save-ticket').on('click', function() {
        var userAssigned = $('select[name="user_assigned"]').val();
        var ticketId = $(this).data('ticket_id');

        // Check if a user is selected
        if (userAssigned === '(Assign)') {
            toastr.error("Please select a user to assign.");
            return;
        }

        // AJAX request to save the ticket assignment
        $.ajax({
            url: '/update-ticket/' + ticketId,
            type: 'POST',
            data: {
                user_assigned: userAssigned,
                _token: '{{ csrf_token() }}'
            },
            success: function(response) {
                // Handle the response from the server
                if (response.success) {
                    toastr.success('Ticket Assigned Successfully');
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                // Handle any errors that occurred during the request
                console.error('AJAX Error:', status, error);
                toastr.error("An error occurred while assigning the ticket.");
            }
        });
    });
});
</script>
<!--save priority-->
<script>
$(document).ready(function() {
    $('#save-priority').on('click', function() {
        var priority = $('select[name="priority"]').val();
        var ticketId = $(this).data('ticket_id');

        // Check if a user is selected
        if (priority === '(Choose Priority)') {
            toastr.error("Please select a priority.");
            return;
        }

        // AJAX request to save the ticket assignment
        $.ajax({
            url: '/update-ticket/' + ticketId,
            type: 'POST',
            data: {
                priority: priority,
                _token: '{{ csrf_token() }}'
            },
            success: function(response) {
                // Handle the response from the server
                if (response.success) {
                    toastr.success('Priority Updated Successfully');
                } else {
                    toastr.error('Error: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                // Handle any errors that occurred during the request
                console.error('AJAX Error:', status, error);
                toastr.error('An error occurred while updating the priority.');
            }
        });
    });
});
</script>
<script>
    // Assuming you have a DOM element with the ID 'tags'
    var input = document.getElementById('tags');
    new Tagify(input);
</script>


<?php

$tags = [];
$db_tags = getTicketMeta($ticket->id,'tags',false);

// if($db_tags){

// foreach($db_tags as $tag){
//     $tags[] = $tag->value;
// }

// }
?>

           <input type="text" name="tags" id="tags" value="{{implode(',',$tags)}}" placeholder="Type and press Enter"
              class="form-control input-reply-textarea input-comment-textarea" required/>
              
              
            <button data-ticket_id="{{$ticket->id}}" class="ui button bg-light-green-color mt-4 color-light" id="save-tags">
              Save
            </button>
                
<script>
$(document).ready(function() {
    $('#save-tags').on('click', function(event) {
        event.preventDefault();

        var tags = $('#tags').val();
         var ticketId = $(this).data('ticket_id');

        // Check if the input field is not empty
        if (tags === '') {
            toastr.error('Please enter some tags.');
            return;
        }

        // AJAX request to save the tags
        $.ajax({
            url: '/store-tags',
            type: 'POST',
            data: {
                tags: tags,
                ticket_id:ticketId,
                _token: '{{ csrf_token() }}'
            },
            success: function(response) {
                // Handle the response from the server
                if (response.success) {
                    toastr.success('Tags Added successfully!');
                } else {
                    toastr.error('Error: ' + response.message);
                }
            },
            error: function(xhr, status, error) {
                // Handle any errors that occurred during the request
                console.error('AJAX Error:', status, error);
                toastr.error('An error occurred while saving the tags.');
            }
        });
    });
});

</script>                
      <!--<p><img src="{{ asset('images/icons/+.png') }}" alt="Chevron Right"></p>-->
    </li>
    </form>
    <li class="single-option d-flex justify-content-between">
      <div class="accordion w-100 border-0" id="accordionExample">
        <div class="accordion-item custom-accordion">
          <div data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true"
            aria-controls="collapseOne" class="custom-accordion-item d-flex justify-content-between">
            <p>Comments
              <span>(Write Comments)</span>
            </p>
            <p><img src="{{ asset('images/icons/Frame (1).png') }}" alt="Chevron Right"></p>
          </div>
          <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne"
            data-bs-parent="#accordionExample">
            <div class="accordion-body accordion-body--custom">
              <div class="body-content">
                <textarea rows="7" placeholder="Your Message"
                  class="form-control input-reply-textarea input-comment-textarea" id="add-comment"></textarea>
                <button class="ui button bg-light-green-color mt-4 add-comment-btn color-light">
                  Add Your Comment
                </button>
              </div>
              @foreach($ticket->comments as $comment)
              <div class="response-comment d-flex">
                <div class="response-comment-user-image">
                  <img src="{{ asset('images/Rectangle 4.png') }}" alt="">
                </div>
                <div class="response-content">
                  <div class="top-content-row d-flex justify-content-between align-items-center">
                    <div class="left-area">
                      <p class="response-comment-time">{{ \Carbon\Carbon::parse($comment->created_at)->format('h:i A') }}</p>
                      <p class="response-comment-user-name">{{ $comment->user->name }}</p>
                    </div>
                    <div class="right-area d-flex">
                      <!--<button-->
                      <!--  class="ui button comment--btn bg-dark-green-color color-light comment-edit-btn ">-->
                      <!--  <i class="edit outline icon"></i>-->
                      <!--</button>-->
                      <button
                        class="ui button comment--btn bg-light-green-color color-light comment-delete-btn" data-comment-id="{{ $comment->id }}">
                        <i class="trash alternate outline icon"></i>
                      </button>
                    </div>
                  </div>
                  <p>{{$comment->comment}}</p>
                </div>
              </div>
              @endforeach
            </div>
          </div>
        </div>


      </div>
    </li>
  </ul>
</div>

<style>
    
    .aw-done{
        padding:10px;
        color:white;
        font-size:20px!important;
        cursor:pointer;
    }
    
    .aw-select{
        color: #8d98aa;
    font-family: Poppins;
    font-size: 11px;
    font-weight: 500;
    padding: 13px;
    background: linear-gradient(0deg, #edf2f6 0%, #edf2f6 100%), #fff;
    border: none;
    outline: none;
    border-radius: 6px;
    width: 100%;
    resize: unset;
    }
    
</style>

<!--delete Comment-->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
  $('.comment-delete-btn').on('click', function() {
    var commentId = $(this).data('comment-id');
    var commentElement = $(this).closest('.response-comment');

    // SweetAlert confirmation dialog
    Swal.fire({
      title: 'Are you sure?',
      text: "You won't be able to revert this!",
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: '/delete-comment/' + commentId,
          method: 'GET',
          data: {
            _token: '{{ csrf_token() }}'
          },
          success: function(response) {
            toastr.success("Comment Deleted Successfully");
            commentElement.remove();
          },
          error: function(error) {
            console.error('Error deleting comment:', error);
            Swal.fire(
              'Error!',
              'An error occurred while deleting the comment.',
              'error'
            );
          }
        });
      }
    });
  });
});
</script>

<!--store comment-->
<script>
    $(document).ready(function() {
      $('.add-comment-btn').on('click', function() {
        var ticketId = $('.chat-detail-item.active').data('ticket-id');
        var comment = $('#add-comment').val();
    
        if (comment === '') {
            toastr.error('Comment cannot be empty');
            return;
        }
    
        $.ajax({
          url: '/store-comment',
          method: 'POST',
          data: {
            ticket_id: ticketId,
            comment: comment,
            _token: '{{ csrf_token() }}'
          },
          success: function(response) {
            toastr.success("Comment Added Successfully");
            $('#add-comment').val('');
            $.ajax({
                url: '/fetch-action-box/' + ticketId,
                method: 'GET',
                success: function(response) {
                    $('.action-box').html(response);
                },
                error: function(error) {
                    console.log('Error fetching action box content:', error);
                }
            });
          },
          error: function(error) {
            console.error('Error adding comment:', error);
          }
        });
      });
    });

</script>
<!--change ticket status-->
<script>
  $(document).ready(function() {
    $('.status-btn').on('click', function() {
      var newStatus = $(this).data('status');
      $('.status-btn').removeClass('active');
      $(this).addClass('active');

      updateTicketStatus(newStatus);
    });

    function updateTicketStatus(newStatus) {
      $.ajax({
        url: '/update-ticket-status/{{ $ticket->id }}',
        method: 'POST',
        data: {
          status: newStatus,
          _token: '{{ csrf_token() }}'
        },
        success: function(response) {
          toastr.success(response.message);
        },
        error: function(error) {
          console.error('Error updating ticket status:', error);
        }
      });
    }
  });
</script>