@extends('layouts.app')
@section('title','IPD Billings')
@section('pages')
<style type="text/css">
    .breadcrumb-title {
        border: none;
    }

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

    #total_billing {
        border-color: #5cff80;
        background-color: #e0ffe2;
        font-size: 16px;
    }

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

    #amount_recieved {
        border: 2px solid #fff579;
        background-color: #fff;
        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> IPD Admission Billings</div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="{!! route('ipd-admissions.show', $ipd_admission_id) !!}" 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>

                    <form class="row auto-width mt-0" action="{{ route('ipd-billings.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-6 mt-3">
                                    <h5 class="mb-0">Intent for IPD 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" id="round_off" value="0">
                                    </div>--}}
                                        {{-- <input type="hidden" name="bill_type" value="{{ $bill_type }}">
                                        <input type="hidden" name="ipd_admission_id" value="{{ $ipd_admission_id }}"> --}}
                                        <input type="hidden" name="ipd_admission_id" value="{{ $ipd_admission_id }}">
                                    <hr class="mb-2">
                                    <div class="col-md-6">
                                        <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>Patient</small></h6>
                                                    </div>
                                                    <div class="info">
                                                        <p class="mb-0">{!! $patients['name'] ?? '' !!}</p>
                                                        <p class="mb-0">{!! isset($patients['gender']) && $patients['gender'] != '' ? ' ' . $patients['gender'] : '' !!}{!! isset($patients['date_of_birth']) && $patients['date_of_birth'] != '' ? ', ' . age($patients['date_of_birth']) . ' Years' : '' !!}</p>
                                                        <p class="mb-0">{!! isset($patients['phone_no']) && $patients['phone_no'] != '' ? ' ' . $patients['phone_no'] : '' !!}</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <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>
                                    <div class="col-md-6">
                                        <label for="invoice_date" class="form-label">Intent for IPD 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="">
                                        <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">Total Intent 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>
                                            <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="special_case" class="form-label">Payment Mode <span class="text-danger"><b>*</b></span></label>
                                <div class="input-group">
                                    <select class="single-select form-control" name="payment_mode_id">
                                        @foreach($accounting_group as $list)
                                        <option value="{{ $list->id }}" {!! isset($data['payment_mode_id']) && $data['payment_mode_id']=$list->id ? 'selected' : ($list->is_payment_mode == 1 ? 'selected' : '') !!}>{{ $list->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <span class="text-danger error_payment_mode_id" 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">
                                                    {{$list->name ?? ''}}
                                                    <input type="hidden" class="form-control" name="payment_mode[{!! $list->id !!}][mode_id]" value="{!! $list->id !!}" style="text-align: right;">
                                                </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">
                                <label for="special_discount" class="form-label">Special Discount</label>
                                <div class="input-group">
                                    <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>
                                    <input type="text" class="form-control" id="special_discount" value="{!! $data['special_discount'] !!}" name="special_discount" style="text-align: right;">
                                </div>
                                <span class="text-danger error_special_discount" style="display: none;">This field is required.</span>
                            </div>


                            <div class="col-md-6">
                                <label for="other_charges" class="form-label">Other Charges</label>
                                <input type="text" class="form-control" id="other_charges" name="other_charges" value="{!! isset($data['other_charges']) ? convertDecimelPoint($data['other_charges']) : '' !!}" placeholder="Other Charges">
                            </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">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 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">Special Case </label>
                                        <div class="input-group">
                                            <select name="special_case" class="single-select form-control">
                                                @foreach($special_cases as $key => $value)
                                                    <option value="{!! $value->id !!}" {!! isset($data['special_case']) && $data['special_case'] == $value->id ? 'checked' : '' !!}>{!! $value->name !!}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="sample_barcode" class="form-label">Sample Barcode</label>
                                        <input type="text" class="form-control" name="sample_barcode" value="{!! $data['sample_barcode'] ?? '' !!}" placeholder="Sample Barcode">
                                    </div>
                                    <div class="col-md-6">
                                        <div>
                                            <label for="payment_mode" class="form-label">Sample Receive Date </label>
                                        </div>
                                        <div class="input-group">
                                            {{-- <input type="text" class="form-control" id="sample_receive_date" name="sample_receive_date" aria-describedby="inputGroupPrepend" value="{!! $data['sample_receive_date'] !!}"> --}}
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="special_discount" class="form-label">Sample Receive Time</label>

                                        <input type="time" class="form-control" name="sample_receive_time" value="{!! $data['sample_receive_time'] ?? '' !!}">
                                    </div> -->
                        <div class="col-md-12">
                            <label for="due_balance_amount" class="form-label">Any Ref. No</label>
                            <input id="reff_no" class="form-control" type="text" name="reff_no" autocomplete="off" placeholder="Ref. No" value="{!! $data['reff_no'] ?? '' !!}">
                        </div>
                        <!-- <div class="col-md-6">
                                        <label for="special_case" class="form-label">Bussiness Source </label>
                                        <div class="input-group">
                                            <select name="bussiness_source" class="single-select form-control">
                                                @foreach($bussiness_source as $key => $value)
                                                    <option value="{!! $value->id !!}" {!! isset($data['bussiness_source']) && $data['bussiness_source'] == $value->id ? 'checked' : (isset($data['bussiness_source']) && $data['bussiness_source'] == $value->id ? 'checked' : '') !!}>{!! $value->enquiry_source_name !!}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                    </div> -->
                        <div class="col-md-12">
                            <label for="sale_remarks" class="form-label">Billing Remarks</label>
                            <textarea name="sale_remarks" id="sale_remarks" rows="1" class="form-control" autocomplete="off" placeholder="Billing Remarks">{!! $data['sale_remarks'] ?? '' !!}</textarea>
                        </div>
                        <!-- <div class="col-md-12">
                                        <label for="sale_remarks" class="form-label">Remarks for Technician</label>
                                        <textarea name="remarks_for_technician" id="remarks_for_technician" rows="1" class="form-control" autocomplete="off" placeholder="Technician Remarks">{!! $data['remarks_for_technician'] ?? '' !!}</textarea>
                                    </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());
    });
    $(document).ready(function() {
        fetch_cart();

        $('.round_off_show').hide();
        var total_billing = $('#total_billing').val();
        $('#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('ipd-billing-product-cart', $ipd_id) !!}?page=billing",
            success: function(data) {
                $('.cart_products').html('');
                $('.cart_products').html(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="payment_mode_id"]').val().trim() == '') {
        //     $('.error_payment_mode_id').show();
        //     error = 1;
        // }
        // if ($('[name="payment_term_id"]').val().trim() == '') {
        //     $('.error_payment_term_id').show();
        //     error = 1;
        // }
        // if ($('[name="due_balance_amount"]').val().trim() == '') {
        //     $('.error_due_balance_amount').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('focusout', '[name="invoice_date"]', function() {
        $.ajax({
            url: '{!! route("ipd-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("ipd-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("ipd-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("ipd-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("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("ipd-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', '.cart_products [name="product_price"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("ipd-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('patient_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="per_discount"]', function() {
        var product_id = $(this).data('product_id');

        $.ajax({
            url: '{!! route("ipd-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('patient_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);
            }
        });
    })

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

        $.ajax({
            url: '{!! route("ipd-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('patient_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("ipd-cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('patient_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('patient_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);
                    }
                });
            }
        });
    });
</script>
@endsection
