@extends('layouts.app')
@section('title','Booking')
@section('pages')

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/css/intlTelInput.css">
<link rel="stylesheet" type="text/css" href="{{ asset('admin/plugins/datepicker/less/datepicker.less') }}">
<link href="{{ asset('admin/plugins/datepicker/css/datepicker.css') }}" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<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 id="create_form" name="create_form" class="create_form">
    @csrf
    <div class="card m-1">
        <div class="card-body">
            <div class="row ">

                <div class="col-lg-4 ">
                    <label for="search_cosignor"><b>Consignor/Sender</b><span class="text-danger"><b>*</b></span></label>
                    <div class="input-group autocomplete" >
                            <input type="text" name=" "  id="consignor_id"  class="consignor-select form-control " placeholder="Search Consignor" value="{{ $consignor->name  ?? ''}}">
                         <ul class="searchResult" ></ul>
                         <input type="hidden" name="consignors_id" value="$booking->consignor_id">
                        <button class="btn btn-secondary add_btn" id="create_consignor" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                        <button class="btn btn-sm btn-primary "style="margin-left: 4px ;width:45px" type="button"  id="edit_consignor" data-bs-toggle="modal" data-bs-target="#commonModal"  ><i class="bi bi-pencil-square"></i>
                        </button>      
                    </div> 
                    <span class="text-danger error_consignors_id" style="display: none;">This field is required.</span>
                </div>
                <div class="col-lg-4 ">
                    <label for="search_consignee"><b>Consignee/Receiver</b><span class="text-danger"><b>*</b></span></label>
                    <div class="input-group autocomplete">
                        <input type="text" name="" id="consignee_id"  class="consignee-select form-control " placeholder="Search Consignee"value="{{$consignee->name ?? ''}}">
                        <ul class="searchResult"></ul>
                        <input type="hidden" name="consignees_id" value="$booking->consignee_id">
                        <button class="btn btn-secondary add_btn" id="create_consignee" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + 
                        </button>
                        <button class="btn btn-sm btn-primary "style="margin-left: 4px ;width:45px"  id="edit_consignee" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"><i class="bi bi-pencil-square"></i>
                        </button>
                    </div>
                    <span class="text-danger error_consignees_id" style="display: none;">This field is required.</span>
                </div>
                <div class="col-lg-4 ">
                    <label for="search_vendor"><b>Third Party (Booking Source)</b></label>
                    <div class="input-group autocomplete">
                        <input type="text" name=" "  id="vendor_id"  class="vendor-select form-control " placeholder="Search Third Party" value="{{ $vendor->name  ?? ' '}}">
                        <ul class="searchResult"></ul>
                        <input type="hidden" name="vendors_id" value="$booking->vendor_id">
                        <button class="btn btn-secondary add_btn" id="create_vendor" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + 
                        </button>
                        <button class="btn btn-sm btn-primary "style="margin-left: 4px ;width:45px" type="button" id="edit_vendor" type="button"  data-bs-toggle="modal" data-bs-target="#commonModal"><i class="bi bi-pencil-square"></i>
                        </button>
                    </div>          
                </div>
            </div>
        </div>
    </div>
    <input type="hidden" class="account_types_id" id="account_types_id" value="{{ $account_types->id }}">
    <input type="hidden" class="accounting_group_id" id="accounting_group_id" value="{{ $accounting_groups->id }}">  
    <div class="card m-1">
        <div class="card-body">
            <div class="row">
                <div class="col-md-3  mb-1">
                    <label for="voucher_type">Voucher Type<span class="text-danger"><b>*</b></span></label>
                     <select name="voucher_type" id="voucher_type" class="form-control ">
                        <option value="">~Select~</option>
                        @foreach($voucher_types as $voucher)
                        <option value="{{ $voucher->voucher_id }}" {{ $booking->voucher_type_id == $voucher->voucher_id ? 'selected' : '' }}>{{ $voucher->code }}</option>
                        @endforeach                                   
                    </select>
                    <span class="text-danger error_voucher_type" style="display: none;">This field is required.</span>
                </div>
                <div class="col-md-3  mb-1">
                    <label for="transportation_id" class="control-label">Transportation Mode<span class="text-danger"><b>*</b></span></label>
                    <select name="transportation_id" id="transportation_id" class="form-control ">
                        @foreach($transportations as $transportation)
                        <option value="{{ $transportation->id}}"{{ $booking->transportation_mode_id == $transportation->id ? 'selected' : '' }}>{{ $transportation->code }}</option>
                        @endforeach
                    </select>
                    <span class="text-danger error_transportation_id" style="display: none;">This field is required.</span>
                </div>
                <div class="col-md-3 mb-1">
                    <input type="hidden" name="consignorcountry_id" id="consignorcountry_id" value="">
                    <label for=""><b>From Location</b><span class="text-danger"><b>*</b></span></label>
                    <div class="input-group autocomplete">
                        <input type="text" name="" id="from_id"class="consignor-city-select form-control " placeholder="Search City" value="{{$from_location_id->name ?? ''}}">
                        <ul class="searchResult"></ul>
                        <input type="hidden" name="from_id" value="{!! $booking->from_location_id ?? '' !!}">
                        <div class="input-group-append" style="margin: auto 10px auto 0;">
                        <button class="btn btn-secondary add_btn" id="create_city" type="button" data-bs-toggle="modal" data-bs-target="#commonModal">+</button>
                        </div>
                    </div>  
                    <span class="text-danger error_from_id" style="display:none;">This field is required.</span>
                </div>
                <div class="col-md-3 mb-1">
                     <input type="hidden" name="consigneecountry_id" id="consigneecountry_id" value="">
                    <label for=""><b>To Location</b><span class="text-danger"><b>*</b></span></label>
                    <div class="input-group autocomplete">
                        <input type="text" name="" id="to_id" class="consignee-city-select  form-control " placeholder="Search City" value="{{$to_location_id->name ?? ''}}">
                        <ul class="searchResult"></ul>
                        <input type="hidden" name="to_id" value="{!! $booking->to_location_id ?? '' !!}">
                        <div class="input-group-append" style="margin: auto 10px auto 0;">
                            <button class="btn btn-secondary add_btn" id="create_city" type="button" data-bs-toggle="modal" data-bs-target="#commonModal">+</button>
                        </div> 
                    </div>  
                    <span class="text-danger error_to_id" style="display:none;">This field is required.</span>
                </div>
                <div class="col-md-3  mb-1">
                    <label for=""> Bill To Party <span class="text-danger"><span class="text-danger"><b>*</b></span></label>
                    <select name="bill_to_party" id="bill_to_party" class="form-control">
                        <option value="">~Select~</option>
                    </select>
                    <span class="text-danger error_bill_to_party" style="display: none;">This field is required.</span>
                </div>
                <div class="col-md-3  mb-1">
                    <label for="">Tax Paid By<span class="text-danger"><b>*</b></span></label>
                    <select name="taxpaidby" id="taxpaidby" class="taxpaidby  form-control">
                        <option value="">~Select~</option>
                        @foreach($taxpaidby as $taxpaidby)
                        <option value="{{ $taxpaidby->id }}" {{ $booking->tax_paid_by_id == $taxpaidby->id ? 'selected' : '' }}>{{ $taxpaidby->code }}</option>
                        @endforeach
                    </select>
                    <span class="text-danger error_taxpaidby" style="display: none;">This field is required.</span>
                </div>
                <div class=" col-md-3 mb-1">
                    <label for="delivery_type" class="control-label ">Delivery Type<span class="text-danger"><b>*</b></span></label>
                    <select class="form-control" id ="delivery_type" name="delivery_type">
                    <option value="">~Select~</option>
                       @foreach($deliveries as $delivery)
                       <option value="{{$delivery->id}}" {{ $booking->delivery_type_id == $delivery->id ? 'selected' : '' }}>{{$delivery->name}}</option>
                       @endforeach
                   </select>
                   <span class="text-danger error_delivery_type" style="display: none;">This field is required.</span>
                </div>
                <div class="col-md-3 mb-1">
                    <label for="shipping_risk" class="control-label ">Shipping Risk<span class="text-danger"><b>*</b></span></label>
                    <select class="form-control" id ="shipping_risk" name="shipping_risk">
                       @foreach($risks as $risk)
                       <option value="{{$risk->id}}" {{ $booking->shipping_risk == $risk->id ? 'selected' : '' }}>{{$risk->name}}</option>
                       @endforeach
                   </select>
                   <span class="text-danger error_shipping_risk" style="display: none;">This field is required.</span>
                </div>
                <div class="col-md-3 mb-1">
                    <label for="transport_type" class="control-label ">Transport Type<span class="text-danger"><b>*</b></span></label>
                    <select class="form-control" id ="transport_type" name="transport_type">
                        <option value="">~Select~</option>
                       @foreach($transports as $transport)
                       <option value="{{$transport->id}}" {{ $booking->transport_type_id == $transport->id ? 'selected' : '' }}>{{$transport->name}}</option>
                       @endforeach
                   </select>
                   <span class="text-danger error_transport" style="display: none;">This field is required.</span>
                </div>
            </div>
        </div>
    </div>
            </div>
        </div>
    </div>
    <div class="card-footer bg-white text-center col-md-12 m-1">
        <button class="btn btn-success  new_bookings">Save Booking</button>
    </div>

</form>
@endsection

@section('js')
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js') }}"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>

    function delay(callback, ms) {
        var timer = 0;
        return function() {
            var context = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function() {
                callback.apply(context, args);
            }, ms || 0);
        };
    }

    /**************** Create City ********************/
    $(document).on('click', '#create_city', function() {
    $('#commonModalLabel').text('Add New City');
    $('.save_button_span').text('Save City');
    $.ajax({
        url: "{!! route('cities.create') !!}",
        success: function(data) {
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
        }
    })
    })


   // search Consignor City

$(document).ready(function(){
  $('.consignor-city-select').autocomplete
   ({    
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="from_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ url('companies/getcityConsignor') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term,
                        country_id:$('#consignorcountry_id').val(),
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="from_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                                address: item.address,
                                country_id:item.country_id,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();
                $(this).val(ui.item.name +  "");
                $('[name="from_id"]').val(ui.item.id);
                $('#to_id').focus();
                return false;
                
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item)
         {
            return $("<li>")
                .append("<a>" + item.name +   "</a>")
                .appendTo(ul);
        };
  const citySelect = document.querySelector(".consignor-city-select");
  const querySelector = document.querySelector(".searchResult");
  document.addEventListener("click", (event) =>
   {
  if (event.target !== citySelect && event.target !== querySelector) {
  $(".searchResult").empty();
  }
  }); 
})

   // search Consignee City

$(document).ready(function(){
  $('.consignee-city-select').autocomplete
   ({  
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="to_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ url('companies/getcityConsignor') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term,
                        country_id:$('#consigneecountry_id').val(),
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="to_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                                address: item.address,
                                country_id:item.country_id,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();;
                $(this).val(ui.item.name +  "");
                $('[name="to_id"]').val(ui.item.id);
                 $('#bill_to_party').focus();
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item)
         {
            return $("<li>")
                .append("<a>" + item.name +   "</a>")
                .appendTo(ul);
        };
  const citySelect = document.querySelector(".consignee-city-select");
  const querySelector = document.querySelector(".searchResult");
  document.addEventListener("click", (event) =>
   {
  if (event.target !== citySelect && event.target !== querySelector) {
  $(".searchResult").empty();
  }
  }); 
})

   // search consignor

$(document).ready(function(){
  $('.consignor-select').autocomplete
  ({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="consignors_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('customer-account-search') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="consignors_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                                address: item.address,
                                country_id:item.country_id
                                
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();
                var country_id = ui.item.country_id ;
                $("#consignorcountry_id").val(country_id);
                

                $(this).val(ui.item.name  + "");
                $('[name="consignors_id"]').val(ui.item.id);
                $('#pickup_address').val(ui.item.address)
                $('.consignor').hide();
                $('#bill_to_party').append('<option class ="consignor" value='+ui.item.id+'  > '+ ui.item.name + ' (consignor)</option>');
                $('#consignee_id').focus();
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item)
         {
            return $("<li>")
                .append("<a>" + item.name +   "</a>")
                .appendTo(ul);
        };

  const customerSelect = document.querySelector(".consignor-select");

  const querySelector = document.querySelector(".searchResult");

  document.addEventListener("click", (event) => 
  {
  if (event.target !== customerSelect && event.target !== querySelector) {
  $(".searchResult").empty();
  }
  }); 
})
   
   // search Consignee

$(document).ready(function(){
  $('.consignee-select').autocomplete
  ({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="consignees_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('customer-account-search') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="consignees_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                                address: item.address,
                                country_id:item.country_id,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();;
                var country_id = ui.item.country_id ;
                $("#consigneecountry_id").val(country_id);
                // getcityconsignee();

                $(this).val(ui.item.name +  "");
                $('[name="consignees_id"]').val(ui.item.id);
                $('#bill_to_address').val(ui.item.address);
                $('#ship_to_address').val(ui.item.address)
                $('.consignee').hide();
                $('#bill_to_party').append('<option class ="consignee"  value='+ui.item.id+' > '+ ui.item.name + ' (consignee)</option>');
                $('#vendor_id').focus();
                

                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) 
        {
            return $("<li>")
                .append("<a>" + item.name +"</a>")
                .appendTo(ul);
        };

 const customerSelect = document.querySelector(".consignor-select");

  const querySelector = document.querySelector(".searchResult");
  document.addEventListener("click", (event) =>
   {
  if (event.target !== customerSelect && event.target !== querySelector) {
  $(".searchResult").empty();
  }
  }); 
})

  // search Vendor
$(document).ready(function(){
        $('.vendor-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="vendors_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('customer-account-search') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search_text: request.term
                    },
                    success: function(json) {
                        if (json.error) {
                            $('[name="vendors_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();

                $(this).val(ui.item.name + "");
                $('[name="vendors_id"]').val(ui.item.id);
                $('.vendor').hide();
                $('#bill_to_party').append('<option class ="vendor" value='+ui.item.id+' > '+ ui.item.name + ' (vendor)</option>');
                $('#voucher_type').focus();
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item)
         {

            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };

  const customerSelect = document.querySelector(".consignor-select");

  const querySelector = document.querySelector(".searchResult");


  document.addEventListener("click", (event) => 
  {
  if (event.target !== customerSelect && event.target !== querySelector) {
  $(".searchResult").empty();
  }
  }); 
})

    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_consignor', function(){
        $('#commonModalLabel').text('Add New Consignor');
        $('.save_button_span').text('Save Consignor');
        $('.save_button').addClass('save-consignor');
        var account_type_id = $('.account_types_id').val();
        var accounting_group_id = $('.accounting_group_id').val();
        $.ajax({
          url:"{!! route('booking.createconsignor') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $(".vendor_columns").remove();
            $(".consignee_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', '#create_consignee', function(){
        $('#commonModalLabel').text('Add New Consignee');
        $('.save_button_span').text('Save Consignee');
        $('.save_button').addClass('save-consignee');
        var account_type_id = $('.account_types_id').val();
        var accounting_group_id = $('.accounting_group_id').val();
        $.ajax({
          url:"{!! route('booking.createconsignor') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $(".vendor_columns").remove();
            $(".consignor_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', '#create_vendor', function(){
        $('#commonModalLabel').text('Add New Vendor');
        $('.save_button_span').text('Save Vendor');
        $('.save_button').addClass('save-vendor');
         var account_type_id = $('.account_types_id').val();
        var accounting_group_id = $('.accounting_group_id').val();
        $.ajax({
          url:"{!! route('booking.createconsignor') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);

            $(".consignor_columns").remove();
            $(".consignee_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();
          }
        })
    })


    // editing accounts

    $(document).on('click', '#edit_consignor', function() {
        $('.save_button').addClass('save-consignor');
        var customerName = $('[name="consignors_id"]').val();
        if (customerName.trim() === "") {
            $('.error_patient_id').show();
        } else {
            $('.error_patient_id').hide();

            $('#commonModalLabel').text('Edit Consignor');
            $('.save_button_span').text('Update Consignor');
            var id = $('[name="consignors_id"]').val();
            var url = `{!! route('booking.editconsignor', ':id') !!}`.replace(':id', id);
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                    $(".vendor_columns").remove();
                    $(".consignee_columns").remove();
                    reinitializeTelInput();  
                }
            });
        }
    });

    $(document).on('click', '#edit_consignee', function() {
        $('.save_button').addClass('save-consignee');
        var customerName = $('[name="consignees_id"]').val();
        if (customerName.trim() === "") {
            $('.error_patient_id').show();
        } else {
            $('.error_patient_id').hide();

            $('#commonModalLabel').text('Edit Consignee');
            $('.save_button_span').text('Update Consignee');
            var id = $('[name="consignees_id"]').val();
            var url = `{!! route('booking.editconsignor', ':id') !!}`.replace(':id', id);
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                    $(".vendor_columns").remove();
                    $(".consignor_columns").remove();
                    reinitializeTelInput();
                }
            });
        }
    });

    $(document).on('click', '#edit_vendor', function() {
        $('.save_button').addClass('save-vendor');
        var customerName = $('[name="vendors_id"]').val();
        if (customerName.trim() === "") {
            $('.error_patient_id').show();
        } else {
            $('.error_patient_id').hide();

            $('#commonModalLabel').text('Edit Vendor');
            $('.save_button_span').text('Update Vendor');
            var id = $('[name="vendors_id"]').val();
            var url = `{!! route('booking.editconsignor', ':id') !!}`.replace(':id', id);
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                    $(".consignor_columns").remove();
                    $(".consignee_columns").remove();
                    reinitializeTelInput();
                }
            });
        }
    });
  // ************* Save Consignor ************/

$(document).on('click', '.save-consignor', 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 (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="consignors_id"]').val(response.data.id);
                      $('#consignor_id').val(response.data.name);
                      $('#pickup_address').val(response.data.address);
                      $('.consignor').hide();
                      $('#bill_to_party').append('<option class ="consignor"  value='+response.data.id+' > '+ response.data.name + ' (consignor)</option>');
                      $('#consignorcountry_id').val(response.data.country_id);
                      $('#voucher').focus();
                      $('#edit_consignor').prop('disabled', false);
                      $('.save_button').removeClass('save-consignor');
                      // 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;
})

 /******* save Consignee   ************/

$(document).on('click', '.save-consignee', 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 (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="consignee_id"]').val(response.data.id);
                      $('#consignee_id').val(response.data.name);
                      $('#bill_to_address').val(response.data.address);
                      $('.consignee').hide();
                      $('#bill_to_party').append('<option class ="consignee"  value='+response.data.id+' > '+ response.data.name + ' (consignee)</option>');
                      $('#consigneecountry_id').val(response.data.country_id);
                      $('#vendor_id').focus();
                      $('#edit_consignee').prop('disabled', false);
                      $('.save_button').removeClass('save-consignee');
                      
                      // 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;
})

 //*************** save vendor ************/

$(document).on('click', '.save-vendor', 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 (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="vendors_id"]').val(response.data.id);
                      $('#vendor_id').val(response.data.name);
                      $('.vendor').hide();
                      $('#bill_to_party').append('<option class ="vendor"  value='+response.data.id+'  > '+ response.data.name + ' (vendor)</option>');
                      $('#voucher_type').focus();
                      $('#edit_vendor').prop('disabled', false);
                      $('.save_button').removeClass('save-consignor');
                      // 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;
})


 /******* Disabling & Enabling edit button of Consignor ************/
    $(document).ready(function() {
        function toggleEditButton() {
            var patientId = $('[name="consignors_id"]').val();
            $('#edit_consignor').prop('disabled', patientId.trim() === "");
        }

        toggleEditButton();

        $('#consignor_id').on('input', function() {
            toggleEditButton();
        });

        $('#consignor_id').on('change', function() {
            toggleEditButton();
        });

        $('#edit_consignor').on('click', function() {
            var patientName = $('#consignor_id').val().trim();

            if (patientName === "") {
                $('.error_patient_id').show();
            } else {
                $('.error_patient_id').hide();

                $('#commonModalLabel').text('Edit Consignor');
                $('.save_button_span').text('Update Consignor');
                var id = $('[name="consignors_id"]').val();
                var url = `{!! route('patient-account-edit', ':id') !!}`.replace(':id', id);

                $.ajax({
                    url: url,
                    success: function(data) {
                        $('#commonModal').find('.modal-body').html('');
                        $('#commonModal').find('.modal-body').html(data);
                    }
                });
            }
        });

        function enableEditButton() {
            $('#edit_consignor').prop('disabled', false);
        }

        function addValueToPatientId(newValue) {
            $('[name="consignors_id"]').val(newValue);
            enableEditButton();
        }
    });


 /******* Disabling & Enabling edit button of Consignee ************/
    $(document).ready(function() {
        function toggleEditButton() {
            var patientId = $('[name="consignees_id"]').val();
            $('#edit_consignee').prop('disabled', patientId.trim() === "");
        }

        toggleEditButton();

        $('#consignee_id').on('input', function() {
            toggleEditButton();
        });

        $('#consignee_id').on('change', function() {
            toggleEditButton();
        });

        $('#edit_consignee').on('click', function() {
            var patientName = $('#consignee_id').val().trim();

            if (patientName === "") {
                $('.error_patient_id').show();
            } else {
                $('.error_patient_id').hide();

                $('#commonModalLabel').text('Edit Consignee');
                $('.save_button_span').text('Update Consignee');
                var id = $('[name="consignees_id"]').val();
                var url = `{!! route('patient-account-edit', ':id') !!}`.replace(':id', id);

                $.ajax({
                    url: url,
                    success: function(data) {
                        $('#commonModal').find('.modal-body').html('');
                        $('#commonModal').find('.modal-body').html(data);
                    }
                });
            }
        });

        function enableEditButton() {
            $('#edit_consignee').prop('disabled', false);
        }

        function addValueToPatientId(newValue) {
            $('[name="consignees_id"]').val(newValue);
            enableEditButton();
        }
    });
 /******* Disabling & Enabling edit button of Vendor ************/
    $(document).ready(function() {
        function toggleEditButton() {
            var patientId = $('[name="vendors_id"]').val();
            $('#edit_vendor').prop('disabled', patientId.trim() === "");
        }

        toggleEditButton();

        $('#vendor_id').on('input', function() {
            toggleEditButton();
        });

        $('#vendor_id').on('change', function() {
            toggleEditButton();
        });

        $('#edit_vendor').on('click', function() {
            var patientName = $('#vendor_id').val().trim();

            if (patientName === "") {
                $('.error_patient_id').show();
            } else {
                $('.error_patient_id').hide();

                $('#commonModalLabel').text('Edit Vendor');
                $('.save_button_span').text('Update Vendor');
                var id = $('[name="vendors_id"]').val();
                var url = `{!! route('patient-account-edit', ':id') !!}`.replace(':id', id);

                $.ajax({
                    url: url,
                    success: function(data) {
                        $('#commonModal').find('.modal-body').html('');
                        $('#commonModal').find('.modal-body').html(data);
                    }
                });
            }
        });

        function enableEditButton() {
            $('#edit_vendor').prop('disabled', false);
        }

        function addValueToPatientId(newValue) {
            $('[name="vendors_id"]').val(newValue);
            enableEditButton();
        }
    });
   

</script>
@endsection
