<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    @include('layout.header')
    <link rel="stylesheet" href="{{url(env("APP_URL").'storage/assets/libs/lightgallery/lightgallery.css')}}" >
    <link rel="stylesheet" href="{{url(env("APP_URL").'storage/assets/libs/printjs/printjs.css')}}" >
    <script src="{{url(env("APP_URL").'storage/assets/libs/printjs/printjs.min.js')}}"></script>

    <style>
        .form-group label {
            line-height: 0.2rem !important;
        }
    </style>
</head>
<body>

<div class="container-scroller">
@include('layout.navbar')
<!-- partial -->
    @include('layout.breadscrum')
    <div class="container-fluid page-body-wrapper">

    @include('layout.sidebar')

    <!-- partial -->
        <div class="main-panel">
            <div class="content-wrapper">
                <div class="row">
                    <div class="col-md-12 grid-margin stretch-card">
                        <div class="card min-vh-70">
                            <div class="card-body">
                                <h4 class="card-title"><i class="mdi mdi-dots-vertical menu-icon"></i> {{__('invoice.form_edit_title')}}</h4>
                                <form method="post" class="p-2" action="{{route('invoice.update')}}" id="form-test-sample">
                                    @csrf
                                    <div class="row">
                                        <div class="col-lg-12">
                                            <div class="row">
                                                <div class="col-lg-12">
                                                    <div class="form-vertical sample-creation-form">
                                                        <div class="row">
                                                            <div class="col-sm-12 col-md-6 col-lg-3 pl-0">
                                                                <div class="form-group mb-1">
                                                                    <label for="lab-name-en">{{__('invoice.form_patient')}} <span class="text-danger">*</span></label>
                                                                    <select disabled class="form-control form-control-sm bg-white select2_ rounded-0" name="sample_id" id="sample-id" style=" width: 100% !important;">
                                                                        <option></option>
                                                                        @foreach($samples as $sample)
                                                                            <option {{$sample_id == $sample->id ? 'selected':''}} value="{{$sample->id}}">{{$sample->sample_number . ' - ' . $sample->patient->name_en}}</option>
                                                                        @endforeach
                                                                    </select>
                                                                </div>
                                                            </div>
                                                            <div class="col-sm-12 col-md-6 col-lg-3">
                                                                <div class="form-group mb-1">
                                                                    <label for="lab-name-en">{{__('invoice.form_invoice_number')}} <span class="text-danger">*</span></label>
                                                                    <input type="hidden" class="form-control" name="uid" value="{{$invoice->id}}">
                                                                    <input type="text" class="form-control form-control-sm bg-white rounded-0" value="{{$invoice->invoice_code}}" name="invoice_code" readonly id="invoice-number" placeholder="{{__('invoice.form_invoice_number')}}">
                                                                </div>
                                                            </div>
                                                            <div class="col-sm-12 col-md-6 col-lg-3">
                                                                <div class="form-group mb-1">
                                                                    <label for="lab-name-en">{{__('invoice.form_invoice_date')}} <span class="text-danger">*</span></label>
                                                                    <input type="date" value="{{date('Y-m-d', strtotime($invoice->invoice_date))}}" class="form-control form-control-sm rounded-0" name="invoice_date" id="invoice_date" placeholder="{{__('invoice.form_invoice_date')}}">
                                                                </div>
                                                            </div>
                                                            <div class="col-sm-12 col-md-6 col-lg-3 pr-0">
                                                                <div class="form-group mb-1">
                                                                    <label for="lab-name-en">{{__('sample.physician_name')}} <span class="text-danger"></span></label>
                                                                    <input type="text" value="{{$samples[0]->physician->name_en}}" class="form-control form-control-sm rounded-0" disabled>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="row border p-0">
                                                            <div class="col-sm-7 p-0" style="max-height: 350px; overflow: auto;">
                                                                @if(\App\Http\Controllers\Helper\GlobalController::user_can(Auth::user()->role_id, ['update_invoice']))
                                                                <button type="button" id="btnRefreshItem" onclick="updateInvoiceItems()" class="btn btn-light rounded-25 btn-sm my-1 ml-1 font-13"><i class="mdi mdi-rotate-left"></i> {{__('invoice.refresh_item')}}</button>
                                                                @endif
                                                                <table class="table">
                                                                    <thead>
                                                                    <tr style="background: #f5f5f5;">
                                                                        <th class="py-2 px-3">{{__('invoice.form_description')}}</th>
                                                                        <th width="150px" class="py-2 text-right" id="discount-type">
                                                                            {{__('invoice.form_discount')}} {{$labSettings->discount_type == 2 ? ($labSettings->currency==1?'៛':'$') : '(%)'}}</th>
                                                                        <th width="150px" class="py-2 text-right">{{__('invoice.form_net_amount')}} ({{$labSettings->currency==1?'៛':'$'}})</th>
                                                                    </tr>
                                                                    </thead>
                                                                    <tbody id="invoice-item">
                                                                        @foreach($invoice->invoiceDetail->sortBy('weight') as $k=>$invItem)
                                                                            <?php //$total+= $invItem->unit_price;?>
                                                                            <tr>
                                                                                <td class="py-1">{{$invItem->test_name}}
                                                                                    <input name="weight[]" type="hidden" value="{{$invItem->weight}}" />
                                                                                    <input name="test_sample_id[]" type="hidden" value="{{$invItem->test_sample_id}}" />
                                                                                    <input name="test_name[]" type="hidden" value="{{$invItem->test_name}}" />
                                                                                    <input name="item_discount_type[]" type="hidden" value="{{$invItem->discount_type}}" />
                                                                                    <input name="item_discount[]" type="hidden" value="{{$invItem->discount}}" />
                                                                                    <input name="unit_price[]" type="hidden" value="{{$invItem->unit_price}}" />
                                                                                </td>
                                                                                <td class="text-right ">{{$invItem->discount}}</td>
                                                                                <td class="text-right ">{{$labSettings->currency==1?'៛':'$'}} {{$invItem->unit_price}}</td>
                                                                            </tr>
                                                                        @endforeach
                                                                    </tbody>
                                                                </table>
                                                                <div class="form-group py-5 px-3">
                                                                    <label class="font-weight-medium" for="lab-name-en">{{__('invoice.form_description')}}</label>
                                                                    <textarea class="form-control" name="invoice_note" id="invoice-note" rows="3">{{$invoice->invoice_note}}</textarea>
                                                                </div>

                                                            </div>
                                                            <div class="col-sm-5 px-4 pt-2 border-left">
                                                                <div class="row">
                                                                    <div class="col-sm-12">
                                                                        <div class="form-group row">
                                                                            <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.exchange_rate')}} <span class="text-danger">*</span></label>
                                                                            <div class="col-sm-7">
                                                                                <input type="number" required step="any" class="form-control bg-white form-control-xxs rounded-0" value="{{($invoice->exchange_rate<=0 ? $labSettings->exchange_rate : $invoice->exchange_rate)}}" name="exchange_rate" id="exchange_rate">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-sm-12">
                                                                        <div class="form-group row">
                                                                            <label for="total-amount" class="col-sm-5 col-form-label">{{__('invoice.form_total_amount')}} <span class="text-danger">({{$labSettings->currency==1?'៛':'$'}})</span></label>
                                                                            <div class="col-sm-7">
                                                                                <input type="number" min="0.00" max="99999999" step="any" readonly required class="form-control bg-white form-control-xxs rounded-0" name="total" id="total-amount" value="{{$invoice->total}}">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-sm-12">
                                                                        <div class="form-group row">
                                                                            <label for="discount-amount" class="col-sm-5 col-form-label">{{__('invoice.form_discount')}} <span class="text-danger">({{$labSettings->discount_type == 2 ? ($labSettings->currency==1?'៛':'$') : '%'}})</span></label>
                                                                            <div class="col-sm-7">
                                                                                <input type="hidden" name="discount_type" value="{{$invoice->discount_type}}" id="discount_type" />
                                                                                <input type="number" min="0.00" max="99999999" step="any" required value="{{$invoice->discount}}" class="form-control form-control-xxs rounded-0" name="discount" id="discount-amount" placeholder="0.00">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-sm-12">
                                                                        <div class="form-group row">
                                                                            <label for="net-amount" class="col-sm-5 col-form-label">{{__('invoice.form_net_amount')}} <span class="text-danger">({{$labSettings->currency==1?'៛':'$'}})</span></label>
                                                                            <div class="col-sm-7">
                                                                                <input type="number" min="0.00" max="99999999" step="any" required value="{{$invoice->gross_total}}" class="form-control form-control-xxs rounded-0" name="gross_total" id="net-amount" placeholder="0.00">
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="col-sm-12 px-0 pt-2" style="background: #fbfbfb;">
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.pay_type')}} <span class="text-danger">*</span></label>
                                                                                <div class="col-sm-7">
                                                                                    <select class="form-control form-control-xxs select2_ rounded-0 py-0" name="pay_type" id="pay_type" style=" width: 100% !important;">
                                                                                        <option value="1" {{$invoice->pay_type==1 ? 'selected' : ''}}>{{__('invoice.cash_paid')}}</option>
                                                                                        <option value="2" {{$invoice->pay_type==2 ? 'selected' : ''}}>{{__('invoice.bank_paid')}}</option>
                                                                                        <option value="3" {{$invoice->pay_type==3 ? 'selected' : ''}}>{{__('invoice.cash_paid')}} + {{__('invoice.bank_paid')}}</option>
                                                                                    </select>
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.form_paid_amount')}} <small class="text-info">({{__('invoice.cash_paid')}})</small></label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="number" min="0.00" max="99999999" step="any" required value="{{$invoice->deposit}}" class="form-control form-control-xxs rounded-0" name="deposit" id="paid-amount" placeholder="0.00">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.form_paid_amount')}} <small class="text-info">({{__('invoice.bank_paid')}})</small></label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="number" min="0.00" max="99999999" step="any" required value="{{$invoice->bank_deposit}}" class="form-control form-control-xxs rounded-0" name="bank_deposit" id="bank-amount" placeholder="0.00">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.form_paid_date')}} <span class="text-danger">*</span></label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="date" value="{{date('Y-m-d')}}" class="form-control form-control-xxs rounded-0" name="first_paid_date" id="paid-date" placeholder="DD-MM-YYYY">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.bank_name')}}</label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="text" value="{{$invoice->bank_name}}" class="form-control form-control-xxs rounded-0" name="bank_name" id="bank_name">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="paid-amount" class="col-sm-5 col-form-label">{{__('invoice.transaction_no')}}</label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="text" value="{{$invoice->transaction_ref}}" class="form-control form-control-xxs rounded-0" name="transaction_ref" id="transaction_ref">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                        <div class="col-sm-12">
                                                                            <div class="form-group row">
                                                                                <label for="owe-amount" class="col-sm-5 col-form-label">{{__('invoice.form_owe_amount')}} ({{$labSettings->currency==1?'៛':'$'}})<span class="text-danger">*</span></label>
                                                                                <div class="col-sm-7">
                                                                                    <input type="number" min="0.00" max="99999999" step="any" readonly value="{{number_format($invoice->balance,2, '.', '')}}" class="form-control bg-white form-control-xxs rounded-0" name="balance" id="owe-amount" placeholder="0.00">
                                                                                </div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                </div>


                                                                <div class="form-check" style="width: 250px !important;">
                                                                    <label class="form-check-label">
                                                                        <input type="checkbox" {{($invoice->is_hide_discount==1 || $labSettings->is_hide_inv_discount==1)? 'checked':''}} name="is_hide_discount" class="form-check-input" id="select-all-lab">
                                                                        {{__('invoice.hide_discount')}}
                                                                    </label>
                                                                </div>

                                                            </div>
                                                        </div>
                                                        <div class="row">
                                                            <div class="col-lg-12 pt-4 text-right">

                                                                <button type="button" class="btn btn-inverse-info rounded-25 mr-2 ml-5 btn-print-invoice-a4" data-toggle="modal" data-target="#print_invoice_modal_a4" data-backdrop="static"><i class="mdi mdi-printer"></i>&nbsp;&nbsp;<span>{{__('sample.btn_print')}} A4</span></button>
                                                                <button type="button" class="btn btn-inverse-info rounded-25 mr-2 ml-5 btn-print-invoice" data-toggle="modal" data-target="#print_invoice_modal" data-backdrop="static"><i class="mdi mdi-printer"></i>&nbsp;&nbsp;<span>{{__('sample.btn_print')}}</span></button>
                                                                <button class="btn btn-info rounded-25" type="submit"><i class="mdi mdi-check-all"></i> {{__('invoice.form_btn_save')}}</button>

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



                @if($labSettings->invoice_template_id==1)
                    @if($labSettings->currency==1)
                        @include('modal.preview_invoice_forms.riel_invoice')
                    @else
                        @include('modal.preview_invoice_forms.usd_invoice')
                    @endif
                @elseif($labSettings->invoice_template_id==2)
                    @include('modal.preview_invoice_forms.usd_invoice_summary')
                @else
                    @include('modal.preview_invoice_forms.usd_invoice_t'.$labSettings->invoice_template_id)
                @endif

                @include('modal.preview_invoice_forms.usd_invoice_t4')


            @include('layout.footer')


        </div>
    </div>
</div>
@include('layout.common_script')
<script>


    var base_url = "{{url('invoice')}}";

    var invoice_id = {{$invoice_id}};
    var invoice = <?php echo json_encode($invoice);?>;
    var is_print_invoice = "{{isset($_GET['print'])? true : false}}";
    let sample_id = {{$invoice->sample_id}};
    let currency = {{$labSettings->currency}};
    let exchange_rate = {{$labSettings->exchange_rate}};
    if(is_print_invoice){
        $('.btn-print-invoice').trigger('click');
    }


    let newlyItems = <?php echo json_encode(collect($refreshItemItem)->whereNotIn('test_sample_id', $invoice->invoiceDetail->pluck('test_sample_id')->toArray())->toArray());?>;
    let is_need_refresh = <?php echo json_encode($is_need_refresh_invoice)?>;


</script>

<!--<script src="{{url(env("APP_URL").'storage/assets/js/admin/invoice.js')}}"></script>-->
<script src="{{url(env("APP_URL").'storage/assets/libs/printjs/printjs.min.js')}}"></script>

<script>

    function updateInvoiceItems(){
        if(newlyItems.length<1 && !is_need_refresh){
            handleMessage(false, 'No new items found!')
        }
        else {
            let newlyItems = <?php echo json_encode(collect($refreshItemItem))?>;
            let update_amt = 0;
            let update_discount = 0;
            $('#invoice-item').empty();
            let idOrder = 1;
            Object.values(newlyItems).map(updatedItem => {
                let tr = '<tr>' +
                    '<td class="py-1">' + updatedItem.group_result +
                    '   <input name="test_sample_id[]" type="hidden" value="' + updatedItem.test_sample_id + '" />' +
                    '   <input name="weight[]" type="hidden" value="' + idOrder + '" />' +
                    '   <input name="test_name[]" type="hidden" value="' + updatedItem.group_result + '" />' +
                    '   <input name="item_discount_type[]" type="hidden" value="' + updatedItem.item_discount_type + '" />' +
                    '   <input name="item_discount[]" type="hidden" value="' + updatedItem.discount_price + '" />' +
                    '   <input name="unit_price[]" type="hidden" value="' + updatedItem.usd_price + '" />' +
                    '</td>' +
                    '<td class="text-right py-1">' + updatedItem.discount_price + '</td>' +
                    '<td class="text-right py-1 ">' + updatedItem.usd_price + '</td>' +
                    '</tr>';
                $('#invoice-item').append(tr)

                update_amt += (currency === 1 ? Math.ceil((parseFloat(updatedItem.usd_price) * exchange_rate) / 100) * 100 : parseFloat(updatedItem.usd_price))
                update_discount += parseFloat(updatedItem.discount_price)
                idOrder++
            })
            let oldAmt = 0; // parseFloat($('#total-amount').val())
            let oldDisAmt = parseFloat(toFixedNumber($('#discount-amount').val(),2))
            let oldPaidAmt = parseFloat(toFixedNumber($('#paid-amount').val(),2))
            //let oldOweAmt = parseFloat(toFixedNumber($('#owe-amount').val(),2))
            let totalAmt = (parseFloat(oldAmt) + parseFloat(update_amt)).toFixed(2)
            $('#total-amount').val(totalAmt)
            let discountAmt = (parseFloat(oldDisAmt) + parseFloat(update_discount)).toFixed(2)
            $('#discount-amount').val(discountAmt)
            let netAmt = (parseFloat(oldAmt) + (parseFloat(update_amt)-(parseFloat(oldDisAmt) + parseFloat(update_discount)))).toFixed(2)
            $('#net-amount').val(netAmt)
            $('#owe-amount').val((netAmt - oldPaidAmt).toFixed(2))
        }
        $('#btnRefreshItem').attr('disabled', true)
    }

    $('#discount-amount').keyup(function () {
     let net_amount = 0;
     if($('#discount_type').val()==1){
         //net_amount = parseFloat($('#total-amount').val()) - parseFloat($('#discount-amount').val())
         net_amount = parseFloat($('#total-amount').val()) * (1 - (parseFloat($('#discount-amount').val())/100))
     }
     else{
         net_amount = parseFloat($('#total-amount').val()) - parseFloat($('#discount-amount').val())
     }
     //let net_amount = parseFloat($('#total-amount').val()) - parseFloat($('#discount-amount').val())
     //console.log(Math.ceil((net_amount/100))*100)
     let finalAmount = currency==1 ? Math.ceil((net_amount)/100) * 100 : toFixedNumber(net_amount,2)
     $('#net-amount').val(finalAmount)

     let own_amount = parseFloat(finalAmount) - (parseFloat( $('#paid-amount').val()) + parseFloat( $('#bank-amount').val()) )
     $('#owe-amount').val((own_amount).toFixed(2))
 })


 $('#paid-amount, #bank-amount').keyup(function () {
        let own_amount = parseFloat($('#net-amount').val()) - (parseFloat( $('#paid-amount').val()) + parseFloat( $('#bank-amount').val()) )
        $('#owe-amount').val((own_amount).toFixed(2))
    });

     $('#paid-amount, #bank-amount').click(function () {
        let own_amount = parseFloat($('#net-amount').val()) - (parseFloat( $('#paid-amount').val()) + parseFloat( $('#bank-amount').val()) )
        $('#owe-amount').val((own_amount).toFixed(2))
    });

</script>



</body>

</html>

