<style type="text/css">
.autocomplete{
        position: relative;
    }
    .autocomplete .searchResult{
        list-style: none;
        padding: 0px;
        width: 78%;
        position: absolute;
        margin: 0;
        margin-top: 40px;
        background: white;
        z-index: 5;
    }

    .autocomplete .searchResult li{
        background: #F2F3F4;
        padding: 10px;
        margin-bottom: 1px;
        white-space: break-spaces;
    }

    .autocomplete .searchResult li:nth-child(even){
        background: #E5E7E9;
        color: black;
    }

    .autocomplete .searchResult li:hover{
        cursor: pointer;
        background: #CACFD2;
    }
</style>
<form class="row g-3 auto-width" action=""  method="post" enctype='multipart/form-data'>
    @csrf
       <div class="col-lg-12 ">
         <label for="search_account" class="consignor_columns"><b>Consignor/Sender</b><span class="text-danger"><b>*</b></span></label>
        <label for="search_account" class=" consignee_columns"><b>Consignee/Receiver</b><span class="text-danger"><b>*</b></span></label>
        <label for="search_account" class=" vendor_columns"><b>Third Party (Booking Source)</b></label>
         <div class="input-group autocomplete" >
                 <input type="text" name=" "  id="account_id"  class="account-select form-control " placeholder="Search Account" value="{{ $accounts->name  ?? ''}}">
              <ul class="searchResult" ></ul>
              <input type="hidden" name="accounts_id" value="{{$accounts->id}}">
              <input type="hidden" name="type" id ="type" value="{{$type}}">
              <input type="hidden" name="booking_id" id ="booking_id" value="{{$booking_id}}">
     
             <button class="btn btn-secondary " id="create_account" type="button"> + </button>   
         </div> 
         <span class="text-danger error_consignors_id" style="display: none;">This field is required.</span>
     </div>
</form>
  <script type="text/javascript">


    function isNumber(value) 
    {
    return typeof value === 'number';
    }

    function reinitializeTelInput(countryCode) {
        var telInput = $('#commonModal').find('#phone_no , #whatsapp_no , #alternative_no');
        telInput.intlTelInput('destroy'); // Destroy the existing instances

        telInput.intlTelInput({
            utilsScript: "https://cdn.jsdelivr.net/npm/intl-tel-input@18.2.1/build/js/utils.js",
            initialCountry: countryCode || '{!! $countryCode ?? '' !!}',
            separateDialCode: true
        });
    }

 // creating accounts

    $(document).on('click', '#create_account', function(){
        $('#commonModalLabel').text('Add New Account');
        $('.save_button_span').text('Save Account');
        $('.save_button').addClass('save-account');
        $('.save_button').removeClass('save-consignor');
        var type = $('#type').val();
        var booking_id = $('#booking_id').val();
        var account_type_id = $('.account_types_id').val();
        var accounting_group_id = $('.accounting_group_id').val();
        $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
               }
               });
            $.ajax({
                type: 'POST',
                url:"{!! route('booking.createaccount') !!}",
                data: {
                    type       : type,
                    booking_id       : booking_id,
                },
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            if (type == 'consignor'){
                        $(".vendor_columns").remove();
                        $(".consignee_columns").remove();
                        $(".lc_issued_by_columns").remove();
                        $(".cfs_agent_columns").remove();
                        $(".broker_columns").remove();
                     }
               else if(type == 'consignee'){
                  $(".vendor_columns").remove();
                        $(".consignor_columns").remove();
                        $(".lc_issued_by_columns").remove();
                        $(".cfs_agent_columns").remove();
                        $(".broker_columns").remove();
               }
               else if(type == 'vendor'){
                  $(".consignor_columns").remove();
                        $(".consignee_columns").remove();
                        $(".lc_issued_by_columns").remove();
                        $(".cfs_agent_columns").remove();
                        $(".broker_columns").remove();
               }
            $('#quality_form').append('<input type="hidden" name="accounting_group_id" value="'+accounting_group_id+'">')
            $('#quality_form').append('<input type="hidden" name="account_type_id" value="'+account_type_id+'">')
             reinitializeTelInput();
          }
        })
    })
    $(document).on('click', '.save-account', function(event){
   event.preventDefault();
     if ($('#phone_no').val().trim() != '') {
        var dailcode_title = $('.phone_no_col .selected-flag').attr('title');
        var dailcode_array = dailcode_title.split("+");
        $('input[name="phone_no"]').val("+" + dailcode_array[1] + $('#phone_no').val());
    }

    if ($('#whatsapp_no').val().trim() != '') {
        var dailcode_title = $('.whatsapp_no_col .selected-flag').attr('title');
        var dailcode_array = dailcode_title.split("+");
        $('input[name="whatsapp_no"]').val("+" + dailcode_array[1] + $('#whatsapp_no').val());
    }

  $('.error_name').hide();
  var error = 0;

  if ($('#commonModal').find('form').find('input[name="name"]').val().trim() == '') {
  $('.error_name').show();
  error = 1;
  setTimeout(function () {
  $('.error_name').hide();
  }, 3000);
  } 

  if ($('#commonModal').find('form').find('#phone_no').val().trim() == '') {
  $('.error_phone_no').show();
  error = 1;
  }

   if (error == 0) {
          let formdata = new FormData($('#commonModal').find('form')[0]);
        
          $.ajax({
              url: $('#commonModal').find('form').attr('action'),
              data: formdata,
              processData: false,
              contentType: false,
              type: 'POST',
              success: function (response) {
                  if (response.success === true) {
                      toastr.success(response.message, 'Success.');
                      $('[name="accounts_id"]').val(response.data.id);
                      $('#account_id').val(response.data.name);
                      $('.consignor').hide();
                      $('#edit_consignor').prop('disabled', false);
                      $('.save_button').removeClass('save-account');
                      // hide modal
                      $('#commonModal').modal('hide');
                      $('#commonModal').find('.modal-body').html('');
                  } else {
                      toastr.error(response.message, 'Error!');
                  }
              }
          })

.fail(function(jqXHR, textStatus, errorThrown) {
  console.log('AJAX request failed:', textStatus, errorThrown);
  toastr.error('An error occurred during the request.', 'Error!');

  // hide modal
  // $('#commonModal').modal('hide');
  // $('#commonModal').find('.modal-body').html('');
  
});
}

error = 1;
})
  </script>
