@extends('layouts.app')
@section('title','Billing')
@section('pages')
<style type="text/css">
    #total_billing {
        border-color: #5cff80;
        background-color: #e0ffe2;
        font-size: 16px;
    }

    #due_balance_amount {
        border-color: #ff7979;
        background-color: #ffe0e0;
        font-size: 16px;
    }

    .final_total_billing {
        border-color: #5cff80 !important;
        background-color: #e0ffe2 !important;
        font-size: 16px !important;
    }

    #amount_recieved {
        border-color: #fff579;
        background-color: #fff6e0;
        font-weight: 600;
        font-size: 16px;
    }

    .amount_collection {
        border: 2px solid #fff579;
        /* background-color: #f9f2df; */
        font-weight: 600;
        font-size: 16px;
    }

.autocomplete{
        position: relative;
    }
    .autocomplete .searchResult{
        list-style: none;
        padding: 0px;
        width: 78%;
        position: absolute;
        margin: 0;
        margin-top: 40px;
        background: white;
        z-index: 5;
    }

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

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

    .autocomplete .searchResult li:hover{
        cursor: pointer;
        background: #CACFD2;
    }

</style>
<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" />

<!--breadcrumb-->
<div class="page-breadcrumb d-flex align-items-center mb-3 px-3 px-md-0">
    <div class="breadcrumb-title pe-3"><i class="bi bi-list"></i> Sale Billings</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">

                <li class="breadcrumb-item active" aria-current="page">Edit Sale Billing</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="javascript:history.back()" class="btn btn-primary"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
        </div>
    </div>
</div>
<!--end breadcrumb-->
<div class="row ">
    <div class="col-md-3 mt-0">
        <div class="card border shadow-none" style="margin-bottom:0.8rem;">
            <div class="card-body py-2">
                <div class="d-flex gap-3">
                     <div class="icon">
                           <div class="icon-box small_icon bg-light-primary border-0">
                              <i class="bi bi-person-hearts text-primary"></i>
                           </div>
                           <h6 class="text-center mt-1 mb-0"><small>Consignor</small></h6>
                     </div>
                     <div class="info">
                           <p class="mb-0">{!! $consignor['name'] ?? '' !!}</p>
                           <p class="mb-0">{!! isset($consignor['phone_no']) && $consignor['phone_no'] != '' ? ' ' . $consignor['phone_no'] : '' !!}</p>
                     </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mt-0">
        <div class="card border shadow-none" style="margin-bottom:0.8rem;">
            <div class="card-body py-2">
                 <div class="d-flex gap-3">
                        <div class="icon">
                           <div class="icon-box small_icon bg-light-primary border-0">
                             <i class="bi bi-person text-primary"></i>
                           </div>
                           <h6 class="text-center mt-1 mb-0"><small>Consignee</small></h6>
                        </div>
                        <div class="info">
                           <p class="mb-0">{!! $consignee['name'] ?? '' !!}</p>
                           <p class="mb-0">{!! isset($consignee['phone_no']) && $consignee['phone_no'] != '' ? ' ' . $consignee['phone_no'] : '' !!}</p>
                        </div>
                  </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 mt-0">
        <div class="card border shadow-none" style="margin-bottom:0.8rem;">
            <div class="card-body py-2">
                 <div class="d-flex gap-3">
                        <div class="icon">
                           <div class="icon-box small_icon bg-light-primary border-0">
                             <i class="bi bi-person text-primary"></i>
                           </div>
                           <h6 class="text-center mt-1 mb-0"><small>Vendor</small></h6>
                        </div>
                        <div class="info">
                           <p class="mb-0">{!! $vendor['name'] ?? '' !!}</p>
                           <p class="mb-0">{!! isset($vendor['phone_no']) && $vendor['phone_no'] != '' ? ' ' . $vendor['phone_no'] : '' !!}</p>
                        </div>
                  </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <form class="row auto-width mt-0"  action="{{ route('booking-register.store')}}"  method="post" enctype='multipart/form-data'  style="padding: 0px 0px 0px 9px;" id="billing_form">
        @csrf
        <div class="col-6 "style="padding: 0 0 0 9px;">
            <div class="card">
                <div class="card-body g-3 row">
                    <div class="col-md-4 ">
                    <h5 class="mb-0 ">Billing Details</h5>
                    </div>
                    <hr class="mb-2">
                    <div class="col-md-6">
                        <label for="invoice_date" class="form-label">Billing Date <span class="text-danger"><b>*</b></span></label>
                        <input type="text" class="form-control" id="invoice_date" name="invoice_date" aria-describedby="inputGroupPrepend" required value="{{ now()->format('m/d/Y'); }}">
                        <span class="text-danger error_invoice_date" style="display: none;">This field is required.</span>
                    </div>
                    <div class="col-md-6">
                        <label for="amount" class="form-label">Taxable Amount </label>
                        <input type="text" class="form-control" name="taxable_amount" id="taxable_amount" value="{{ $taxable_amount}}" placeholder="Enter Textable Amount">
                        <span class="text-danger" style="display: none;">This field is required.</span>
                    </div>
                    <div class="col-md-6">
                        <label for="payment_term" class="form-label">Payment Terms</label>
                        <div class="input-group">
                          <select name="payment_term" id="payment_term" class="form-control">
                          @foreach($payment_terms as $list)
                            <option value="{{$list->id}}">{{$list->name}}</option>
                          @endforeach
                        </select>
                        </div>
                    </div>
                    <div class="col-md-6 ">
                         <label for="">Manual LR/CN NO</label>
                        <div class="input-group">
                        <input id="manual_lr_no" class="form-control table-search" type="number" name="manual_lr_no" placeholder="Enter Manual LR/CN No." >
                        </div>
                    </div>
                    <div class="col-md-12">
                        <label for="amount" class="form-label">Total Billing Amount <span class="text-danger"><b>*</b></span></label>
                        <input type="text" class="form-control" name="total_billing" id="total_billing" readonly value="{{ $total }}" style="text-align: right;">
                        <span class="text-danger" style="display: none;">This field is required.</span>
                    </div>
                    
                    <div class="col-md-12">
                        <div class="table-responsive">
                            <table id="example" class="table table-bordered align-middle" style="width:100%">
                                <thead class="table-light">
                                    <tr>
                                        <th class="text-start">Transaction Mode </th>
                                        <th class="text-start">Transaction Reference</th>
                                        <th style="text-align:right;width: 30%">Advance Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @if(isset($accounting_group) )
                                    @foreach($accounting_group as $key => $list)
                                    <tr class="cart-products" data-patient_id="{{$list['account_id']}}">
                                        <td class="text-start">
                                            <input type="hidden" class="form-control" name="payment_mode[{!! $list->id !!}][mode_id]" value="{!! $list->id !!}" style="text-align: right;">
                                            {{$list->name ?? ''}}
                                        </td>
                                        <td class="text-start">
                                            <select class="form-control" name="payment_mode[{!! $list->id !!}][transaction_mode_id]">
                                                @if(isset($list->chart_of_account_sub_type->paymentModes))
                                                @foreach($list->chart_of_account_sub_type->paymentModes as $value)
                                                    <option value="{!! $value->id !!}" {!! matchselected($value->is_default, 1) !!}>{!! $value->mode !!}</option>
                                                @endforeach
                                                @endif
                                            </select>
                                        </td>
                                        <td style="text-align: center;">
                                            <input type="number" class="form-control amount amount_collection" name="payment_mode[{!! $list->id !!}][amount]" value="0" style="text-align: right;">
                                        </td>
                                    </tr>
                                    @endforeach
                                    @else
                                    <tr>
                                        <td colspan="9">No Data Found</td>
                                    </tr>
                                    @endif
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label for="due_balance_amount" class="form-label">Due Balance Amount</label>
                        <input type="text" class="form-control" id="due_balance_amount" name="due_balance_amount" value="{{ $total }}" readonly  style="text-align: right;">
                        <span class="text-danger error_due_balance_amount" style="display: none;">This field is required.</span>
                        <span class="text-danger error_due_balance_amount_negative" style="display: none;">Due amount can not be in negative.</span>
                    </div>
                    <div class="col-md-6">
                        <label for="amount_recieved" class="form-label">Total Amount Received</label>
                        <input type="text" class="form-control" value="00" id="amount_recieved" name="amount_recieved" style="text-align: right;" readonly  >
                        <span class="text-danger error_amount_recieved" style="display: none;">This field is required.</span>
                    </div>
                    <div class="d-grid gap-2 with-100">
                         <button class="btn btn-primary submit" type="button"><i class="bx bx-save"></i> Submit </button>
                    </div>
                </div>   
            </div>      
        </div>
        <div class="col-md-6  card" style="padding: 0 0 0 9px;">
            <div class="card-body g-3 px-1">
                <div class="col-md-4 ">
                    <h5 class="mb-0 ">Additional  Details</h5>
                </div>
                <hr class="mb-2">
                <input type="hidden" name="insurance" id = "insurance" value="">
                <div class="col-12 justify-content-center mb-1 insurance_columns">
                    <div style="" class="accordion-item">
                        <h2 class="accordion-header" id="panelsStayOpen-headingTwo">
                          <button class="accordion-button collapsed p-2" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseTwo" aria-expanded="false" aria-controls="panelsStayOpen-collapseTwo">
                            Insurance Details
                          </button>
                        </h2>
                        <div style="" id="panelsStayOpen-collapseTwo" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo">
                            <div class="accordion-body p-0 m-0">
                                <div class="card m-0">
                                    <div class="card-body p-1">
                                        <div class="row">
                                            <div class="col-md-6  mb-1">
                                                <label  for=""> Insurance Provider</label>
                                                <select onchange ="insurancevalue()" name="insurance_provider" id="insurance_provider" class="form-control" >
                                                    <option value="">~select~</option>
                                                    @foreach($account as $account)
                                                        <option value="{{$account->id}}">{{$account->name}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            <div class="col-md-6  mb-1">
                                                <label  for="">Policy Number</label>
                                                <div class="input-group">
                                                <input id="policy_number" class="form-control " type="number" name="policy_number" placeholder=" Policy Number" >
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-1" >
                                                <label  for="policy_amount">Policy Amount</label>
                                               <div class="input-group" >
                                                <input id="" class="form-control " type="number" name="policy_amount" placeholder="  Amount"  >
                                                </div>
                                            </div>
                                            <div class="col-md-4  mb-1" >
                                                <label  for="policy_percentage">Policy Percentage</label>
                                               <div class="input-group" >
                                                <input id="" class="form-control " type="number" name="policy_percentage" placeholder="Policy Percentage" >
                                                </div>
                                            </div>
                                            <div class="col-md-4  mb-1">
                                                <label  for="claim_amount">Claim Amount</label>
                                                <div class="input-group">
                                                <input id="claim_amount" class="form-control " type="number" name="claim_amount" placeholder=" Claim Amount" >
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-12 justify-content-center mb-1">
                    <div style="" class="accordion-item">
                        <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">
                           Broker Details
                          </button>
                        </h2>
                        <div style="" id="panelsStayOpen5-collapseTwo" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo2">
                            <div class="accordion-body p-0 m-0">
                                <div class="card m-0">
                                    <div class="card-body p-1">
                                        <div class="row">
                                             <div class="col-md-6  mb-1">
                                                    <label for="search_broker"><b>Broker</b><span class="text-danger"><b>*</b></span></label>
                                                    <div class="input-group autocomplete" >
                                                         <input type="text" name="" id="broker_id" class="broker-select form-control " placeholder="Search broker" value="">
                                                         <ul class="searchResult" ></ul>
                                                         <input type="hidden" name="brokers_id" value = "">
                                                        <button class="btn btn-secondary add_btn" id="create_broker" type="button" data-bs-toggle="modal" data-bs-target="#commonModal"> + </button>
                                                        <button class="btn btn-sm btn-primary "style="margin-left: 4px ;width:45px" type="button"  id="edit_broker" data-bs-toggle="modal" data-bs-target="#commonModal"  ><i class="bi bi-pencil-square"></i>
                                                        </button>      
                                                </div>
                                             </div>
                                            <div class="col-md-6  mb-1">
                                                <label  for="">Broker Commission</label>
                                                <div class="input-group">
                                                <input id="broker_commission" class="form-control " type="text" name="broker_commission" placeholder=" Enter Broker Commission">
                                                </div>
                                            </div>
                                            <div class="col-md-6  mb-1" >
                                                <label  for="">Broker Note</label>
                                                <div class="input-group">
                                                <input id="broker_note" class="form-control " type="text" name="broker_note" placeholder="Search Broker Note">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</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 }}">  
@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://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/12.1.10/js/intlTelInput.js"></script>
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js') }}"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>

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

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

    function fetch_due_balance_amount() {
        $.ajax({
            url: '{!! route("sale-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "type": 'billing',
                "amount_recieved": $('[name="amount_recieved"]').val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                    $('[name="due_balance_amount"]').val(response.data.due_balance_amount);
                    due_balance()
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    }

    $(document).on('click', '.submit', function(e) {
        e.preventDefault();
        $('.error_payment_mode_id').hide();
        $('.error_payment_term_id').hide();
        $('.error_due_balance_amount').hide();
        $('.error_due_balance_amount_negative').hide();
        var error = 0;

        if ($('[name="due_balance_amount"]').val() == '' || $('[name="due_balance_amount"]').val() == null) {
            $('.error_due_balance_amount').show();
            error = 1;
        }
        if ($('[name="due_balance_amount"]').val().trim() < 0) {
            $('.error_due_balance_amount_negative').show();
            error = 1;
        }
         if ($('[name="due_balance_amount"]').val().trim() < 0) {
            $('.error_due_balance_amount_negative').show();
            error = 1;
        }

        if (error == 0) {

            $('#billing_form').submit();
        }
    });


    $(document).on('change', '[name="payment_mode"]', function() {
        $.ajax({
            url: '{!! route("sale-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "type": 'billing',
                "payment_mode": $(this).val(),
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function(response) {
                if (response.success) {
                }
            },
            error: function(data) {
                console.log("error ", data);
            }
        });
    })

    $(document).on('focusout input', '[name="amount_recieved"]', function() {
        due_balance()
    })

    function due_balance() {
        $('#due_balance_amount').val($('[name="due_balance_amount"]').val() - $('[name="amount_recieved"]').val());

        if ($('#due_balance_amount').val() < 0) {
            $('.submit').attr('disabled', true);
        } else {
            $('.submit').attr('disabled', false);
        }
    }

         $(document).on('keyup', '.amount', function(){

        var sum_amount = 0;
        var amount = 0;
        $(".amount").each(function() {
            var value = $(this).val();

            // add only if the value is number
            if (!isNaN(value) && value.length != 0) {
                sum_amount += parseFloat(value);
            }

        });
        var total_billing = $('#total_billing').val();
        if (total_billing < sum_amount) {
            $(this).val(amount);
        } else {
            $('#amount_recieved').val(sum_amount);
          }
         var amounts =  total_billing - sum_amount;
        $('#due_balance_amount').val(amounts) ; 
        });



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

    });
function insurancevalue(){
     $('#insurance').val('YES');
};


// search Broker
$(document).ready(function(){
        $('.broker-select').autocomplete({
            autoFocus: true,
            minLength: 0,
            source: function(request, response) {
                if (request.term.length < 2) {
                    $('[name="brokers_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="brokers_id"]').val('');
                            return false;
                        }
                        response($.map(json.result, function(item) {
                            return {
                                id: item.id,
                                name: item.name,
                            };
                        }));
                    }
                });
            },
            select: function(event, ui) {
                event.preventDefault();

                $(this).val(ui.item.name + "");
                $('[name="brokers_id"]').val(ui.item.id);
                $('.broker_id').hide();
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item)
         {
            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };

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

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


  document.addEventListener("click", (event) => 
  {
  if (event.target !== customerSelect && event.target !== querySelector) {
  $(".searchResult").empty();
  }
  }); 
})
        $(document).on('click', '#create_broker', function(){
        $('#commonModalLabel').text('Add New Broker');
        $('.save_button_span').text('Save Broker');
        $('.save_button').addClass('save-broker');
        var account_type_id = $('.account_types_id').val();
        var accounting_group_id = $('.accounting_group_id').val();
        $.ajax({
          url:"{!! route('booking.createconsignor') !!}",
          success:function(data){
            $('#commonModal').find('.modal-body').html('');
            $('#commonModal').find('.modal-body').html(data);
            $(".consignor_columns").remove();
            $(".consignee_columns").remove();
            $(".vendor_columns").remove();
            $(".lc_issued_by_columns").remove();
            $(".cfs_agent_columns").remove();
            $('#quality_form').append('<input type="hidden" name="accounting_group_id" value="'+accounting_group_id+'">')
            $('#quality_form').append('<input type="hidden" name="account_type_id" value="'+account_type_id+'">')
            reinitializeTelInput();
          }
        })
    })


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

            $('#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();
                    $(".vendor_columns").remove();
                    $(".lc_issued_by_columns").remove();
                    $(".cfs_agent_columns").remove();
                    reinitializeTelInput();
                }
            });
        }
    });




 //*************** save broker ************/

$(document).on('click', '.save-broker', 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="brokers_id"]').val(response.data.id);
                      $('#broker_id').val(response.data.name);
                      $('.broker_id').hide();
                      $('#edit_broker').prop('disabled', false);
                      $('.save_button').removeClass('save-broker_id');
                      // hide modal
                      $('#commonModal').modal('hide');
                      $('#commonModal').find('.modal-body').html('');
                  } else {
                      toastr.error(response.message, 'Error!');
                  }
              }
          })

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

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


    /******* Disabling & Enabling edit button of  Broker ************/

    $(document).ready(function() {
        function toggleEditButton() {
            var patientId = $('[name="brokers_id"]').val();
            $('#edit_broker').prop('disabled', patientId.trim() === "");
        }
        toggleEditButton();
        $('#broker_id').on('input', function() {
            toggleEditButton();
        });
        $('#broker_id').on('change', function() {
            toggleEditButton();
        });
        function enableEditButton() {
            $('#edit_broker').prop('disabled', false);
        }
 
    });

</script>
@endsection