@extends('layouts.app')
@section('title','Purchase Billings')
@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;
    }
</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" />

<!--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> Purchase 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">Add New Purchase Billing</li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{!! route('purchase.create') !!}" 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 auto">
    <div class="col-xl-12 mx-auto">
        <div class=" shadow-none radius-5 min-height">
            <div class="">
                <div class="row g-3 auto-width">
                    <div class="col-md-12 cart_products">
                    </div>
                    <div class="col-md-12 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>Supplier</small></h6>
                              </div>
                              <div class="info">
                                 <p class="mb-0">{!! $customers['name'] ?? '' !!}</p>
                                 <p class="mb-0">{!! isset($customers['phone_no']) && $customers['phone_no'] != '' ? ' ' . $customers['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>Doctor</small></h6>
                              </div>
                              <div class="info">
                                @if(!empty($doctors))
                                 <p class="mb-0">{!! $doctors['name'] ?? '' !!}</p>
                                  <p class="mb-0">{!! isset($doctors['phone_no']) && $doctors['phone_no'] != '' ? ' ' . $doctors['phone_no'] : '' !!}</p>
                                 <p class="mb-0">{!! isset($doctors['gender']) && $doctors['gender'] != '' ? ' ' . $doctors['gender'] : '' !!}{!! isset($doctors['date_of_birth']) && $doctors['date_of_birth'] != '' ? ', ' . $doctors['date_of_birth'] : '' !!}</p>
                                @else
                                    <p class="mb-0">Self</p>
                                @endif
                              </div>
                           </div>
                           </div>
                         </div>
                    </div>--}}


                    <form class="row auto-width mt-0" action="{{ route('purchase.store')}}" method="post" enctype='multipart/form-data' style="padding: 0px 0px 0px 9px;" id="billing_form">
                        <div class="col-md-6" style="padding: 0 0 0 9px;">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    @csrf
                                    <div class="col-md-4 mt-3">
                                    <h5 class="mb-0">Sale Details</h5>
                                    </div>
                                    <div class="col-md-8 mt-3" style="text-align: right;display: flex; justify-content: space-between;">
                                        <label for="validationCustomOrder" style="margin-top: 5px;margin-left: auto;" class="form-label"><b>Round Off?</b> </label><br>
                                        <input name="round_off" class="form-check-inputFeatured btn-lg round_off" type="checkbox" checked id="round_off" value="1">
                                    </div>
                                    <hr class="mb-2">
                                    <div class="col-md-6">
                                        <label for="supplier_invoice_no" class="form-label">Supplier Invoice No. <span class="text-danger"><b>*</b></span></label>
                                        <input type="text" class="form-control" id="supplier_invoice_no" placeholder="Supplier Invoice No" name="supplier_invoice_no" aria-describedby="inputGroupPrepend" required
                                        value=""
                                        >
                                        <span class="text-danger error_supplier_invoice_no" style="display: none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="invoice_date" class="form-label">Invoice Date <span class="text-danger"><b>*</b></span></label>
                                        <input type="text" readonly class="form-control" id="invoice_date" name="invoice_date" aria-describedby="inputGroupPrepend" required
                                        value=""
                                        >
                                        <span class="text-danger error_invoice_date" style="display: none;">This field is required.</span>
                                    </div>
                                    {{-- <div class="col-md-6">
                                        <div>
                                            <label for="payment_term_id" class="form-label">Payment Term <span class="text-danger"><b>*</b></span></label>
                                        </div>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="payment_term_id">
                                                @foreach($payment_types as $list)
                                                <option value="{{ $list->id }}" {!! isset($data['payment_term_id']) && $data['payment_term_id'] = $list->id ? 'selected' : ($list->is_default == 1 ? 'selected' : '') !!}>{{ $list->payment_term_name }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <span class="text-danger error_payment_term_id" style="display: none;">This field is required.</span>
                                    </div> --}}

                                    <div class="col-md-6">
                                        <label for="amount" class="form-label">Total Billing Amount <span class="text-danger"><b>*</b></span></label>
                                        <input type="text" class="form-control" id="total_billing" readonly value="{!! convertDecimelPoint($data['amount']) !!}">
                                        <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) && count($accounting_group) > 0)
                                                    @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
                                                    @if($discount_group)
                                                    <tr class="cart-products">
                                                        <td class="text-start">
                                                            <input type="hidden" class="form-control" name="discount_account_id" value="{!! $discount_group->id !!}" style="text-align: right;">
                                                        {{$discount_group->name ?? ''}}</td>
                                                        <td class="text-start">
                                                        <select name="discount_type" id="discount_type" class="form-control">
                                                            <option value="FLAT" {!! isset($data['discount_type']) && $data['discount_type'] == 'FLAT' ? 'selected' : '' !!}>FLAT</option>
                                                            <option value="PERCENTAGE" {!! isset($data['discount_type']) && $data['discount_type'] == 'PERCENTAGE' ? 'selected' : '' !!}>%</option>
                                                        </select>
                                                        </td>
                                                        <td style="text-align: center;">
                                                        <input type="text" class="form-control" id="special_discount" value="{!! $data['special_discount'] !!}" name="special_discount" style="text-align: right;">
                                                        </td>
                                                    </tr>
                                                    @endif

                                                    @if($round_off)
                                                    <tr class="cart-products round_off_show">
                                                        <td class="text-start">
                                                        {{$round_off->name ?? ''}}</td>
                                                        <td class="text-start">
                                                        <select name="round_off_account_id" id="round_off_account_id" class="form-control">
                                                            <option value="{!! $round_off->id !!}">{!! $round_off->name !!}</option>
                                                        </select>
                                                        </td>
                                                        <td style="text-align: center;">
                                                            <input type="text" class="form-control" id="round_off_amount" value="" name="round_off_amount" style="text-align: right;" readonly>
                                                        </td>
                                                    </tr>
                                                    @endif

                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    <div class="col-md-12 round_off_show">
                                        <label for="final_total_billing_amount" class="form-label" style="float: right;">Final Total Billing Amount</label>
                                        <input type="text" class="form-control final_total_billing" id="final_total_billing_amount" name="final_total_billing_amount" value="" readonly  style="text-align: right;">
                                    </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="{!! convertDecimelPoint($data['due_balance_amount']) !!}" readonly >
                                        <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">Adv. / Amt. Received</label>
                                        <input type="text" class="form-control" value="{!! convertDecimelPoint($data['amount_recieved']) !!}" id="amount_recieved" name="amount_recieved" >
                                        <span class="text-danger error_amount_recieved" style="display: none;">This field is required.</span>
                                    </div>
                                </div>
                                <div class="card-body g-3 row">
                                    <div class="col-12" align="center">
                                        <div class="d-grid gap-2 with-100">
                                          <button class="btn btn-primary submit"  type="button"><i class="bx bx-save"></i> Submit to Create Final Invoice/Bill</button>
                                      </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6" style="padding: 0 0 0 18px;">
                            <div class="card">
                                <div class="card-body g-3 row">
                                    <h5 class="mb-0">Additional Details</h5>
                                    <hr class="mb-2">
                                    {{--<div class="col-md-6">
                                        <label for="special_case" class="form-label">TPA/Corporate Name </label>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="tpa_corporate_id">
                                                <option value="">select Corporate</option>
                                                @foreach($TpaAccounts as $row)
                                                <option value="{{ $row->id ?? '' }}">{{ $row->name ?? '' }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>--}}
                                    <div class="col-md-6">
                                        <label for="special_case" class="form-label">Bill To </label>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="bill_to_account_id">
                                                <option value="{!! $customers['id'] ?? '' !!}">{!! $customers['name'] ?? '' !!}</option>
                                            </select>
                                        </div>
                                    </div>
                                    

                                    <div class="col-md-6">
                                        <label for="special_case" class="form-label">Ship From </label>
                                        <div class="input-group">
                                            <select class=" form-control" name="ship_from">
                                                <option value="{{ auth()->user()->getComapnyDetails->getCompanyAddress->address_1}}">{{auth()->user()->getComapnyDetails->getCompanyAddress->address_1}}</option>
                                                {{-- <option value="">Null</option> --}}
                                            </select>
                                            {{-- <input type="text" class="form-control" name="ship_from" value="{{ auth()->user()->getComapnyDetails->getCompanyAddress->address_1}}" placeholder="Ship From"> --}}
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="special_case" class="form-label">Ship To </label>
                                        <div class="input-group">
                                            <select class="single-select form-control" name="ship_to">
                                                <option value="{{ $accountAddress->address_line1 ?? '' }}">{{ $accountAddress->address_line1 ?? '' }}</option>
                                            </select>
                                            {{-- <input type="text" class="form-control" name="ship_to"  placeholder="Ship To" value="{{ $accountAddress->address_line1 ?? '' }}" > --}}
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="special_case" class="form-label">Sales Agent </label>
                                        <div class="input-group">
                                            {{-- <input type="text" class="form-control" name="sales_agent"  placeholder="Sales Agent"> --}}
                                            <select class="single-select form-control" name="sales_agent">
                                                <option value="">Null</option>
                                                @foreach($sales_agent as $list)
                                                <option value="{{ $list->id }}">{{ $list->type_name ?? '' }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="special_case" class="form-label">Delivery Agent </label>
                                        <div class="input-group">
                                            {{-- <input type="text" class="form-control" name="delivery_agent"  placeholder="Delivery Agent"> --}}
                                            <select class="single-select form-control" name="delivery_agent">
                                                <option value="">Null</option>
                                                @foreach($delivery_agent as $list)
                                                <option value="{{ $list->id }}">{{ $list->type_name ?? ''}}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="delivery_date" class="form-label">Delivery Date <span class="text-danger"><b>*</b></span></label>
                                        <input type="text" readonly class="form-control" id="delivery_date" name="delivery_date" aria-describedby="inputGroupPrepend" required>
                                        <span class="text-danger error_delivery_date" style="display: none;">This field is required.</span>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="special_case" class="form-label">Ref. No </label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" name="ref_no"  placeholder="Ref. No">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="due_reminder_date" class="form-label">Due Reminder Date <span class="text-danger"><b>*</b></span></label>
                                        <input type="text" readonly class="form-control" id="due_reminder_date" name="due_reminder_date" aria-describedby="inputGroupPrepend" required>
                                        <span class="text-danger error_due_reminder_date" style="display: none;">This field is required.</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<!--end row-->

@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>
  $(function() {
        $('#sample_receive_date').datepicker();
        $('#invoice_date').datepicker({
        format: "{!! $companyDateFormate??'dd-mm-yyyy' !!}",
        autoclose: true,
        //startDate: financialYearDates.fromDate,//optional
        //endDate: financialYearDates.toDate//optional
        }).datepicker("setDate", new Date());

        var currentDate = new Date();
        var formattedDate = currentDate.toISOString().split('T')[0];
        // $('#delivery_date').val(formattedDate).datepicker();
        $('#delivery_date').datepicker({
        format: "{!! $companyDateFormate??'dd-mm-yyyy' !!}",
        autoclose: true,
        }).datepicker("setDate", new Date());

        var currentDate = new Date();
        var formattedDate = currentDate.toISOString().split('T')[0];
        // $('#due_reminder_date').val(formattedDate).datepicker();
        $('#due_reminder_date').datepicker({
        format: "{!! $companyDateFormate??'dd-mm-yyyy' !!}",
        autoclose: true,
        }).datepicker("setDate", new Date());
    });

    $(document).ready(function(){
        fetch_cart();
        // $('.round_off_show').hide();
        $('#round_off').prop('checked', true);
        $('#round_off').change();
        var total_billing = $('#total_billing').val();
        $('.round_off_show').show();
        var roundOF =  Math.round(total_billing)
        var differenceAmount  = roundOF - total_billing;
        $('#final_total_billing_amount').val(roundOF);
        $('#round_off_amount').val(parseFloat(differenceAmount).toFixed(2));
        
        $('#round_off').change(function() {
            if ($(this).is(':checked')) {
                $(this).val(1);
                $('.round_off_show').show();
                var roundOF =  Math.round(total_billing)
                var differenceAmount  = roundOF - total_billing;
                $('#final_total_billing_amount').val(roundOF);
                $('#round_off_amount').val(parseFloat(differenceAmount).toFixed(2));
            } else {
                var roundOF = 0;
                $(this).val(0);
                $('.round_off_show').hide();
                $('#round_off_amount').val(roundOF);
            }
        });
    });

    function fetch_cart(){
      $.ajax({
        url:"{!! route('purchase-product-cart') !!}?page=billing",
        success:function(data){
            $('.cart_products').html('');
            $('.cart_products').html(data);
        }
      })
    }

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

        // if ($('[name="amount_recieved"]').val() > 0 && ($('[name="transaction_mode_id"]').val() == '' || $('[name="transaction_mode_id"]').val() == null)) {
        //   $('.error_transaction_mode_id').show();
        //   error = 1;
        // }
        // if ($('[name="payment_term_id"]').val() == '' || $('[name="payment_term_id"]').val() == null) {
        //   $('.error_payment_term_id').show();
        //   error = 1;
        // }
        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="supplier_invoice_no"]').val().trim() =='') {
          $('.error_supplier_invoice_no').show();
          $('[name="supplier_invoice_no"]').focus();
          error = 1;
        }

        

        if (error == 0) {

            $('#billing_form').submit();
        } else {
            $(this).Toastshow('error', 'Please fill all required fields!');
        }
    });

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

    $(document).on('change', '[name="payment_mode"]', function(){
        $.ajax({
          url     : '{!! route("purchase-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){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    $(document).on('focusout', '[name="special_discount"]', function(){
        $.ajax({
          url     : '{!! route("purchase-cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "type": 'billing',
                "special_discount": $(this).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);

                  if (response.data.due_balance_amount < 1) {
                    $(this).Toastshow('error', 'Balance Amount can not be in negative!');
                  }
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    $(document).on('change', '[name="discount_type"]', function(){
        $.ajax({
          url     : '{!! route("purchase-cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "type": 'billing',
                "discount_type": $(this).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);

                  if (response.data.due_balance_amount < 1) {
                    $(this).Toastshow('error', 'Balance Amount can not be in negative!');
                  }
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    // $(document).on('focusout', '[name="amount_recieved"]', function(){
    //     $.ajax({
    //       url     : '{!! route("purchase-cart-product-update") !!}',
    //       method  : 'post',
    //       data    : {
    //             "_token": $('meta[name ="csrf-token"]').attr('content'),
    //             "type": 'billing',
    //             "amount_recieved": $(this).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);
    //           }
    //       },
    //       error: function (data) {
    //         console.log("error ",data);
    //       }
    //     });
    // })

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

            $.ajax({
            url     : '{!! route("purchase-cart-product-update") !!}',
            method  : 'post',
            data    : {
                    "_token": $('meta[name ="csrf-token"]').attr('content'),
                    "type": 'billing',
                    "amount_recieved": sum_amount,
            },
            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);
                }
            },
            error: function (data) {
                console.log("error ",data);
            }
            });
            }
            })




    $(document).on('focusout', '[name="tax_per"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("purchase-cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('customer_id'),
                "tax_per": $(this).val(),
            },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    $(document).on('focusout', '[name="loose_qty"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("purchase-cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('customer_id'),
                "loose_qty": $(this).val(),
            },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    $(document).on('focusout', '[name="product_detail"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("purchase-cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('customer_id'),
                "product_detail": $(this).val(),
            },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    function updateCartQuantity(productId, quantity) {
        $.ajax({
            url: '{!! route("purchase-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": productId,
                "main_qty": quantity,
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function (response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function (data) {
                console.log("error ", data);
            }
        });
    }

    function updateCartLooseQuantity(productId, quantity) {
        $.ajax({
            url: '{!! route("purchase-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": productId,
                "loose_qty": quantity,
            },
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            success: function (response) {
                if (response.success) {
                    fetch_cart();
                }
            },
            error: function (data) {
                console.log("error ", data);
            }
        });
    }


    $(document).on('focusout', '.cart_products [name="product_price"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("purchase-cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('customer_id'),
                "product_price": $(this).val(),
          },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    $(document).on('focusout', '.cart_products [name="flat_discount"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("purchase-cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('customer_id'),
                "flat_discount": $(this).val(),
          },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    $(document).on('focusout', '.cart_products [name="per_discount"]', function(){
        var product_id = $(this).data('product_id');

        $.ajax({
          url     : '{!! route("purchase-cart-product-update") !!}',
          method  : 'post',
          data    : {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('customer_id'),
                "per_discount": $(this).val(),
          },
          headers:
          {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
          success : function(response){
              if(response.success){
                  fetch_cart();
              }
          },
          error: function (data) {
            console.log("error ",data);
          }
        });
    })

    /*********delete data**********/
    $("body").on("click",'.deleteDataCustom', function(event){
          dataString   = {"id":$(this).data('id')};
          var UrlValue = $(this).data('url');
          var btn      = $(this);

          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('customer_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);
                          fetch_cart();
                      }else{
                          var ErroMsg = $(this).printErrorMsg(response.message);
                          $(this).Toastshow('error',ErroMsg);
                      }
                  },
                  error: function (data) {
                    console.log("error ",data);
                  }
              });
              }
          });
    });

    //paument mode
    $(document).ready(function() {
        // Initialize payment mode dropdown as empty
        $('select[name="payment_mode_id"]').empty();

        // Handle change event on transaction mode dropdown
        $('select[name="transaction_mode_id"]').on('change', function() {
            var transactionModeId = $(this).val();
            if (transactionModeId) {
                $.ajax({
                    url: '{{ route("getPaymentModes") }}',
                    type: "GET",
                    data: {
                        transaction_mode_id: transactionModeId
                    },
                    dataType: "json",
                    success: function(data) {
                        $('select[name="payment_mode_id"]').empty();
                        $('select[name="payment_mode_id"]').append('<option value="">Select Payment Mode</option>');
                        $.each(data, function(key, value) {
                            $('select[name="payment_mode_id"]').append('<option value="' + value.id + '">' + value.mode + '</option>');
                        });
                    },
                    error: function(xhr, status, error) {
                        console.error(xhr.responseText);
                    }
                });
            } else {
                // If no transaction mode is selected, clear payment mode dropdown
                $('select[name="payment_mode_id"]').empty();
            }
        });





         // Handle change event on Bill To mode dropdown
         $('select[name="tpa_corporate_id"]').on('change', function() {
            var tpa_corporate_id = $(this).val();
            var customerId = "{!! $customers['id'] ?? '' !!}";
            if (tpa_corporate_id) {
                $.ajax({
                    url: '{{ route("getBillTo") }}',
                    type: "GET",
                    data: {
                        tpa_corporate_id: tpa_corporate_id,
                        customer_id:customerId
                    },
                    dataType: "json",
                    success: function(data) {
                        $('select[name="bill_to_account_id"]').empty();
                        $('select[name="bill_to_account_id"]').append('<option value="">Select Bill To Account</option>');
                        $.each(data, function(key, value) {
                            $('select[name="bill_to_account_id"]').append('<option value="' + value.id + '">' + value.name + '</option>');
                        });
                    },
                    error: function(xhr, status, error) {
                        console.error(xhr.responseText);
                    }
                });
            } else {
                // If no transaction mode is selected, clear payment mode dropdown
                $('select[name="bill_to_account_id"]').empty();
            }
        });
    });
</script>
@endsection