@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="">
                         <ul class="searchResult" ></ul>
                         <input type="hidden" name="consignors_id" value="">
                        <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 ="">
                        <ul class="searchResult"></ul>
                        <input type="hidden" name="consignees_id" value="">
                        <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="">
                        <ul class="searchResult"></ul>
                        <input type="hidden" name="vendors_id" value="">
                        <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</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 }}">{{ $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}}">{{ $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="" class="consignor-city-select form-control " placeholder="Search City" value="">
                        <ul class="searchResult"></ul> -->
                        <input type="hidden" name="from_id" id="from_id"  value="">
<!--                         <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="" class="consignee-city-select  form-control " placeholder="Search City" value="">
                        <ul class="searchResult"></ul> -->
                        <input type="hidden" name="to_id"   id="to_id"  value="">
<!--                         <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 }}">{{ $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}}">{{$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}}">{{$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}}">{{$transport->name}}</option>
                       @endforeach
                   </select>
                   <span class="text-danger error_transport" style="display: none;">This field is required.</span>
                </div>
            </div>
        </div>
    </div>
   <div class="col-12 justify-content-center  mb-1" >
        <div style="" class="accordion-item mx-1">
            <h2 class="accordion-header" id="panelsStayOpen4-headingTwo">
            <button class="accordion-button collapsed px-3" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen3-collapseTwo" aria-expanded="false" aria-controls="panelsStayOpen3-collapseTwo">
            Address Details
            </button>
            </h2>
            <div style="" id="panelsStayOpen3-collapseTwo" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen3-headingTwo">
                <div class="accordion-body p-0 m-0">
                    <div class="card p-0 m-1">
                        <div class="card-body p-2">
                            <div class="row ">
                                <div class="col-lg-4 ">
                                    <label for=""><b>Dispatch/Pickup Address</b></label>
                                    <div class="input-group autocomplete" >
                                        <input type="text" name="pickup_address" id="pickup_address" class=" form-control " placeholder="Search Dispatch From" value="">              
                                        <button class="btn btn-secondary add_btn" id="" type="button" > + </button>
                                        <button class="btn btn-sm btn-primary " disabled style="margin-left: 4px ;width:45px" type="button"  id=""  ><i class="bi bi-pencil-square"></i></button>
                                    </div> 

                                </div>
                                <div class="col-lg-4 ">
                                    <label for=""><b>Bill To Address</b><span class="text-danger"><b>*</b></span></label>
                                    <div class="input-group autocomplete">
                                        <input type="text" name="bill_to_address" id="bill_to_address" class="form-control " placeholder="Search Bill To Address" value="">
                                        <button class="btn btn-secondary add_btn" id="" type="button" > + </button>
                                        <button class="btn btn-sm btn-primary " disabled 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_bill_to_address" style="display: none;">This field is required.</span>
                                </div>
                                <div class="col-lg-4 ">
                                    <label for=""><b>Ship To/Delivery Address</b><span class="text-danger"><b>*</b></span></label>
                                    <div class="input-group autocomplete">
                                        <input type="text" name="ship_to_address" id="ship_to_address"class="form-control " placeholder="Search Ship Address" value="">
                                       <button class="btn btn-secondary add_btn" id="" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                      <button class="btn btn-sm btn-primary " disabled style="margin-left: 4px ;width:45px" type="button" id="" type="button"><i class="bi bi-pencil-square"></i></button>
                                    </div>
                                    <span class="text-danger error_ship_to_address" style="display: none;">This field is required.</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-12 justify-content-center mb-1">
        <div style="" class="accordion-item mx-1">
            <h2 class="accordion-header" id="panelsStayOpen4-headingTwo">
            <button class="accordion-button collapsed p-2" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen4-collapseTwo" aria-expanded="false" aria-controls="panelsStayOpen4-collapseTwo">
                Container/Export/Import Details
            </button>
            </h2>
            <div style="" id="panelsStayOpen4-collapseTwo" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo">
                <div class="accordion-body p-0 m-0">
                    <div class="card m-0">
                        <div class="card-body p-1">
                            <div class="row">
                                <div class="col-md-3  mb-1">
                                    <label  for=""> Container No</label>
                                    <div class="input-group">
                                    <input id="container_no" class="form-control " type="number" name="container_no" placeholder=" Enter Container Number" >
                                    </div>
                                </div>
                                <div class="col-md-3  mb-1">
                                    <label  for="">Seal Number</label>
                                    <div class="input-group">
                                    <input id="seal_number" class="form-control " type="number" name="seal_number" placeholder=" Enter Seal Number" >
                                    </div>
                                </div>
                                <div class="col-md-3  mb-1" >
                                    <label  for="">Container DO Number</label>
                                    <div class="input-group">
                                    <input id="do_number" class="form-control " type="number" name="do_number" placeholder=" Enter DO Number" >
                                    </div>
                                </div>
                                 <div class="col-md-3  mb-1">
                                    <label  for="">DO Validity date</label>
                                    <div class="input-group">
                                    <input id="do_validity_date" class="form-control " type="text" name="do_validity_date" placeholder=" Enter DO Validity date" >
                                    </div>
                                </div>
                               <div class="col-md-2  mb-1" >
                                    <label  for="">Container Return Expiry Date</label>
                                    <div class="input-group">
                                    <input id="container_return_expiry_date" class="form-control " type="text" name="container_return_expiry_date" placeholder=" Enter Container Return Expiry Date" >
                                    </div>
                                </div>
                                <div class="col-md-2  mb-1">
                                    <label  for="">LC Number</label>
                                    <div class="input-group">
                                    <input id="lc_number" class="form-control " type="number" name="lc_number" placeholder=" Enter LC Number" >
                                    </div>
                                </div>
                                
                                <div class="col-md-3  mb-1" >
                                    <label for="search_lc_issued_by"><b>LC Issued By</b><span class="text-danger"><b>*</b></span></label>
                                            <div class="input-group autocomplete" >
                                                 <input type="text" name="" id="lc_issued_by_id" class="lc_issued_by-select form-control " placeholder="Search LC Issued By" value="">
                                                 <ul class="searchResult" ></ul>
                                                 <input type="hidden" name="lc_issued_by_id" value="">
                                                <button class="btn btn-secondary add_btn" id="create_lc_issued_by" 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_lc_issued_by" data-bs-toggle="modal" data-bs-target="#commonModal"  ><i class="bi bi-pencil-square"></i>
                                                </button>      
                                            </div>
                                </div>
                                <div class="col-md-2  mb-1">
                                    <label  for="">LC Date</label>
                                    <div class="input-group">
                                    <input id="lc_date" class="form-control " type="text" name="lc_date" placeholder=" Enter LC Date" >
                                    </div>
                                </div>
                                 <div class="col-md-3 mb-1">
                                    <label for="search_cfs_agent_id"><b>CFS Agent</b><span class="text-danger"><b>*</b></span></label>
                                        <div class="input-group autocomplete" >
                                             <input type="text" name="" id="cfs_agent_id" class="cfs_agent-select form-control " placeholder="Search CFS Agent" value="">
                                             <ul class="searchResult" ></ul>
                                             <input type="hidden" name="cfs_agent_id" value="">
                                            <button class="btn btn-secondary add_btn" id="create_cfs_agent" 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_cfs_agent" data-bs-toggle="modal" data-bs-target="#commonModal"  ><i class="bi bi-pencil-square"></i>
                                            </button>      
                                        </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
     </div>
     
    <div class="row gx-0 p-3 m-1" style="background-color: white;">
        <h5>Item/Material Details</h5>
        <div class="col-lg-3 ">
            <label for="Item Details" class="form-label">Item Name  <span class="text-danger"><b>*</b></label>
            <div class="input-group" >
                <input type="text" name="" id="search_product" class="search_product form-control" placeholder="Search Item Name ">
                <ul class="searchResult" style="width: 100%;"></ul>
                <input type="hidden" name="search_product" value="">
                <span class="text-danger error_product_id" style="display:none;">This field is required.</span>
            </div>
        </div>
         <div class="col-md-2">
            <label for="rate_calculation_type" class="form-label">Rate Calculation Type<span class="text-danger"><b>*</b></span></label>
            <div class="input-group">
                <select name="rate_calculation_type" id="rate_calculation_type" class="form-control">
                    @foreach($rate_calculations as $calculation)
                    <option value="{{$calculation->id}}">{{$calculation->name}}</option>
                    @endforeach
              </select>
            </div>
        </div>
        <div class="col-md-1">
            <label for="item_qty" class="form-label">Item QTY <span class="text-danger"><b>*</b></label>
            <div class="input-group">
                <input type="number" name="item_qty" id="item_qty" class="form-control br-0" value="1" placeholder="Enter Item Qty">
                <span class="text-danger error_item_qty" style="display:none;">This field is required.</span>
            </div>
        </div>
        <div class="col-md-1">
            <label for="actual_weight" class="form-label">Actual Weight </label>
            <div class="input-group">
                <input type="number" name="actual_weight" id="actual_weight"  class="form-control br-0" value="" placeholder="Actual Weight ">
            </div>
        </div>
        <div class="col-md-1  gross_column" >
            <label for="gross_weight" class="form-label">Gross Weight<span class="text-danger"><b>*</b></span></label>
            <div class="input-group">
                <input type="number" name="gross_weight" id="gross_weight"  class="form-control br-0" value="" placeholder="Gross Weight">
            </div>
        </div>
        <div class="col-md-1">
            <label for="weight_type" class="form-label">Weight type<span class="text-danger"><b>*</b></span></label>
            <div class="input-group">
                <select name="weight_type" id="weight_type" class="form-control">
                    @foreach($weights as $list)
                    <option value="{{$list->id}}">{{$list->name}}</option>
                    @endforeach
                </select>
            </div>
        </div>
        <div class="col-md-2">
            <label for="product_price" class="form-label">Freight/Rate<span class="text-danger"><b>*</b></span></label>
            <div class="input-group">
               <input type="number" name="product_price" id="product_price" class="form-control br-0" value="" placeholder=" Product Price">  
            </div>
        </div>

        <div class="col-md-2 distance_column"  style="display:none;">
            <label for="product_price" class="form-label">Distance<span class="text-danger"><b>*</b></span></label>
            <div class="input-group">
               <input type="number" name="distance" id="distance" class="form-control br-0" value="" placeholder=" Enter Distance in Kilometer">  
            </div>
        </div> 
        <div class="col-md-2 hour_column"style="display:none;">
            <label for="product_price" class="form-label">Hour<span class="text-danger"><b>*</b></span></label>
            <div class="input-group">
               <input type="number" name="hours" id="hours" class="form-control br-0" value="" placeholder=" Enter Time in hours">  
            </div>
        </div> 
        <div class="col-md-4 volumetric_column"  style="display:none;">
            <label for="product_price" class="form-label">Volumetric Weight<span class="text-danger"><b>*</b></span></label>
            <div class="input-group input-group-sm">
                <div class="">
                    <span class="input-group-text " style="height: 100%;">L</span>
                </div>
                <input type="text" class="form-control form-control-sm volumetric_calculation" placeholder="Length" name="length" id="length">
                <div class="input-group-prepend">
                    <span class="input-group-text border-left-0 " style="height: 100%;">B</span>
                </div>
                <input type="text" class="form-control form-control-sm volumetric_calculation" placeholder="Breadth" name="breadth" id="breadth">
                <div class="input-group-prepend">
                    <span class="input-group-text border-left-0" style="height: 100%;">H</span>
                </div>
                <input type="text" class="form-control form-control-sm volumetric_calculation" placeholder="Height" name="height" id="height">
            </div>
        </div> 
        <div class="col-md-2 vehicle_column" style="display:none;">
            <label for="vehicle_type" class="form-label">Vehicle Type<span class="text-danger"><b>*</b></span></label>
           <div class="input-group">
                <select name="vehicle_type" id="vehicle_type" class="form-control">
                    <option value="">--Select--</option>
                    @foreach($vehicles as $vehicle)
                    <option value="{{$vehicle->name}}">{{$vehicle->name}}</option>
                    @endforeach
              </select>
            </div>
        </div>

        <div class="col-md-1">
            <label for="add_to_cart" class="form-label" style="color: white;">Add to</label>
            <button class="btn add_to_cart " style="color: white;background-color:blue;width: 100%;height: 40px;line-height:1;" type="button">Add To Cart</button>
        </div>
    </div>
    <div class="cart_products m-1">
    </div>

    <div class="row gx-0 p-3 m-1 " style="background-color: white;">
        <h5>Additional Charges</h5>
        <div class="col-lg-3 ">
            <label for="additional_charges" class="form-label">Charge Name<span class="text-danger"><b>*</b> </span></label>
            <div class="input-group" >
                <input type="text" name="" id="search_charge" class="search_charge form-control" placeholder="Search Additional Charge">
                <span class="text-danger error_search_charge" style="display:none;">This field is required.</span>
                <ul class="searchResult" style="width: 100%;"></ul>
                <input type="hidden" name="search_charge" value="">
            </div>
        </div>
        <div class="col-md-2">
            <label for="rate" class="form-label">Rate<span class="text-danger"><b>*</b></span></label>
            <div class="input-group">
                <input type="number" name="charge_rate" id="charge_rate" class="form-control " value="" placeholder="Enter Rate">
                <span class="text-danger error_charge_rate" style="display:none;">This field is required.</span>
            </div>
        </div>
        <div class="col-md-2">
            <label for="Qty" class="form-label">Qty <span class="text-danger"><b>*</b></span></label>
            <div class="input-group">
                <input type="number" name="charge_qty"  id="charge_qty" class="form-control  br-0" value="1" placeholder="Enter Quantity">
                <span class="text-danger error_charge_qty" style="display:none;">This field is required.</span>
            </div>
        </div>
        <div class="col-md-1">
            <label for="charge_tax" class="form-label">Tax <span class="text-danger"><b>*</b></span></label>
            <div class="input-group">
                <select name="charge_tax" id="charge_tax" class="form-control">
                    <option value="">--Select--</option>
                    @foreach($tax as $tax)
                    <option value="{{$tax->id}}">{{$tax->name}}</option>
                    @endforeach
              </select>
            </div>
        </div>
        <div class="col-md-2">
            <label for="amount" class="form-label">Amount <span class="text-danger"><b>*</b></span></label>
            <div class="input-group">
                <input type="number" name="charge_amount" id="charge_amount" class="form-control " value="" readonly placeholder=" Amount">
            </div>
        </div>
          
        <div class="col-md-2">
            <label for="charges_add_to_cart" class="form-label" style="color:white;">Add to </label>
            <button class="btn charges_add_to_cart" style="color: white;background-color:blue;width: 100%;height: 40px;" type="button">Add To Cart</button>
        </div>
    </div>

    <div class="charges_cart m-1">
    </div>

    <div class="col-12 justify-content-center">
        <div style="" class="accordion-item mx-1">
            <h2 class="accordion-header" id="panelsStayOpen2-headingTwo">
            <button class="accordion-button collapsed px-3" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen2-collapseTwo" aria-expanded="false" aria-controls="panelsStayOpen2-collapseTwo">
            Consignor Invoice Details
            </button>
            </h2>
            <div style="" id="panelsStayOpen2-collapseTwo" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen2-headingTwo">
                <div class="accordion-body p-0 m-0">
                    <div class="row gx-0 p-3 m-1 " style="background-color: white;">
                        <div class="col-md-1">
                            <label for="bill_date" class="form-label">Invoice Date </label>
                            <div class="input-group">
                                <input type="text" name="bill_date" id="bill_date" class="form-control " value="{{ now()->format('m/d/Y'); }}" placeholder="Enter Invoice Date">
                            </div>
                        </div>
                        <div class="col-lg-2">
                            <label for="bill_no" class="form-label">Invoice No <span class="text-danger"><b>*</b></span></label>
                            <div class="input-group" >
                                  <input type="number" name="bill_no" id="bill_no" class="form-control " value="" placeholder="Enter Invoice No ">
                                  <span class="text-danger error_bill_no" style="display:none;">This field is required.</span>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <label for="invoice_value" class="form-label">Invoice Value<span class="text-danger"><b>*</b></span></label>
                            <div class="input-group">
                                <input type="number" name="invoice_value"  id="invoice_value" class="form-control " value="" placeholder="Enter Invoice Value">
                                <span class="text-danger error_invoice_value" style="display:none;">This field is required.</span>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <label for="Way Bill No "  class="road_label" >E-Way Bill No</label>
                            <label for="Way Bill No "  class="rail_label" style="display:none;">R-Way Bill No</label>
                            <label for="Way Bill No "  class="air_label" style="display:none;">A-Way Bill No</label>
                            <label for="Way Bill No "  class="ship_label" style="display:none;">S-Way Bill No</label>
                            <div class="input-group" >
                                <input class="form-control form-control-lg" type="text" name="way_bill_no" id="way_bill_no" placeholder="Way Bill No" value="">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <label for="Way Bill Date " class = "road_label" >E-Way Bill Date</label>
                            <label for="Way Bill Date " class ="rail_label" style="display:none;">R-Way Bill Date</label>
                            <label for="Way Bill Date " class ="air_label" style="display:none;">A-Way Bill Date</label>
                            <label for="Way Bill Date " class ="ship_label" style="display:none;">S-Way Bill Date</label>
                            <div class="input-group">
                                <input class="form-control form-control-lg" type="text" name="way_bill_date" id="way_bill_date" placeholder="Way Bill Date"value="">
                            </div>
                        </div>
                        <div class="col-md-2">
                            <label for="Way Exp date " class = "road_label" >E-Way Exp Date</label>
                            <label for="Way Exp date " class ="rail_label" style="display:none;">R-Way Exp Date</label>
                            <label for="Way Exp date " class ="air_label" style="display:none;">A-Way Exp Date</label>
                            <label for="Way Exp date " class ="ship_label" style="display:none;">S-Way Exp Date</label>
                            <div class="input-group">
                                <input class="form-control form-control-lg" type="text" name="way_exp_date" id="way_exp_date" placeholder="Way Exp date" value="">
                            </div>
                        </div>
                        <div class="col-md-1">
                            <label for="add_to_cart" class="form-label" style="margin-bottom: 13px;"></label>
                            <button class="btn invoice_add_to_cart " style="color: white;background-color:blue;width: 100%;height: 40px;line-height:1;" type="button">Add To Cart</button>
                        </div>
                    </div>

                    <div class="invoice_cart m-1">
                    </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 & Continue </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>

    fetch_cart();

    fetch_charges_cart();

    fetch_invoice_cart();

    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);
        };
    }

    $(function () {
        $('#bill_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });

    $(function () {
        $('#invoice_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });

    $(function () {
        $('#way_bill_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });

    $(function () {
        $('#way_exp_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });
    $(function () {
        $('#container_return_expiry_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });

    $(function () {
        $('#do_validity_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })

    });

    $(function () {
        $('#lc_date').datepicker({
            dateFormat: 'dd/mm/yy'
        })
        .on('changeDate', function (ev) {
             $(this).datepicker('hide');
        })
    });

    function fetch_cart(){
      $.ajax({
        url:"{!! route('sale-products-cart') !!}",
        success:function(data){
            $('.cart_products').html('');
            $('.cart_products').html(data);

        }
      })
    }

    function fetch_charges_cart(){
      $.ajax({
        url:"{!! route('additional-charges-cart') !!}",
        success:function(data){
            $('.charges_cart').html('');
            $('.charges_cart').html(data);
           
        }
      })
    }

    function fetch_invoice_cart(){
      $.ajax({
        url:"{!! route('invoice-cart') !!}",
        success:function(data){
            $('.invoice_cart').html('');
            $('.invoice_cart').html(data); 
        }
      })
    }
    

    /**************** 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 Product ********************/

    $('#search_product').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="search_product"]').val('');
                    $(' [name="product_price"]').val('');
                    $(' [name="price_id"]').val('');
                    return false;
                }

                $.ajax({
                    url: "{{ route('search-product') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {

                        search: request.term,
                    },
                    success: function(json) {
                        if (json.error) {
                            $('.add_to_cart').attr('id', '');
                            $('.add_to_cart').data('id', '');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                price_id: item.price_id,
                                name: item.name,
                                mrp: item.mrp,
                                tax: item.tax,
                                netweight: item.netweight,
                                grossweight: item.grossweight,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                $('#search_product').val(ui.item.name);
                $('[name="search_product"]').val(ui.item.id);
                $('[name="product_price"]').val(ui.item.mrp);
                $('[name="price_id"]').val(ui.item.price_id);
                $('[name="batch"]').val(ui.item.batch);
                $('[name="actual_weight"]').val(ui.item.netweight);
                $('[name="gross_weight"]').val(ui.item.grossweight);
                $('[name="tax"]').val(ui.item.tax);
                $('[name="tax_id"]').val(ui.item.taxid);

                $('#search_product').trigger('keypress', { which: 9 });
                $('#rate_calculation_type').focus();
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            return $("<li>")
                .addClass("custom-ui-li")
                .append("<a>" + item.name + " | Price:" + item.mrp + "</a>")
                .appendTo(ul);
        };

       $(document).on('click','.add_to_cart', function(e) {

        e.preventDefault();
        $('.error_search_product').hide();
        $('.error_duplicate_customer_id').hide();
        $('.error').removeClass('error');
        var error = 0;

        if ($('[name="search_product"]').val().trim() == '') {
          $('#search_product').addClass('error');
          $('#search_product').focus();
          error = 1;

        }
         if ($('[name="item_qty"]').val().trim() ==  '') {
          $('#item_qty').addClass('error');
          $('#item_qty').focus();
          error = 1;
        }
        if ($('[name="gross_weight"]').val().trim() == '') {
          $('#gross_weight').addClass('error');
          $('#gross_weight').focus();
          error = 1;
        }

      if ($('#create_form').find('[name="taxpaidby"]').val() == '') {
            $('.error_taxpaidby').show();
            $('#taxpaidby').focus();
            error = 1;
            setTimeout(function () {
            $('.error_taxpaidby').hide();
            }, 3000);
        }

        if (error == 0) {   
           let item_qty = $('#item_qty').val();
           let product_price = $('#product_price').val();
           let actual_weight = $('#actual_weight').val();
           let rate_calculation_type = $('[name="rate_calculation_type"]').val();
           let gross_weight = $('#gross_weight').val();
           let hours = $('#hours').val();
           let distance = $('#distance').val();
           let weight_type = $('#weight_type').val();
           let taxpaidby = $('#taxpaidby').val();
           let search_product = $('[name="search_product"]').val();

            $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
            $.ajax({
                type: 'POST',
                url: "{{ route('products-add-to-cart') }}",
                data: {
                    search_product:search_product,
                    item_qty:item_qty,
                    product_price:product_price,
                    actual_weight:actual_weight,
                    gross_weight:gross_weight,
                    hours:hours,
                    distance:distance,
                    weight_type:weight_type,
                    taxpaidby:taxpaidby,
                    rate_calculation_type:rate_calculation_type,
                },
                success: function (response) {
                    if (response.success === true) {
                        toastr.success(response.message, 'Success.');
                        fetch_cart();

                        
                        let total = response.total;
                        $(' [name="total_billing"]').val(total);
                        $(' #search_product').val('');
                        $(' [name="search_product"]').val('');
                        $(' [name="product_price"]').val('');
                        $(' [name="actual_weight"]').val('');
                        $(' [name="gross_weight"]').val('');
                        $(' [name="item_qty"]').val('1');
                        $(' [name="tax"]').val('');
                        $(' [name="hours"]').val('');
                        $(' [name="distance"]').val('');
                        // $(' [name="distance"]').val('');
                        $(' [name="vehicle_type"]').val('');
                        $('#search_product').focus();
                    } 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!');
            });
        }

        error = 1;
    })

$(document).on('focusout', '[name="item_qty_update"]', delay(function(){
        var product_id = $(this).data('product_id');
        $.ajax({
          url     : '{!! route("cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('id'),
                "item_qty": $(this).val(),  
                "taxpaidby": $('#taxpaidby').val(),
                "rate_calculation_type": $(this).data('rate-cal'),
          },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
               fetch_cart();
              let total = response.total;
               $(' [name="total_billing"]').val(total);
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    },700)); 

$(document).on('input', '.taxpaidby', delay(function(){

        $.ajax({
          url     : '{!! route("taxpaidby-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "taxpaidby": $(this).val(),
                
          },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
               fetch_cart();
               fetch_charges_cart();
              let total = response.total;
               $(' [name="total_billing"]').val(total);
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    },700));

     /**************** Search Charges ********************/

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

                $.ajax({
                    url: "{{ route('search-charge') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        search: request.term,
                    },
                    success: function(json) {
                        if (json.error) {
                            $('.charge_add_to_cart').attr('id', '');
                            $('.charge_add_to_cart').data('id', '');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                                code: item.shortcode,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {

                $('#search_charge').val(ui.item.name);
                $('[name="search_charge"]').val(ui.item.id);

                $('#search_charge').trigger('keypress', { which: 9 });
                $('#charge_rate').focus();
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            return $("<li>")
                .addClass("custom-ui-li")
                .append("<a>" + item.name + " </a>")
                .appendTo(ul);
        };

 $(document).on('click','.charges_add_to_cart', function(e) {
        e.preventDefault();
        $('.error_customer_id').hide();
        $('.error_search_charges').hide();
        $('.error_duplicate_customer_id').hide();
        $('.error').removeClass('error');
        var error = 0;

        if ($('[name="search_charge"]').val().trim() == '') {
          $('#search_charge').addClass('error');
          $('#search_charge').focus();
          error = 1;
        }
         if ($('[name="charge_qty"]').val().trim() == '') {
          $('#charge_qty').addClass('error');
          $('#charge_qty').focus();
          error = 1;
        }
         if ($('[name="charge_rate"]').val().trim() == '') {
          $('#charge_rate').addClass('error');
          $('#charge_rate').focus();
          error = 1;
        }
        if ($('#create_form').find('[name="taxpaidby"]').val() == '') {
            $('.error_taxpaidby').show();
            $('#taxpaidby').focus();
            error = 1;
            setTimeout(function () {
            $('.error_taxpaidby').hide();
            }, 3000);
        }

        if (error == 0) {   
           let charge_qty = $('#charge_qty').val();
           let charge_rate = $('#charge_rate').val();
           let search_charge = $('[name="search_charge"]').val();
           let charge_tax = $('[name="charge_tax"]').val();
           let taxpaidby = $('[name="taxpaidby"]').val();

            $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
            $.ajax({
                type: 'POST',
                url: "{{ route('charges-add-to-cart') }}",
                data: {
                    search_charge:search_charge,
                    charge_qty:charge_qty,
                    charge_rate:charge_rate,
                    charge_tax:charge_tax,
                    taxpaidby:taxpaidby,

                },
                success: function (response) {
                    if (response.success === true) {
                        toastr.success(response.message, 'Success.');
                        fetch_charges_cart();
                        let total = response.total;
                        $(' [name="total_billing"]').val(total);
                        $(' #search_charge').val('');
                        $(' [name="search_charge"]').val('');
                        $(' [name="charge_rate"]').val('');            
                        $(' [name="charge_qty"]').val('1');            
                        $(' [name="charge_amount"]').val('');                   
                        $(' [name="charge_tax"]').val('');                   
                    } 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!');
            });
        }

        error = 1;
    })


    $(document).on('focusout', '[name="charge_qty_update"]', delay(function(){
        var charge_id = $(this).data('charge_id');
        var taxpaidby = $('#taxpaidby').val();

        $.ajax({
          url     : '{!! route("cart-charge-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('id'),
                "charge_qty": $(this).val(),
                "taxpaidby": $('#taxpaidby').val(),
          },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                fetch_charges_cart();
              let total = response.total;
               $(' [name="total_billing"]').val(total);

              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    },500));


  /**************** Invoice Cart ********************/

     $(document).on('click','.invoice_add_to_cart', function(e) {
        e.preventDefault();
        $('.error_customer_id').hide();
        $('.error_duplicate_customer_id').hide();
        $('.error').removeClass('error');
        var error = 0;
        if ($('[name="bill_no"]').val().trim() == '') {
          $('#bill_no').addClass('error');
          $('#bill_no').focus();
          error = 1;

        }
        if ($('[name="invoice_value"]').val().trim() == '') {
          $('#invoice_value').addClass('error');
          $('#invoice_value').focus();
          error = 1;
        }
        if (error == 0) {
           let bill_no         = $('#bill_no').val();
           let bill_date       = $('#bill_date').val();
           let invoice_value   = $('#invoice_value').val();
           let way_bill_no   = $('#way_bill_no').val();
           let way_bill_date = $('#way_bill_date').val();
           let way_exp_date  = $('#way_exp_date').val();
           
            $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
            $.ajax({
                type: 'POST',
                url: "{{ route('invoice-add-to-cart') }}",
                data: {
                    bill_no:bill_no,
                    bill_date:bill_date,
                    invoice_value:invoice_value,
                    way_bill_no:way_bill_no,
                    way_bill_date:way_bill_date,
                    way_exp_date:way_exp_date,

                },
                success: function (response) {
                    if (response.success === true) {
                        toastr.success(response.message, 'Success.');
                        fetch_invoice_cart();

                        let total = response.total;
                        $(' [name="total_billing"]').val(total);
                        $(' [name="bill_no"]').val('');
                        $(' [name="invoice_value"]').val('');                   
                        $(' [name="way_bill_no"]').val('');                   
                        $(' [name="way_bill_date"]').val('');                   
                        $(' [name="way_exp_date"]').val('');                   
                    } 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!');
            });
        }

        error = 1;
    })
  
/*********delete data**********/
    $("body").on("click",'.deleteDataCustom', function(event){
          dataString   = {"id":$(this).data('id')};
          var UrlValue = $(this).data('url');
          var btn      = $(this);
          var type   = $(this).data('type');
          Swal.fire({
              title: 'Are you sure you want to delete this?',
              icon: 'warning',
              showDenyButton: true,
              showCancelButton: false,
              confirmButtonText: 'Yes',
              denyButtonText: 'No',
          }).then((result) => {
              /* Read more about isConfirmed, isDenied below */
              if (result.isConfirmed) {
                  $.ajax({
                  url: UrlValue,
                  method  : 'post',
                  data    : {
                        "_token": $('meta[name="csrf-token"]').attr('content'),
                        "id": $(this).data('id')
                    },
                  headers:
                  {
                      'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                  },
                  beforeSend: function( xhr ) {
                      // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                  },
                  success : function(response){
                      if(response.success){
                          var ErroMsg = $(this).printErrorMsg(response.message);

                          $(this).Toastshow('success',ErroMsg);

                          if(type == 'product'){
                          fetch_cart();
                          }
                         else if (type == 'charge'){
                            fetch_charges_cart();
                            }
                          else{
                            fetch_invoice_cart();
                          }
                      }else{
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error',ErroMsg);
                      }
                  },
                  error: function (data) {
                    console.log("error ",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,
                                city_id:item.city_id,
                                country_id:item.country_id
                                
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();
                var city_id = ui.item.city_id ;
                var country_id = ui.item.country_id ;
                $("#from_id").val(city_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,
                                city_id: item.city_id,
                                country_id:item.country_id,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();;
                var city_id = ui.item.city_id ;
                var country_id = ui.item.country_id ;
                $("#to_id").val(city_id);
                $("#consigneecountry_id").val(country_id);

                $(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();
  }
  }); 
}) 

 // search LC issued By
$(document).ready(function(){
        $('.lc_issued_by-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="lc_issued_by_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="lc_issued_by_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="lc_issued_by_id"]').val(ui.item.id);
                $('.lc_issued_by_id').hide();
                $('#lc_date').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 CFS
$(document).ready(function(){
        $('.cfs_agent-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="cfs_agent_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="cfs_agent_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="cfs_agent_id"]').val(ui.item.id);
                $('.cfs_agent_id').hide();
                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();
            $(".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', '#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();
            $(".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', '#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();
            $(".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', '#create_lc_issued_by', function(){
        $('#commonModalLabel').text('Add New LC Issued By');
        $('.save_button_span').text('Save LC Issued BY');
        $('.save_button').addClass('save-lc_issued_by');
         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();
            $(".vendor_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', '#create_cfs_agent', function(){
        $('#commonModalLabel').text('Add New CFS Agent');
        $('.save_button_span').text('Save CFS Agent');
        $('.save_button').addClass('save-cfs_agent');
         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();
            $(".vendor_columns").remove();
            $(".lc_issued_by_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();
          }
        })
    })


    // 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();
                    $(".lc_issued_by_columns").remove();
                    $(".cfs_agent_columns").remove();   
                    $(".broker_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();
                    $(".lc_issued_by_columns").remove();
                    $(".cfs_agent_columns").remove();
                    $(".broker_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();
                    $(".lc_issued_by_columns").remove();
                    $(".cfs_agent_columns").remove();
                    $(".broker_columns").remove();
                    reinitializeTelInput();
                }
            });
        }
    });

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

            $('#commonModalLabel').text('Edit Lc Issued By');
            $('.save_button_span').text('Update Lc Issued By');
            var id = $('[name="lc_issued_by_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();
                    $(".vendor_columns").remove();
                    $(".cfs_agent_columns").remove();
                    $(".broker_columns").remove();
                    reinitializeTelInput();
                }
            });
        }
    });

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

            $('#commonModalLabel').text('Edit CFS Agent');
            $('.save_button_span').text('Update CFS Agent');
            var id = $('[name="cfs_agent_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();
                    $(".vendor_columns").remove();
                    $(".lc_issued_by_columns").remove();
                    $(".broker_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 ($('#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="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="vendor_id"]').val(response.data.id);
                      $('#vendor_id').val(response.data.name);
                      $('#bill_to_address').val(response.data.address);
                      $('.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-vendor');
                      
                      // 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 lc issued by ************/

$(document).on('click', '.save-lc_issued_by', 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="lc_issued_by_id"]').val(response.data.id);
                      $('#lc_issued_by_id').val(response.data.name);
                      $('.vendor').hide();
                      $('#edit_lc_issued_by').prop('disabled', false);
                      $('.save_button').removeClass('save-lc_issued_by');
                      // 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 cfs agent ************/

$(document).on('click', '.save-cfs_agent', 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="cfs_agent_id"]').val(response.data.id);
                      $('#cfs_agent_id').val(response.data.name);
                      $('.cfs_agent_id').hide();
                      $('#edit_cfs_agent').prop('disabled', false);
                      $('.save_button').removeClass('save-cfs_agent_id');
                      // 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();
        });

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

    });


 /******* 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();
        });

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

    });
 /******* 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();
        });

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

    }); 

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

        toggleEditButton();

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

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


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

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

        toggleEditButton();

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

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


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

       
    });
     
     $(document).on('input', '#charge_qty,#charge_rate', function(event){
        var charge_rate = $('#charge_rate').val();
        var charge_qty = $('#charge_qty').val();

        var amount = charge_qty * charge_rate;

        $('#charge_amount').val(amount) ;

     })

     $(document).on('input', '#rate_calculation_type', function(event){
        var selectedOption = $('#rate_calculation_type').find('option:selected');
            // if (selectedOption.text() === 'Option 2') {

        if (selectedOption.text() === 'Distance') {
        $('.distance_column').show();
        $('.hour_column').hide() ;
        $('.volumetric_column').hide() ;
        $('.vehicle_column').hide() ;
         $('.gross_column').removeClass('col-md-1');
            $('.gross_column').addClass('col-md-2');

        }else if(selectedOption.text() === 'Hours'){
            $('.distance_column').hide();
            $('.hour_column').show() ;
            $('.volumetric_column').hide() ;
            $('.vehicle_column').hide() ;
            $('.gross_column').removeClass('col-md-1');
            $('.gross_column').addClass('col-md-2');
        }else if(selectedOption.text() === 'Volumetric Weight'){
            $('.distance_column').hide();
            $('.hour_column').hide() ;
            $('.volumetric_column').show() ;
            $('.vehicle_column').hide() ;
            $('.gross_column').removeClass('col-md-1');
            $('.gross_column').addClass('col-md-2');
        }else if (selectedOption.text() === 'Vehicle Type'){
            $('.distance_column').hide();
            $('.hour_column').hide() ;
            $('.volumetric_column').hide() ;
            $('.vehicle_column').show() ;
           $('.gross_column').removeClass('col-md-1');
            $('.gross_column').addClass('col-md-2');
        }
        else{
            $('.distance_column').hide();
            $('.hour_column').hide() ;
            $('.volumetric_column').hide() ;
            $('.vehicle_column').hide() ;
            $('.gross_column').addClass('col-md-1');
            $('.gross_column').removeClass('col-md-2');
        }
     })

     $(document).on('input', '#transportation_id', function(event){
        var selectedOption = $('#transportation_id').find('option:selected');

        if (selectedOption.text() === 'ROAD') {
        $('.road_label').show();
        $('.rail_label').hide() ;
        $('.air_label').hide() ;
        $('.ship_label').hide() 
      

        }else if(selectedOption.text() === 'RAIL'){
            $('.road_label').hide();
            $('.rail_label').show() ;
             $('.air_label').hide() ;
             $('.ship_label').hide() 
          
        }
        else if(selectedOption.text() === 'AIR'){
           $('.road_label').hide();
            $('.rail_label').hide() ;
             $('.air_label').show() ;
             $('.ship_label').hide() 
          
        }else if (selectedOption.text() === 'SHIP'){
            $('.road_label').hide();
            $('.rail_label').hide() ;
             $('.air_label').hide() ;
             $('.ship_label').show() 
          
        }
     })

   //**** Total Products Cart  *****\\

    $(document).on('click','.new_bookings', function(e) {
        e.preventDefault();
        $('.error_search_product').hide();
        $('.error_duplicate_customer_id').hide();
        $('.error').removeClass('error');
        var error = 0;

        if ($('#create_form').find('[name="consignors_id"]').val() == '') {
            $('.error_consignors_id').show();
            $('#consignor_id').focus();
            error = 1;
            setTimeout(function () {
            $('.error_consignors_id').hide();
            }, 3000);
        }

        if ($('#create_form').find('[name="consignees_id"]').val() == '') {
            $('.error_consignees_id').show();
            $('#consignee_id').focus();
            error = 1;
            setTimeout(function () {
            $('.error_consignees_id').hide();
            }, 3000);
        }

        if ($('#create_form').find('[name="bill_to_party"]').val() == '') {
            $('.error_bill_to_party').show();
            $('#bill_to_party').focus();
            error = 1;
            setTimeout(function () {
            $('.error_bill_to_party').hide();
            }, 3000);
        }

        if ($('#create_form').find('[name="taxpaidby"]').val() == '') {
            $('.error_taxpaidby').show();
            $('#taxpaidby').focus();
            error = 1;
            setTimeout(function () {
            $('.error_taxpaidby').hide();
            }, 3000);
        }

        if ($('#create_form').find('[name="transportation_id"]').val() == '') {
            $('.error_transportation_id').show();
            $('#transportation_id').focus();
            error = 1;
            setTimeout(function () {
            $('.error_transportation_id').hide();
            }, 3000);
        }
        if ($('#create_form').find('[name="bill_to_address"]').val() == '') {
            $('.error_bill_to_address').show();
            $('#bill_to_address').focus();
            error = 1;
            setTimeout(function () {
            $('.error_bill_to_address').hide();
            }, 3000);
        }
        if ($('#create_form').find('[name="ship_to_address"]').val() == '') {
            $('.error_ship_to_address').show();
            $('#ship_to_address').focus();
            error = 1;
            setTimeout(function () {
            $('.error_ship_to_address').hide();
            }, 3000);
        }
        if ($('#create_form').find('[name="delivery_type"]').val() == '') {
            $('#delivery_type').focus();
            $('.error_delivery_type').show();
            error = 1;
            setTimeout(function () {
            $('.error_delivery_type').hide();
            }, 3000);
        }
        if ($('#create_form').find('[name="shipping_risk"]').val() == '') {
            $('#shipping_risk').focus();
            $('.error_shipping_risk').show();
            error = 1;
            setTimeout(function () {
            $('.error_shipping_risk').hide();
            }, 3000);

        }if ($('#create_form').find('[name="transport_type"]').val() == '') {
            $('#transport_type').focus();
            $('.error_transport_type').show();
            error = 1;
            setTimeout(function () {
            $('.error_transport_type').hide();
            }, 3000);
        }

        if (error == 0) {   
           let consignor_id         = $('[name="consignors_id"]').val();
           let consignee_id         = $('[name="consignees_id"]').val();
           let vendor_id               = $('[name="vendors_id"]').val();
           let voucher_type         = $('#voucher_type').val();
           let bill_to_party           = $('#bill_to_party').val();
           let from_id                    = $('[name="from_id"]').val();
           let to_id                          = $('[name="to_id"]').val();
           let taxpaidby                = $('#taxpaidby').val();
           let transportation_id = $('#transportation_id').val();
           let pickup_address     = $('#pickup_address').val();
           let bill_to_address      = $('#bill_to_address').val();
           let ship_to_address    = $('#ship_to_address').val();
           let delivery_type         = $('#delivery_type').val();
           let shipping_risk         = $('#shipping_risk').val();
           let transport_type         = $('#transport_type').val();
           let container_no          = $('#container_no').val();
           let seal_number           = $('#seal_number').val();
           let do_number             = $('#do_number').val();
           let do_validity_date     = $('#do_validity_date').val();
           let container_return_expiry_date = $('#container_return_expiry_date').val();
           let lc_number               = $('#lc_number').val();
           let lc_date                      = $('#lc_date').val();
           let lc_issued_by           = $('#lc_issued_by').val();
           let cfs                              = $('#cfs').val();


            $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
            $.ajax({
                type: 'POST',
                url: "{{ route('all-products-add-to-cart') }}",
                data: {
                    consignor_id       : consignor_id,
                    consignee_id       : consignee_id,
                    vendor_id             : vendor_id,
                    voucher_type      : voucher_type,
                    bill_to_party        : bill_to_party,
                    from_id                 : from_id,
                    to_id                       : to_id,
                    taxpaidby             : taxpaidby,
                    pickup_address  : pickup_address,
                    bill_to_address   : bill_to_address,
                    ship_to_address : ship_to_address,
                    shipping_risk      : shipping_risk,
                    delivery_type      : delivery_type,
                    transportation_id  : transportation_id,
                    transport_type       : transport_type,
                    container_no       : container_no,
                    seal_number        : seal_number,
                    do_number           : do_number,
                    do_validity_date  : do_validity_date,
                    lc_number             : lc_number,
                    lc_issued_by         : lc_issued_by,
                    lc_date                   : lc_date,
                    cfs                            : cfs,
                    container_return_expiry_date : container_return_expiry_date ,

                },
                success: function (response) {
                    if (response.success === true) {
                        toastr.success(response.message, 'Success.');
                        window.location.href = '{!! route("sales") !!}';
                        
                    } 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!');
            });
        }
    })

</script>
@endsection
