@extends('layouts.app')
@section('title')
@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">
    .breadcrumb-title {
        border-right: none;
    }

    .dataTables_filter {
        margin-bottom: 6px;
    }
</style>
<!--breadcrumb-->
<div class="page-breadcrumb row align-items-center justify-content-between mb-3 px-3 px-md-0">
    <div class="breadcrumb-title col-md-6"> Booking
    </div>
    <div class="col-md-6">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb justify-content-md-end mb-0">
                <li class="breadcrumb-item"><i class="bi bi-info-circle-fill text-info show-help-support" data-id="178" data-bs-toggle="modal" data-bs-target="#commonModal"></i></li>
                <li class="breadcrumb-item" aria-current="page">Booking</li>
                <li class="breadcrumb-item active" aria-current="page"><i class="bi bi-dot"></i> Booking View</li>
            </ol>
        </nav>
    </div>
</div>
<input type="hidden" name="id_of_booking" id="id_of_booking" value="{{ $booking->id }}">
<!--end breadcrumb-->
<div class="row auto">
    <div class="col-xl-12 mx-auto" style="font-size:14px ;">
        <div class="shadow-none radius-5 min-height">
            <div class="row">
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Consignor Details</h5>

                                    <button data-id="" class="btn btn-white "  id = "edit_consignor" data-type = "consignor" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit">
                                        <i class="bi bi-pencil-square"></i>
                                    </button>

                                </div>
                                <hr class="">
                                <table class="">
                                    <tr>
                                        <td style="text-align:left;" id = "consignor_id" > <b>Consignor Name   :  {{ ucfirst($consignor->name ?? '') }} </b></td>
                                         <input type="hidden" name="consignors_id" value="{{ $consignor->id }}">
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;"  id="consignor_phone"><b> Phone no. </b> :  {{$consignor->phone_no ?? ''}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;"  id="consignor_city"><b> City </b>  :  {{$from_location_id->name ?? ''}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;" id="consignor_address"><b>Address  </b> :  {{$consignor->address ?? ''}}</td>
                                    </tr>
                                     <tr>
                                        <td style="text-align:left;" id="consignor_email"><b>Email </b> :  {{$consignor->email?? ''}}</td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3 row">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0"> Consignee Details</h5>
                                    <button type="button" class="btn btn-white "  id = "edit_consignee" data-type = "consignee" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit">
                                        <i class="bi bi-pencil-square"></i>
                                    </button>
                                </div>
                                <hr class="">
                                <table class="">
                                    <tr>
                                        <td style="text-align:left;" id="consignee_id"><b> Consignee Name  :  {{ ucfirst($consignee->name ?? '') }} </b></td>
                                         <input type="hidden" name="consignee_id"  id = "consignee_id" value="{{ $consignee->id }}">
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;" id="consignee_phone"><b>Phone no. </b>  :  {{$consignee->phone_no ?? ''}}</td>
                                    </tr>
                                    <tr>

                                    {{--    <td style="text-align:left;"><b>City</b>  :  {{$to_location_id->name}}</td>--}}
                                        <td style="text-align:left;" id="consignee_city"><b>City</b>  :  {{$to_location_id->name ?? ''}}</td>

                                    </tr>
                                    <tr>
                                        <td style="text-align:left;" id="consignee_address"><b>Address </b> :  {{$consignee->address ?? ''}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;" id="consignee_email"><b> Email  </b>:  {{$consignee->email?? ''}}</td>
                                    </tr>  
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3 row">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Vendor Details</h5>
                                    @if(isset($vendor))
                                    <button  type="button" class="btn btn-white "  id = "edit_vendor"   data-type = "vendor" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit">
                                        <i class="bi bi-pencil-square"></i>
                                    </button>
                                    @endif
                                </div>
                                <hr class="">
                                <table class="">
                                  @if(isset($vendor))
                                    <tr>
                                        <td style="text-align:left;" id="vendor_id"><b>Vendor Name  :  {{ ucfirst($vendor->name ?? '') }}</b></td>
                                        <input type="hidden" name="vendor_id" value="{{ $vendor->id }}">
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;" id="vendor_phone"><b>Phone no. </b> :  {{$vendor->phone_no ?? ''}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;" id="vendor_city"><b>City</b>  : {{$vendor_city->name}}  </td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;" id="vendor_address"><b>Address </b> :  {{$vendor->address ?? ''}}</td>
                                    </tr>
                                     <tr>
                                        <td style="text-align:left;" id="vendor_email"><b>Email</b> :  {{$vendor->email?? ''}}</td>
                                    </tr>
                                 @else
                                    <tr>
                                        <td style="text-align:left;">No Vendor</b></td>
                                    </tr>
                                @endif
                                </table>
                            </div>
                        </div>
                    </div>
                </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="row auto ">
    <div class="col-xl-12 mx-auto" style="font-size:14px ;">
        <div class="shadow-none radius-5 min-height">
            <div class="row">
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Booking Details</h5>
                                            <button class="btn  btn-btn-white " id="edit_view_details" type="button" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit"><i class="bi bi-pencil-square"></i></button>
                                </div>
                                <hr class="">
                                <table class="">
                                    <tr>
                                        <td style="text-align:left;" id="voucher_type"> <b>Voucher Type  :  {{$booking->voucher_type_code ?? ''}}   </b></td>
                                    </tr> 
                                    <tr>
                                        <td style="text-align:left;" id="biil_to_party"> <b>Bill To Party  :  {{ ucfirst($bill_to_party->name ?? '') }}  </b></td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;" id="transportation_mode"><b>Transportation Mode </b> :  {{$transportations->code ?? ''}}</td>
                                    </tr>
                                    <tr>
                                    <td style="text-align:left;" id="transport_type"><b> Transpot Type</b>  :  {{$transports->name ?? ''}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;" id="delivery_type"><b>Delivery Type  </b> :  {{$deliveries->name ?? ''}}</td>
                                    </tr>
                                     <tr>
                                        <td style="text-align:left;" id="shipping_risk"><b>Shipping Risk</b> :  {{$risks->name?? ''}}</td>
                                    </tr> 
                                     <tr>
                                        <td style="text-align:left;"  name = "taxpaidby"  id="taxpaidby"  value = "{{  $taxpaidby->id }}"><b>Tax Paid By:  {{$taxpaidby->code ?? ''}}</b></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Insurance Details</h5>
                                    @if(isset($insurance))
                                            <button class="btn  btn-btn-white " id="edit_insurance" type="button" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit"><i class="bi bi-pencil-square"></i></button>
                                     @endif
                                </div>
                                <hr class="">
                                <table class="">
                                    @if(isset($insurance))
                                    <tr>
                                        <td style="text-align:left;" id="insurance_provider"> <b>Insurance Provider  :  {{ucfirst($insurance_provider->name ?? '' )}}   </b></td>
                                    </tr> 
                                    <tr>
                                        <td style="text-align:left;" id="policy_no"> <b>Policy Number  :  {{ $insurance->policy_no ?? '' }}  </b></td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;" id="policy_percentage"><b>Policy Percentage </b> :  {{$insurance->policy_percentage ?? '' }}%</td>
                                    </tr>
                                    <tr>
                                    <td style="text-align:left;" id="policy_amount"><b> Policy Amount</b>  :  {{$insurance->policy_amount ?? ''}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;" id="claim_amount"><b>Claim Amount  </b> :  {{$insurance->claim_amount ?? ''}}</td>
                                    </tr>
                                    @else
                                    <tr>
                                        <td style="text-align:left;">No Insurance</b></td>
                                    </tr>
                                @endif
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3 row">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Container Details</h5>
                                    @if(isset($containerDetails))
                                    <a href="{{route('edit.container' , $containerDetails->id)}}" class="btn btn-white"  id="containerDetails" title="Edit">
                                        <i class="bi bi-pencil-square"></i>
                                    </a>
                                    @endif
                                </div>
                                <hr class="">
                                <table class="">
                                  @if(isset($containerDetails))
                                    <tr>
                                        <td style="text-align:left;" ><b>Container No  :  {{ ucfirst($containerDetails->container_no ?? '') }}</b></td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;"><b>Seal Number </b> :  {{$containerDetails->seal_no ?? ''}}</td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;"><b>Delivery Order (DO) Number</b>  : {{$containerDetails->delivery_order_no}}  </td>
                                    </tr>
                                    <tr>
                                        <td style="text-align:left;"><b>Delivery Order (DO) Validity date </b> :  {{$containerDetails->delivery_order_validity_date ?? ''}}
                                        </td>
                                    </tr>
                                     <tr>
                                        <td style="text-align:left;"><b> Container Return Expiry Date</b> :  {{$containerDetails->container_return_expiry_date?? ''}}</td>
                                    </tr>
                                 @else
                                    <tr>
                                        <td style="text-align:left;">No Container Details</b></td>
                                    </tr>
                                @endif
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Pickup Address Details</h5>
                                            <button class="btn  btn-btn-white " id="edit_pickup" type="button" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit"><i class="bi bi-pencil-square"></i></button>
                                </div>
                                <hr class="">
                                <table class="">
                                    <tr>
                                        <td style="text-align:left;" id="pickup_address"> <b>Pickup Address  </b>  :   {{$pickup_address->address_line1 ?? '' }}</td>
                                    </tr> 
                                    <tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Bill To  Address Details</h5>
                                            <button class="btn  btn-btn-white " id="edit_billto" type="button" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit"><i class="bi bi-pencil-square"></i></button>
                                </div>
                                <hr class="">
                                <table class="">
                                    <tr>
                                        <td style="text-align:left;" id="billto_address"><b>Bill To Address </b> :  {{$bill_to_address->address_line1 ?? '' }}</td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Ship To Address Details</h5>
                                            <button class="btn  btn-btn-white " id="edit_shipto" type="button" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit"><i class="bi bi-pencil-square"></i></button>
                                </div>
                                <hr class="">
                                <table class="">
                                    <tr>
                                    <td style="text-align:left;" id="shipto_address"><b>Ship To/Delivery Address</b>  :  {{$ship_to_address->address_line1 ?? ''}}</td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="card">
                        <div class="card-body g-3">
                            <div class="table-responsive">
                                <div class="d-flex justify-content-between">
                                    <h5 class="mb-0">Broker Details</h5>
                                    @if(isset($containerDetails))
                                            <button class="btn  btn-btn-white " id="edit_broker_detail" type="button" data-bs-toggle="modal" data-bs-target="#commonModal" title="Edit"><i class="bi bi-pencil-square"></i></button>
                                            @endif
                                </div>
                                <hr class="">
                                <table class="">
                                    @if(isset($broker->name)  )
                                    <tr>
                                    <td style="text-align:left;" id="broker_id"> <b> Broker </b>  :  {{ $broker->name ?? '' }} </td>
                                    </tr>
                                    <tr>
                                    <td style="text-align:left;" id="broker_commission"> <b> Booker Commission </b>  :  {{$booking->broker_commission ?? ''}}</td>
                                    </tr>
                                    @else
                                    <tr>
                                        <td style="text-align:left;">No Broker Details</b></td>
                                    </tr>
                                @endif
                                </table>
                            </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="panelsStayOpen5-headingTwo2">
          <button class="accordion-button collapsed p-2" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen5-collapseTwo" aria-expanded="false" aria-controls="panelsStayOpen5-collapseTwo">
           <h5 style="padding:5px;"> Add Item </h5>
          </button>
        </h2>
        <div style="" id="panelsStayOpen5-collapseTwo" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo2">
            <div class="accordion-body p-0 m-0">
                  <form class="item-form" name="item-form" id="item-form" action="#"  method="post" enctype='multipart/form-data'  >
                        @csrf
                        <input type="hidden" name="booking_id"  id="booking_id" value="{{$booking->id}}">
                         <input  type="hidden" name = "tax_paid_by"  id="tax_paid_by"  value = " {{$taxpaidby->code ?? ''}}"> 
                    <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>
                </form>
            </div>
        </div>
    </div>
 </div>
    <div class="cart_products m-1">
    </div>

    <div class="col-12 justify-content-center mb-1">
        <div style="" class="accordion-item mx-1">
            <h2 class="accordion-header" id="panelsStayOpen6-headingTwo">
              <button class="accordion-button collapsed p-2" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen6-collapseTwo" aria-expanded="false" aria-controls="panelsStayOpen6-collapseTwo">
               <h5 style="padding:5px;"> Add Charge </h5>
              </button>
            </h2>
            <div style="" id="panelsStayOpen6-collapseTwo" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo2">
                <div class="accordion-body p-0 m-0">
                      <form class="charge-form" name="charge-form" id="charge-form" action="#"  method="post" enctype='multipart/form-data'  >
                         @csrf
                            <div class="row gx-0 p-3 m-1 " style="background-color: white;">
                                <h5>Additional invoice</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>
                        </form >
                </div>
            </div>
        </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">
           <h6> Consignor Invoice Details </h6>
            </button>
            </h2>
            <div style="" id="panelsStayOpen2-collapseTwo" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen2-headingTwo">
                <div class="accordion-body p-0 m-0">
                    <form class="invoice-form" name="invoice-form" id="invoice-form" action="#"  method="post" enctype='multipart/form-data'  >
                        @csrf
                        <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" >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"  >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 " >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>
                </form>
                    <div class="invoice_cart m-1">
                    </div>

                </div>
            </div>
        </div>
    </div>

@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 fetch_cart(){
        let booking_id = $('#id_of_booking').val();
        $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
      $.ajax({
        url:"{!! route('products-cart') !!}",
         data: {
                     booking_id  : booking_id,
          },
        success:function(data){
            $('.cart_products').html('');
            $('.cart_products').html(data);
        }
      })
    }

 function fetch_charges_cart(){
        let booking_id = $('#id_of_booking').val();
        $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
      $.ajax({
        url:"{!! route('charges-cart') !!}",
        data: {
                     booking_id  : booking_id,
          },
        success:function(data){
            $('.charges_cart').html('');
            $('.charges_cart').html(data);
           
        }
      })
    }

    function fetch_invoice_cart(){
        let booking_id = $('#id_of_booking').val();
        $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
      $.ajax({
        url:"{!! route('invoices-cart') !!}",
        data: {
                     booking_id  : booking_id,
          },
        success:function(data){
            $('.invoice_cart').html('');
            $('.invoice_cart').html(data); 
        }
      })
    }

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

  // editing accounts
    
    $(document).on('click', '#edit_consignor', function() {
        $('.save_button').addClass('save-consignor');
            $('#commonModalLabel').text('Edit Consignor');
            $('.save_button_span').text('Update Consignor');
            var id = $('[name="consignors_id"]').val();
            var url = `{!! route('booking.editaccount', ':id') !!}`.replace(':id', id);
            var type   = $(this).data('type');
            var booking_id   = $('#id_of_booking').val();
            $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
               }
               });
            $.ajax({
                type: 'POST',
                url: url,
                data: {
                    type       : type,
                    booking_id       : booking_id,
                },
                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');

            $('#commonModalLabel').text('Edit Consignee');
            $('.save_button_span').text('Update Consignee');
            var id = $('[name="consignee_id"]').val();
            var url = `{!! route('booking.editaccount', ':id') !!}`.replace(':id', id);
            var type   = $(this).data('type');
            var booking_id   = $('#id_of_booking').val();
            $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
               }
               });
            $.ajax({
                type: 'POST',
                url: url,
                data: {
                    type       : type,
                    booking_id       : booking_id,
                },
                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');
            $('#commonModalLabel').text('Edit Vendor');
            $('.save_button_span').text('Update Vendor');
            var id = $('[name="vendors_id"]').val();
            var url = `{!! route('booking.editaccount', ':id') !!}`.replace(':id', id);
            var type   = $(this).data('type');
            var booking_id   = $('#id_of_booking').val();
            $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
               }
               });
            $.ajax({
                type: 'POST',
                url: url,
                data: {
                    type       : type,
                    booking_id       : booking_id,
                },
                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 Vendor');
            $('.save_button_span').text('Update Vendor');
            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 (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.');
                      console.log(response)
                      $('[name="consignors_id"]').val(response.data.id);
                      $('#consignor_id').html( '<b> Consignor Name  : '+response.data.name +' </b>');
                      $('#consignor_address').html(' <b>Address </b> :  '+ response.data.address +'');
                      $('#consignor_phone').html(' <b>Phone no. </b> :  '+ response.data.phone_no+'');
                      $('#consignor_city').html(' <b>City</b> :  '+ response.data.city +'');
                      $('#consignor_email').html(' <b>Email</b> :  '+ response.data.email +'');
                      $('.consignor').hide();
                      $('#voucher').focus();
                      $('.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').html( '<b> Consignee Name  : '+response.data.name +' </b>');
                      $('#consignee_address').html(' <b>Address </b> :  '+ response.data.address +'');
                      $('#consignee_phone').html(' <b>Phone no. </b> :  '+ response.data.phone_no+'');
                      $('#consignee_city').html(' <b>City</b> :  '+ response.data.city +'');
                      $('#consignee_email').html(' <b>Email</b> :  '+ response.data.email +'');
                      $('.consignee').hide();
                      $('#vendor_id').focus();
                      $('.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').html( '<b> Vendor Name  : '+response.data.name +' </b>');
                      $('#vendor_address').html(' <b>Address </b> :  '+ response.data.address +'');
                      $('#vendor_phone').html(' <b>Phone no. </b> :  '+ response.data.phone_no+'');
                      $('#vendor_city').html(' <b>City</b> :  '+ response.data.city +'');
                      $('#vendor_email').html(' <b>Email</b> :  '+ response.data.email +'');
                      $('.vendor').hide();
                      $('.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;
 })

 // editing booking details 

   $(document).on('click', '#edit_view_details', function() {
        $('.save_button').addClass('save-view_details');
            $('#commonModalLabel').text('Edit Booking Details');
            $('.save_button_span').text('Update Booking');
            var id = $('[name="id_of_booking"]').val();
            var url = `{!! route('bookingdetails-view-edit', ':id') !!}`.replace(':id', id);
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            });
    });

   $(document).on('click', '.save-view_details', function(event){
   event.preventDefault()
  var error = 0;

   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.');
                      $('.save_button').removeClass('save-view_details');
                      console.log(response)
                       $('#taxpaidby').html(' <b>Tax Paid By  : '+response.data.taxpaidby +'</b> ');
                       $('#voucher_type').html('<b> Voucher Type  : '+response.data.voucher_type+' </b>');
                       $('#transportation_id').html('<b> Transportation Mode   </b>: '+response.data.transportation_id +' ');
                       $('#shipping_risk').html('<b> Shipping Risk  </b>: '+response.data.shipping_risk +' ');
                       $('#delivery_type').html('<b> Delivery Type  </b>: '+response.data.delivery_type +' ');
                       $('#transport_type').html(' <b>Transpot Type  </b>: '+response.data.transport_type +' ');
                       $('#bill_to_party').html('<b> Insurance Provider  : '+response.data.bill_to_party +' </b>');
                      // hide modal
                      $('#commonModal').modal('hide');
                      $('#commonModal').find('.modal-body').html('');
                      fetch_cart();
                  } 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;
 })

 // editing Insurance 

   $(document).on('click', '#edit_insurance', function() {
        $('.save_button').addClass('save-insurance');
            $('#commonModalLabel').text('Edit Insurance Details');
            $('.save_button_span').text('Update ');
            var id = $('[name="id_of_booking"]').val();
            var url = `{!! route('edit-insurance', ':id') !!}`.replace(':id', id);
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            });
    });

   $(document).on('click', '.save-insurance', function(event){
   event.preventDefault()
  var error = 0;

   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.');
                      $('.save_button').removeClass('save-view_details');
                       $('#insurance_provider').html( '<b> Insurance Provider  : '+response.data.insurance_provider +' </b>');
                       $('#policy_no').html( '<b> Policy Number  :  '+ response.data.policy_no +' </b>');
                       $('#policy_percentage').html( '<b> Policy Percentage  </b>: '+ response.data.policy_percentage +'% ');
                       $('#policy_amount').html( '<b> Policy Amount </b> :  '+ response.data.policy_amount +' ');
                       $('#claim_amount').html( '<b> Claim Amount  </b>:  '+ response.data.claim_amount +' ');
                      // 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;
 })


 // editing pickup address

   $(document).on('click', '#edit_pickup', function() {
        $('.save_button').addClass('save-pickup');
            $('#commonModalLabel').text('Edit Pickup Address');
            $('.save_button_span').text('Update Address');
            var id = $('[name="id_of_booking"]').val();
            var url = `{!! route('edit-pickup-address', ':id') !!}`.replace(':id', id);
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            });
    });

   $(document).on('click', '.save-pickup', function(event){
   event.preventDefault()
  var error = 0;

   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.');
                      $('.save_button').removeClass('save-pickup');
                      console.log(response)
                       $('#pickup_address').html( '<b> Pickup Address   </b> : '+response.data.address_line1 +'');
                      // 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;
 })


 // editing Bill to address

   $(document).on('click', '#edit_billto', function() {
        $('.save_button').addClass('save-billto');
            $('#commonModalLabel').text('Edit Bill To Address');
            $('.save_button_span').text('Update Address');
            var id = $('[name="id_of_booking"]').val();
            var url = `{!! route('edit-billto-address', ':id') !!}`.replace(':id', id);
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            });
    });

   $(document).on('click', '.save-billto', function(event){
   event.preventDefault()
  var error = 0;

   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.');
                      $('.save_button').removeClass('save-billto');
                      console.log(response)
                       $('#billto_address').html( '<b> Bill To Address   </b> : '+response.data.address_line1 +'');
                      // 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;
 })


 // editing Ship to address

   $(document).on('click', '#edit_shipto', function() {
        $('.save_button').addClass('save-shipto');
            $('#commonModalLabel').text('Edit Ship To Address');
            $('.save_button_span').text('Update Address');
            var id = $('[name="id_of_booking"]').val();
            var url = `{!! route('edit-shipto-address', ':id') !!}`.replace(':id', id);
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            });
    });

   $(document).on('click', '.save-shipto', function(event){
   event.preventDefault()
  var error = 0;

   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.');
                      $('.save_button').removeClass('save-shipto');
                      console.log(response)
                       $('#shipto_address').html( '<b> Ship To  Address   </b> : '+response.data.address_line1 +'');
                      // 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;
 })


   $(document).on('click', '.save-broker-details', function(event){
   event.preventDefault()
  var error = 0;

   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.');
                      $('.save_button').removeClass('save-shipto');
                      console.log(response)
                       $('#shipto_address').html( '<b> Ship To  Address   </b> : '+response.data.address_line1 +'');
                      // 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;
  })


    /**************** 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 });
                $('#item_qty').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);
        };

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


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


      $(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 ($('[name="gross_weight"]').val() <  1) {
          $('#gross_weight').addClass('error');
          $('#gross_weight').focus();
          error = 1;
        }

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

        if (error == 0) {   
           let booking_id = $('#booking_id').val();
           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 = $('#tax_paid_by').val();
           let search_product = $('[name="search_product"]').val();

            $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
            $.ajax({
                type: 'POST',
                url: "{{ route('storeitem') }}",
                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,
                    booking_id:booking_id,
                    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="vehicle_type"]').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('click', '.edit', function(){
        $('.save_button').addClass('save-items');
        $('#commonModalLabel').text('Edit Item');
        $('.save_button_span').text('Update Item');
        var id = $(this).data('id');
        var url = `{!! route('edit-item', ':id') !!}`.replace(':id', id);

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

  // ************* Save item ************/

 $(document).on('click', '.save-items', function(event){
        event.preventDefault();
          $('.error_name').hide();
        var error = 0;

        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.');

                      fetch_cart();

                      $('.save_button').removeClass('save-items');

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

  $(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 = $('#tax_paid_by').val();
             let booking_id = $('#booking_id').val();


            $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
            $.ajax({
                type: 'POST',
                url: "{{ route('storecharge') }}",
                data: {
                    search_charge:search_charge,
                    charge_qty:charge_qty,
                    charge_rate:charge_rate,
                    charge_tax:charge_tax,
                    taxpaidby:taxpaidby,
                    booking_id:booking_id,
                },
                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('click', '.edit_charge', function(){
      $('.save_button').addClass('save-charges');
        $('#commonModalLabel').text('Edit Charge');
        $('.save_button_span').text('Update Charge');
        var id = $(this).data('id');
        console.log(id);
        var url = `{!! route('edit-charge', ':id') !!}`.replace(':id', id);

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

  // ************* Save Charge ************/

  $(document).on('click', '.save-charges', function(event){
        event.preventDefault();
          $('.error_name').hide();
        var error = 0;

        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.');

                      fetch_charges_cart();

                      $('.save_button').removeClass('save-charges');

                      // 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;
      })
 $(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', '#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) ;

     })

  /**************** 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();
           let booking_id = $('#booking_id').val();
           
            $.ajaxSetup({
            headers : {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
            $.ajax({
                type: 'POST',
                url: "{{ route('storeinvoice') }}",
                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,
                    booking_id:booking_id,

                },
                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="bill_date"]').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;
    })
     $(document).on('click', '.edit-invoice', function(){
      $('.save_button').addClass('save-invoice');
        $('#commonModalLabel').text('Edit Invoice');
        $('.save_button_span').text('Update Invoice');
        var id = $(this).data('id');
        console.log(id);
        var url = `{!! route('edit-invoice', ':id') !!}`.replace(':id', id);

        $.ajax({
          url:url,
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $(function () {
        $('#bill_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');
        })

    });

          }
        })
      })

 // ************* Save Charge ************/

 $(document).on('click', '.save-invoice', function(event){
        event.preventDefault();
          $('.error_name').hide();
        var error = 0;

        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.');

                      fetch_invoice_cart();

                      $('.save_button').removeClass('save-invoice');

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

// for 1
 $(document).on('click', '#edit_broker_detail', function() {
        $('.save_button').addClass('save-broker-details');
            $('#commonModalLabel').text('Edit Broker');
            $('.save_button_span').text('Update Broker');
            var id = $('[name="id_of_booking"]').val();
            var url = `{!! route('edit-broker_details', ':id') !!}`.replace(':id', id);
            $.ajax({
                url: url,
                success: function(data) {
                    $('#commonModal').find('.modal-body').html('');
                    $('#commonModal').find('.modal-body').html(data);
                }
            });
    });

  $(document).on('click', '.save-broker-details', function(event){
   event.preventDefault()
  var error = 0;

   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.');
                      $('.save_button').removeClass('save-broker-details');

                       $('#shipto_address').html( '<b> Ship To  Address   </b> : '+response.data.address_line1 +'');
                       $('#bill').html( '<b> Ship To  Address   </b> : '+response.data.address_line1 +'');
                       $('#broker_commission').html( '<b> Broker Commision </b> : '+response.data.broker_commision+'');
                      // 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;
  })

// for 2


    $(document).on('click', '#edit_broker', function() {
        $('.save_button').addClass('save-broker');
            $('#commonModalLabel').text('Edit Broker');
            $('.save_button_span').text('Update Broker');
            var id = $('[name="brokers_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();
                    $(".vendor_columns").remove(); 
                    reinitializeTelInput();
                }
            });
    });
</script>
 <script type="text/javascript">

//    // search consignor

// $(document).ready(function(){
//   $('.account-select').autocomplete
//   ({
//             autoFocus: true,
//             minLength: 0,
//             source: function(request, response) {
//                 if (request.term.length < 2) {
//                     $('[name="accounts_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="accounts_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();
              
//                 $(this).val(ui.item.name  + "");
//                 $('[name="accounts_id"]').val(ui.item.id);
//                 return false;
//             }
//         }).data("ui-autocomplete")._renderItem = function(ul, item)
//          {
//             return $("<li>")
//                 .append("<a>" + item.name +   "</a>")
//                 .appendTo(ul);
//         };

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

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

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