@extends('layouts.app')
@section('title','Receipt Vouchers')
@section('pages')
<style type="text/css">
    .clear {
        clear: both;
        margin-top: 20px;
    }

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

    #add_reference i {
        height: 20px;
        width: 20px;
        background: #0d6efd25;
        color: #0d6efd;
        text-align: center;
        border-radius: 50px;
        line-height: 20px;
    }

    .add_btn {
        height: 40px;
        width: 40px;
        font-size: 16px;
        border-radius: 0 3.5px 3.5px 0;
        padding: 0;
    }

    .custom_grid {
        padding-left: 1rem;
        padding-right: 1rem;
    }

    .custom_grid .input-group {
        position: relative;
    }

    .custom_grid .input-group .form-label {
        position: absolute;
        top: -10px;
        left: 5px;
        font-size: 12px;
        padding: 0px 8px;
        background-color: #f7f8fa;
        z-index: 5;
    }

    .custom_grid .input-group .form-control.br-0 {
        border-radius: 0;
    }

    .custom_grid .btn {
        font-size: 22px;
        padding: 0.15rem 0.75rem;
        border-top-left-radius: 0px;
        border-bottom-left-radius: 0px;
    }

    .select2-container--bootstrap4 .select2-selection {
        border-top-right-radius: 0px;
        border-bottom-right-radius: 0px;
    }

    #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 #3be94d;
        background-color: #fff;
        font-weight: 600;
        font-size: 16px;
    }

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

    .amount_tds {
        border: 2px solid #3f7fdd;
        font-weight: 600;
        font-size: 16px;
    }

    .amount_expenses {
        border: 2px solid #545353;
        font-weight: 600;
        font-size: 16px;
    }
</style>


<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> Receipt Vouchers</div>
    <div class="ps-3">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb mb-0 p-0">
                <li class="breadcrumb-item pe-3" aria-current="page"><a class="text-danger"><b>
                            @if($voucher_type=='pathology')
                            {{ 'Pathology' }}
                            @elseif($voucher_type=='ipd-invoice')
                            {!! 'IPD Invoice' !!}
                            @else
                            {!! 'OPD Booking' !!}
                            @endif

                            ({!! $sale_invoice->main_invoice_no??'' !!})
                            @if(isset($sale_invoice->invoice_date))
                            ({!! $sale_invoice->invoice_date?formatedDate($sale_invoice->invoice_date):'' !!})
                            @endif
                        </b></a></li>
            </ol>
        </nav>
    </div>
    <div class="ms-auto">
        <div class="btn-group">
            <a href="javascript:history.back()" class="btn btn-info"><i class="bx bx-arrow-back ms-0 me-1"></i>Back</a>
            &nbsp;
            <a href="{!! isset($slip_url)?route($slip_url,$id):'#' !!}" target="_blank" class="btn btn-success"><i class="bi bi-receipt text-white ms-0 me-1"></i>View Voucher</a>
        </div>
    </div>
</div>
<!--end breadcrumb-->

<div class="row auto">
    <div class="col-xl-12 mx-auto">

        <form class="auto-width create_billing" id="create_journal_voucher_form" action="{{ isset($data) && isset($data->id) ? route('update-billing-vouchers', ['id'=>$data->id,'voucher_type'=>$voucher_type,'payment_type'=>$payment_type]) :'#' }}" method="post" enctype='multipart/form-data'>
            <!-- For validation comment on -->
            <!-- <form class="row g-3 was-validated"> -->

            @php $tdsAmount = 0;
            $ids= []; $tdsLastId='';
            @endphp
            @if(isset($data->accountReceiptTransaction))
            @foreach($data->accountReceiptTransaction as $lists)
            @if($lists->account_id==$accounting_tds->id)
            @php $tdsAmount = trim($lists->amount);
            $tdsLastId = $lists->id;
            @endphp
            @endif
            @php $ids[] = $lists->account_id; @endphp
            @endforeach
            @endif

            @php $expensesAmount = 0; $expensesLastId=''; @endphp
            @foreach($accounting_expenses as $keys => $list)
            @if(isset($list->chart_of_expanses))
            @foreach($list->chart_of_expanses as $value)
            @if(isset($data->accountReceiptTransaction))
            @foreach($data->accountReceiptTransaction as $lists)
            @if($value->id==$lists->account_id)
            @php $expensesAmount = trim($lists->amount);
            $expensesLastId = $lists->id;
            @endphp
            @endif
            @endforeach
            @endif
            @endforeach
            @endif
            @endforeach

            @csrf
            <div class="card">
                <div class="card-body pt-2 ps-3" style="border-radius:0px;">
                    <div class="row align-items-center">
                        @if(!isset($redirect) || $redirect != 'lab-billings')
                        <div class="col-md-3">
                            <div>
                                <label class="form-label">Party Account Name <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="" id="account_id" class="accounts-select form-control" placeholder="Search Account" value="{!! $sale_invoice->getPatient->name ?? '' !!}">
                                <ul class="searchResult"></ul>
                            </div>
                            <span class="text-danger error_account_id" style="display:none;">This field is required.</span>
                        </div>
                        @else
                       
                        <div class="col-md-3">
                            <div>
                                <label class="form-label">Account Name</label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" readonly class="form-control" value="{!! $sale_invoice->getPatient->name ?? '' !!}">
                                <ul class="searchResult"></ul>
                            </div>
                            <span class="text-danger error_account_id" style="display:none;">This field is required.</span>
                        </div>
                        @endif
                        <div class="col-md-3">
                            <div>
                                <label class="form-label">Receipt Date <span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <input type="text" name="receipt_date" id="receipt_date" class="doctor-select form-control datepickers" placeholder="Date" value="{{ isset($data->receipt_date)? formatedDate($data->receipt_date) : '' }}" readonly="">
                            </div>
                            <span class="text-danger error_receipt_date" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-2">
                            <div>
                                <label class="form-label">Financial Year<span class="text-danger"><b>*</b></span></label>
                            </div>
                            <div class="input-group autocomplete">
                                <select class="single-select form-control br-0" id="financial_year_id" name="financial_year_id" required>
                                    @foreach($financialYears as $list)
                                    <option value="{{ $list->financialyearid}}" {!! isset($data->financial_year_id) && $data->financial_year_id == $list->financialyearid ? 'selected' : '' !!}>{{$list->financial_year_name}}</option>
                                    @endforeach
                                </select>
                            </div>
                            <span class="text-danger error_financial_year_id" style="display:none;">This field is required.</span>
                        </div>
                        <div class="col-md-4 mt-3" style="text-align: right;display: flex; justify-content: space-between;">
                            <label for="validationCustomOrder" style="margin-top: 5px;" class="form-label"><b>TDS Applicable?</b></label><br>
                            <input name="tds_applicable" class="form-check-inputFeatured btn-lg tds_applicable" type="checkbox" id="tds_applicable" {!! isset($tdsAmount) && $tdsAmount>0?'checked':'' !!} value="{!! isset($tdsAmount) && $tdsAmount>0?1:0 !!}">
                            <label for="validationCustomOrder" style="margin-top: 5px;margin-left: 16%" class="form-label"><b>Loss/Expense?</b> </label><br>
                            <input name="expenses_applicable" class="form-check-inputFeatured btn-lg expenses_applicable" type="checkbox" id="expenses_applicable" {!! isset($expensesAmount) && $expensesAmount>0?'checked':'' !!} value="{!! isset($expensesAmount) && $expensesAmount>0?1:0 !!}">
                        </div>
                    </div>
                </div>
            </div>
            <div class="card">
                <div class="card-body pt-2 ps-3" style="border-radius:0px;">
                    <div class="row align-items-center">
                        <div class="col-12 justify-content-center mb-3">
                            <div style="" class="accordion-item">
                                <h2 class="accordion-header" id="panelsStayOpen-headingTwo">
                                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseTwo" aria-expanded="false" aria-controls="panelsStayOpen-collapseTwo">
                                    @php $totalReturn = isset($returnTransactionSummery['totalBilling'])?$returnTransactionSummery['totalBilling']:0; @endphp
                                        Received History | Total Voucher Amount : <b>{!! convertDecimelPoint(round($transactionSummery['totalBilling']-$transactionSummery['discountAmount']-$totalReturn)) !!}</b>
                                        &nbsp;

                                        <span style="margin-left: 48%;">Received Amount : <b>{!! convertDecimelPoint(round($transactionSummery['receivedAmount'])) !!}</b></span>
                                    </button>
                                </h2>
                                <div style="" id="panelsStayOpen-collapseTwo" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-headingTwo">
                                    <div class="accordion-body">
                                       <x-TransactionSummary :transactionSummery="$transactionSummery" :transactionHistory="$transactionHistory" :totalReturnAmount="$totalReturn"/>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="cart_products">
                <div class="card style_table shadow-none" style="margin-bottom:0.8rem;">
                    <div class="card-body pb-0">
                        <div class="table-responsive">
                            <table id="example" class="table table-bordered align-middle" style="width:100%">
                                <thead class="table-light">
                                    @php
                                    $collection_amount = $sale_invoice->billing_amount - $sale_invoice->discount_amount-$totalReturn;
                                    @endphp
                                    <input type="hidden" id="sale_invoice_received_amount" value="{!! $sale_invoice->received_amount !!}">
                                    <tr>
                                        <th class="thbutton">Sr No.</th>
                                        <th class="text-start">Transaction Mode </th>
                                        <th class="text-start">Receive Mode</th>
                                        <th class="text-start">Transaction Referrence</th>
                                        <th style="text-align: right;">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @php $ids = []; $lastKey = 0; $totalAmount = 0; @endphp

                                    @foreach($accounting_group as $key => $list)

                                    <tr class="cart-products" data-patient_id="{{$list['account_id']}}">
                                        <td class="text-center">{{ $key + 1 }}</td>
                                        <td class="text-start">{{$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 class="text-start">
                                            <input type="text" name="payment_mode[{!! $list->id !!}][transaction_referrence]" class="form-control" placeholder="Transaction Referrence">
                                            <input type="hidden" name="payment_mode[{!! $list->id !!}][mode_id]" class="form-control" value="{!! $list->id !!}">
                                        </td>
                                        <td style="text-align: center;">
                                            @php $pAmount = 0;$lastId=""; @endphp
                                            @if(isset($data->accountReceiptTransaction))
                                            @foreach($data->accountReceiptTransaction as $lists)
                                            @if($lists->account_id==$list->id)
                                            @php $pAmount = trim($lists->amount);
                                            $lastId = $lists->id;
                                            $totalAmount+=$pAmount;
                                            @endphp
                                            @endif
                                            @endforeach
                                            @endif
                                            <input type="hidden" class="form-control" name="payment_mode[{!! $list->id !!}][last_id]" value="{!! isset($lastId)?$lastId:'' !!}" style="text-align: right;">
                                            <input type="number" class="form-control amount amount_collection" name="payment_mode[{!! $list->id !!}][amount]" value="{!! trim(convertDecimelPoint($pAmount)) !!}" style="text-align: right;">
                                        </td>
                                    </tr>
                                    @php $lastKey++; @endphp
                                    @endforeach
                                    <input type="hidden" id="last_sr_no" value="{!! $lastKey !!}">
                                    <tr class="cart-products td_show">
                                        <td class="text-center" id="sr_tds">{!! isset($tdsAmount) && $tdsAmount>0?'3':'' !!}</td>
                                        <td class="text-start">{{$accounting_tds->name ?? ''}}</td>
                                        <input type="hidden" name="payment_mode[{!! $accounting_tds->id !!}][mode_id]" class="form-control" value="{!! $accounting_tds->id !!}">
                                        <td class="text-start">
                                            <select class="form-control" name="payment_mode[{!! $accounting_tds->id !!}][transaction_mode_id]">
                                                <option value="{!! $accounting_tds->id !!}" selected>{!! $accounting_tds->name !!}</option>
                                            </select>
                                        </td>
                                        <td class="text-start">
                                            <input type="text" name="payment_mode[{!! $accounting_tds->id !!}][transaction_referrence]" class="form-control" placeholder="Transaction Referrence">
                                        </td>
                                        <td style="text-align: center;">
                                            <input type="hidden" class="form-control" name="payment_mode[{!! $accounting_tds->id !!}][last_id]" value="{!! isset($tdsLastId)?$tdsLastId:'' !!}" style="text-align: right;">
                                            <input type="number" class="form-control amount amount_tds" name="payment_mode[{!! $accounting_tds->id !!}][amount]" value="{!! trim(convertDecimelPoint($tdsAmount)) !!}" style="text-align: right;">
                                        </td>
                                    </tr>

                                    @foreach($accounting_expenses as $keys => $list)
                                    <tr class="cart-products tr_expenses">
                                        <td class="text-center" id="sr_expenses">
                                            @if($tdsAmount>0 && $expensesAmount>0)
                                            4
                                            @elseif($tdsAmount>0)
                                            3
                                            @endif
                                        </td>
                                        <td class="text-start">{{$list->name ?? ''}}</td>
                                        <td class="text-start">
                                            <select class="form-control" name="payment_mode[{!! $list->id !!}][mode_id]">
                                                <option value=" ">Select Expense Account</option>
                                                @if(isset($list->chart_of_expanses))
                                                @foreach($list->chart_of_expanses as $value)
                                                <option value="{!! $value->id !!}" {!! isset($ids) && in_array($value->id, $ids)?'selected':'' !!}>{!! $value->name !!}</option>
                                                @endforeach
                                                @endif
                                            </select>
                                        </td>
                                        <td class="text-start">
                                            <input type="text" name="payment_mode[{!! $list->id !!}][transaction_referrence]" class="form-control" placeholder="Transaction Referrence">
                                        </td>
                                        <td style="text-align: center;">
                                            <input type="hidden" class="form-control" name="payment_mode[{!! $list->id !!}][last_id]" value="{!! isset($expensesLastId)?$expensesLastId:'' !!}" style="text-align: right;">
                                            <input type="number" class="form-control amount amount_expenses" name="payment_mode[{!! $list->id !!}][amount]" value="{!! isset($expensesAmount) && $expensesAmount>0 ?convertDecimelPoint($expensesAmount):0 !!}" style="text-align: right;">
                                        </td>
                                    </tr>
                                    @endforeach
                                    <tr>
                                        <td colspan="3"></td>
                                        <td class="text-start text-end">Total Received</td>
                                        <td class="text-start">
                                            <input readonly type="number" class="form-control received_amount" id="amount_recieved" name="received_amount" value="{!! convertDecimelPoint($totalAmount+$tdsAmount+$expensesAmount) !!}" style="text-align: right;">
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="3"></td>
                                        <td class="text-start text-end">Total Due</td>
                                        <td class="text-start">
                                            <input type="number" class="form-control due_amount" name="due_amount" id="due_balance_amount" value="{!! isset($transactionSummery['dueAmount']) ? convertDecimelPoint(round($transactionSummery['totalBilling']-$transactionSummery['discountAmount']-$transactionSummery['receivedAmount']-$totalReturn)) : 0 !!}" style="text-align: right;" readonly>

                                            <input type="hidden" class="form-control" id="actual_due_balance_amount" value="{!! isset($transactionSummery['dueAmount']) ? convertDecimelPoint(round($transactionSummery['totalBilling']-$transactionSummery['discountAmount']-$transactionSummery['receivedAmount']-$totalReturn)) : '' !!}" style="text-align: right;" readonly>
                                            <input type="hidden" class="form-control" id="actual_received" value="{!! round($totalAmount+$tdsAmount+$expensesAmount) !!}" style="text-align: right;" readonly>
                                            <span class="text-danger error_due_amount" style="display:none;">Due Amount can not be in negative!</span>
                                        </td>
                                    </tr>
                                    <input type="hidden" class="collection_amount" value="{!! round($collection_amount) ?? '' !!}">


                                    <tr>
                                        <td colspan="4"></td>
                                        <td class="text-start">
                                            <div class="col-12 mt-4 mb-4" align="center">
                                                <div class="">
                                                    <input type="hidden" name="account_id" value="{!! isset($debitTransaction->account_id) ? $debitTransaction->account_id : (isset($sale_invoice->patient_id) ? $sale_invoice->patient_id : '') !!}">
                                                    <input type="hidden" name="redirect" value="{!! $redirect ?? 'receipt' !!}">
                                                    <input type="hidden" class="form-control total_amount" name="total_amount" value="{!! isset($debitTransaction->amount) ? $debitTransaction->amount : (isset($transactionSummery['totalBilling']) ? $transactionSummery['totalBilling']-$transactionSummery['discountAmount']-$totalReturn : '') !!}">
                                                    <button class="btn btn-md btn-primary save_button" type="button" style="width: 100%;height: 35px;"><i class="bx bx-save"></i> Submit To Save Receipt Voucher</button>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

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

            <div class="card style_table">
                <div class="row custom_grid align-items-end gx-0 mt-4 mb-3">
                    <div class="col-md-12">
                        <div>
                            <label class="form-label">Note / Description </label>
                        </div>
                        <div class="input-group">
                            <textarea class="form-textarea" name="remarks" id="remarks" rows="3">{{ isset($data->remarks)? $data->remarks : "" }}</textarea>
                        </div>
                        <span class="text-danger error_description" style="display:none;">This field is required.</span>
                    </div>

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

    </div>
</div>
<!--end row-->

@endsection

@section('js')
<script type="text/javascript" src="{{ asset('admin/plugins/datepicker/js/bootstrap-datepicker.js') }}"></script>

<script>
     $(function() {
        // $('.datepickers').datepicker();
        $('.datepickers').datepicker({
        autoclose: true,
        format: "{!! $companyDateFormate??'dd-mm-yyyy' !!}",
        });
    });
    $(document).on('click', '.save_button', function(e) {
        e.preventDefault();

        //$('.error_voucher_no').hide();
        $('.error_receipt_date').hide();
        $('.error_account_id').hide();
        $('.error_due_amount').hide();
        //$('.error_description').hide();
        /*$('.error_details_narration').hide();*/
        $('.error_duplicate_voucher_no').hide();
        var error = 0;


        if ($('[name="receipt_date"]').val().trim() == '' || $('[name="receipt_date"]').val() == undefined) {
            $('.error_receipt_date').show();
            error = 1;
        }

        if ($('[name="account_id"]').val() == '' || $('[name="account_id"]').val() == undefined) {
            $('.error_account_id').show();
            error = 1;
        }

        @if(isset($redirect) && $redirect == 'lab-billings')
        if ($('[name="due_amount"]').val() < 0) {
            $('.error_due_amount').show();
            error = 1;
            // toastr.error("Due Amount can not be negative!", 'Error!');
        }
        if ($('[name="received_amount"]').val() == '') {
            error = 1;
            toastr.error("Received Amount can not be empty!", 'Error!');
        }
        @endif

        /*if ($('#remarks').val() == '' || $('#remarks').val() == undefined) {
          $('.error_description').show();
          error = 1;
        }*/
        var totalAmount = 0;
        $('.amount').each(function() {
            totalAmount += parseFloat($(this).val()) || 0;
        });

        if (totalAmount == '' || totalAmount == 0) {
            toastr.error('Transaction amount can not be 0!', 'Error!');
            error = 1;
        }

        if (error == 0) {
            $('.create_billing').submit()
        }
    });

    $(document).on('change input', '.amount', function(e) {
        var totalAmount     = 0;
        var setZero         = 0;
        var received_amount = 0;

        $('.amount').each(function() {
            totalAmount += parseFloat($(this).val()) || 0;
        });

        //console.log(totalAmount);
        var actualDue       = $('#actual_due_balance_amount').val();
        var actual_received = $('#actual_received').val();
        var actual_amount   = parseInt(actualDue) + parseInt(actual_received);
        $dueAmount          = actual_amount - totalAmount;
        console.log(actualDue);
        console.log(actual_received);
        console.log(actual_amount);
        console.log($dueAmount);

        if ($dueAmount < 0) {
            $('.error_due_amount').show();
            error = 1;

            // $(this).val(actualDue);
        } else {
            $('.error_due_amount').hide();
            $('.due_amount').val($dueAmount);

            var total = parseInt(totalAmount);
            $('[name="total_amount"]').val(total);
            $('[name="received_amount"]').val(total);
        }
    });

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

        //$('.error_voucher_no').hide();
        $('.error_transaction_date').hide();
        $('.error_account_id').hide();
        //$('.error_description').hide();
        /*$('.error_details_narration').hide();*/
        $('.error_duplicate_voucher_no').hide();
        var error = 0;
        /*
        if ($('input[name="voucher_no"]').val().trim() == '') {
          $('.error_voucher_no').show();
          error = 1;
        }
        */
        if ($('[name="transaction_date"]').val().trim() == '' || $('[name="transaction_date"]').val() == undefined) {
            $('.error_transaction_date').show();
            error = 1;
        }
        if ($('[name="account_id"]').val() == '' || $('[name="account_id"]').val() == undefined) {
            $('.error_account_id').show();
            error = 1;
        }

        if ($('#remarks').val() == '' || $('#remarks').val() == undefined) {
            $('.error_description').show();
            error = 1;
        }

        /*if ($('[name="details_narration"]').val() == '' || $('[name="details_narration"]').val() == undefined) {
          $('.error_details_narration').show();
          error = 1;
        }*/
        /*var productIds = $('.cart-products').map(function() {
            return $(this).data('voucher_no').toString();
        }).get();
        */
        if (error == 0) {
            let formdata = new FormData($('.create_billing')[0]);

            $.ajax({
                    url: $('.create_billing').attr('action'),
                    data: formdata,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function(response) {
                        if (response.success === true) {
                            toastr.success(response.message, 'Success.');
                            fetch_cart();

                            $('#details_narration').val('');
                            $('#account_id').val('');
                            $('[name="debit"]').val('');
                            $('[name="credit"]').val('');
                            $('[name="account_id"]').val('');

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

        error = 1;
    })

    $(document).on('keyup', '.amount', function(e) {
        e.preventDefault();
        if (e.target.name == 'debit') {
            $('[name="debit"]').val($.trim(this.value));
            $('[name="credit"]').val();
        } else {
            $('[name="credit"]').val($.trim(this.value));
            $('[name="debit"]').val();
        }
    });

    $(document).ready(function() {
        var tdsval = $('#tds_applicable').val();
        var expensesval = $('#expenses_applicable').val();

        if (tdsval == 1) {
            $('.td_show').show();
        } else {
            $('.td_show').hide();

        }
        if (expensesval == 1) {
            $('.tr_expenses').show();
        } else {
            $('.tr_expenses').hide();
        }


        $('#tds_applicable').change(function() {
            var sr = $('#last_sr_no').val();
            if ($(this).is(':checked')) {
                var newsr = parseInt(sr) + 1;
                $('#last_sr_no').val(newsr);
                $('#sr_tds').html(newsr)
                $(this).val(1);

                $('.td_show').show();
            } else {
                $(this).val(0);
                var newsr = parseInt(sr) - 1;
                $('#last_sr_no').val(newsr);
                $('#sr_tds').html(newsr)
                $('.td_show').hide();
            }
        });

        $('#expenses_applicable').change(function() {
            var sr = $('#last_sr_no').val();
            if ($(this).is(':checked')) {
                var newsr = parseInt(sr) + 1;
                $('#last_sr_no').val(newsr);
                $(this).val(1);
                $('#sr_expenses').html(newsr)
                $('.tr_expenses').show();
            } else {
                var newsr = parseInt(sr) - 1;
                $('#last_sr_no').val(newsr);
                $('#sr_expenses').html(newsr)
                $(this).val(0);
                $('.tr_expenses').hide();
            }
        });




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

                $.ajax({
                    url: "{{ route('journal-voucher-search-accounts') }}",
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'get_accounts_for_journal_voucher',
                        search_text: request.term
                    },
                    success: function(json) {
                        ;
                        if (json.error) {
                            $('[name="account_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="account_id"]').val(ui.item.id);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function(ul, item) {
            ;
            return $("<li>")
                .append("<a>" + item.name + "</a>")
                .appendTo(ul);
        };
    });

    const patientSelect = document.querySelector(".accounts-select");
    const querySelector = document.querySelector(".searchResult");

    document.addEventListener("click", (event) => {
        if (event.target !== patientSelect && event.target !== querySelector) {
            $(".searchResult").empty();
        }
    });

    $(document).on('click', '#create_patient', function() {
        $('#commonModalLabel').text('Add New Patient');
        $('.save_button_span').text('Save Patient');
        $.ajax({
            url: "{!! route('patient-account-create') !!}",
            success: function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
                reinitializeTelInput();
                $('[name="date_of_birth"]').datepicker('destroy');

                $('[name="date_of_birth"]').datepicker({
                        "dateFormat": "dd-mm-yy",
                        "maxDate": '0',
                        "changeMonth": true,
                        "changeYear": true
                    }).datepicker("setDate", 'now')
                    .on('changeDate', function(ev) {
                        $(this).datepicker('hide');
                    })
                    .on('focusout', function(ev) {
                        $(this).datepicker('hide');
                    });
            }
        })
    })

    $(document).on('click', '#create_doctor', function() {
        $('#commonModalLabel').text('Add New Doctor');
        $('.save_button_span').text('Save Doctor');
        $.ajax({
            url: "{!! route('doctor-account-create') !!}",
            success: function(data) {
                $('#commonModal').find('.modal-body').html('');
                $('#commonModal').find('.modal-body').html(data);
                reinitializeTelInput();
                $('[name="date_of_birth"]').datepicker('destroy');

                $('[name="date_of_birth"]').datepicker({
                        "dateFormat": "dd-mm-yy",
                        "maxDate": '0',
                        "changeMonth": true,
                        "changeYear": true
                    }).datepicker("setDate", 'now')
                    .on('changeDate', function(ev) {
                        $(this).datepicker('hide');
                    })
                    .on('focusout', function(ev) {
                        $(this).datepicker('hide');
                    });
            }
        })
    })

    $(document).on('click change', '#account_id', function() {
        $('[name="search_product"]').val('');
        $('.create_billing [name="product_price"]').val('');
        $('#search_product').val('');
    })

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

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

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

        $.ajax({
            url: '{!! route("cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('voucher_no'),
                "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("cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('voucher_no'),
                "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("cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('voucher_no'),
                "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("cart-product-update") !!}',
            method: 'post',
            data: {
                "_token": $('meta[name ="csrf-token"]').attr('content'),
                "id": $(this).data('voucher_no'),
                "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('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) {
                            toastr.success(response.message, 'Success.');
                            fetch_cart();;
                        } else {
                            var ErroMsg = $(this).printErrorMsg(response.message);
                            $(this).Toastshow('error', ErroMsg);
                        }
                    },
                    error: function(data) {
                        console.log("error ", data);
                    }
                });
            }
        });
    });

    function getAge(birthdate) {
        if (birthdate != '' && birthdate != null && birthdate != undefined) {
            var birthdateObj = new Date(birthdate);
            var now = new Date();
            var age = now.getFullYear() - birthdateObj.getFullYear();

            // Adjust age if birthday hasn't occurred this year yet
            if (now.getMonth() < birthdateObj.getMonth() || (now.getMonth() === birthdateObj.getMonth() && now.getDate() < birthdateObj.getDate())) {
                age--;
            }
            return age;
        }
    };
</script>
@endsection