<!-- Container -->
<div class="container-fluid mt-20">
    <!-- Row -->
    <div class="row" id="vue-app">
        <!-- col-xl-12 -->
        <div class="col-lg-12">
            <div class="card mb-0">
                <div class="card-header pt-8 pb-8 d-flex justify-content-between">
                    <?php if (has_permission(VIEW, 'billing', 'billing')) { ?>
                        <h6 class="card-header d-flex align-items-center">
                            <i class="fa fa-user font-30 mr-10"></i>
                            <?php echo $this->lang->line('create'); ?> <?php echo $this->lang->line('bill'); ?>
                        </h6>
                    <?php } ?>

                    <div class="align-items-center">
                        <?php if (has_permission(ADD, 'billing', 'billing')) { ?>
                            <a href="<?php echo site_url('billing'); ?>" class="btn btn-xs btn-success">
                                <i class="fa fa-plus font-12 mr-5"></i>
                                <?php echo $this->lang->line('create'); ?> <?php echo $this->lang->line('billing'); ?>
                            </a>
                        <?php } ?>
                        <?php if (has_permission(ADD, 'hrm', 'employee')) { ?>
                            <button type="button" data-toggle="modal" data-target="#addEmployeeModal" class="btn btn-xs btn-info">
                                <i class="fa fa-user font-12 mr-5"></i>
                                <?php echo $this->lang->line('add'); ?> <?php echo $this->lang->line('commission'); ?>
                            </button>
                        <?php } ?>
                        <?php if (has_permission(VIEW, 'billing', 'billing')) { ?>
                            <a href="<?php echo site_url('billing/bill'); ?>" class="btn btn-xs btn-primary">
                                <i class="fa fa-list font-12 mr-5"></i>
                                <?php echo $this->lang->line('billing'); ?> <?php echo $this->lang->line('list'); ?>
                            </a>
                        <?php } ?>
                    </div>
                </div>

                <div class="card-body pt-0">
                    <!-- Patient Information Start-->
                    <div class="table-wrap">
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered mt-0">
                                <thead>
                                    <tr>
                                        <th colspan="6" class="text-center bg-light text-ligh font-weight-700 text-uppercase">
                                            <?php echo $this->lang->line('patient'); ?> <?php echo $this->lang->line('info'); ?>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td><?php echo $this->lang->line('patient'); ?> <?php echo $this->lang->line('name'); ?></td>
                                        <td><?php echo $patient->name; ?></td>
                                        <td><?php echo $this->lang->line('patient_id'); ?></td>
                                        <td><?php echo $patient->patient_unique_id; ?></td>
                                        <td><?php echo $this->lang->line('patient'); ?> <?php echo $this->lang->line('age'); ?></td>
                                        <td><?php echo get_age($patient->dob); ?></td>
                                    </tr>
                                    <tr>
                                        <td><?php echo $this->lang->line('phone'); ?></td>
                                        <td><?php echo $patient->phone; ?></td>
                                        <td><?php echo $this->lang->line('gender'); ?></td>
                                        <td><?php echo $this->lang->line($patient->gender); ?></td>
                                        <td><?php echo $this->lang->line('blood_group'); ?></td>
                                        <td><?php echo $this->lang->line($patient->blood_group); ?></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <!-- Patient Information End-->

                    <form enctype="multipart/form-data" method="POST" v-on:submit.prevent="onSubmit" action="<?php echo site_url('billing/add'); ?>">
                        <div class="form-row">
                            <input type="hidden" id="patient_id" v-model="adf.patient_id">
                            <input type="hidden" id="appointment_id" v-model="adf.appointment_id">
                            <input type="hidden" id="marketing_id" v-model="adf.marketing_id">
                            <input type="hidden" id="custom_invoice_id" v-model="adf.custom_invoice_id" class="form-control">
                            <div class="col-md-2 mb-10">
                                <input type="text" class="form-control" v-model="adf.bill_date" id="bill_date" placeholder="<?php echo $this->lang->line('bill'); ?> <?php echo $this->lang->line('date'); ?>">
                            </div>
                            <div class="col-md-5 mb-10">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text" for="ref_dr"><?php echo $this->lang->line('ref_dr'); ?></label>
                                    </div>
                                    <input id="doc_name" type="text" list="docs" class="form-control" v-model="adf.doctor_id" v-on:keyup="searchDoc" autocomplete="off">
                                    <datalist id="docs">
                                        <option v-for="d in docs">{{ d.user_id +' - '+ d.name }}</option>
                                    </datalist>
                                    <div class="input-group-append">
                                        <button class="btn btn-primary" type="button">
                                            <div class="custom-control custom-checkbox checkbox-success">
                                                <input type="checkbox" class="custom-control-input" id="self" v-model="adf.self">
                                                <label class="custom-control-label text-white" for="self">Self</label>
                                            </div>
                                        </button>
                                    </div>
                                </div>
                                <div class="valid-feedback">
                                    <?php echo $this->lang->line('looks_good'); ?>
                                </div>
                                <div class="invalid-feedback">
                                    <?php echo $this->lang->line('required_field'); ?>
                                </div>
                                <small id="ref_dr" class="form-text text-muted">
                                    <?php echo form_error('ref_dr'); ?>
                                </small>
                            </div>
                            <div class="col-md-4 mb-10">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text" for="commission_user_id"><?php echo $this->lang->line('commission'); ?></label>
                                    </div>
                                    <input id="com_name" v-on:change="calcAmount" type="text" list="coms" class="form-control" v-model="adf.commission_user_id" v-on:keyup="searchCom" autocomplete="off">
                                    <datalist id="coms">
                                        <option v-for="c in coms">{{ c.id +' - '+ c.name +' - '+ c.phone }}</option>
                                    </datalist>
                                </div>
                                <small class="form-text text-center text-red">
                                    <?php if (isset($is_reference) && $is_reference > 0) { ?>
                                        <?php echo isset($is_reference) && !empty($reference->reference_id) ? $reference->reference_id . ' - ' . $reference->reference : ''; ?>
                                    <?php } ?>
                                </small>
                            </div>
                            <div class="col-md-1 mb-10">
                                <div class="custom-control custom-checkbox checkbox-danger mt-5">
                                    <input type="checkbox" class="custom-control-input" id="urgent" v-model="adf.urgent">
                                    <label class="custom-control-label" for="urgent"><?php echo $this->lang->line('urgent'); ?></label>
                                </div>
                            </div>
                            <div class="col-md-4 mb-10">
                                <div class="input-group w-100">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text" for="investigetion"><?php echo $this->lang->line('service'); ?></label>
                                    </div>
                                    <vue-bootstrap-typeahead :data="investigetions" v-model="investigetion" :maxMatches="50" ref="investigetion" placeholder="Investigetion Search..." :serializer="item => item.name +' ('+item.code+')'" @hit="selectedInvestigetion = $event">
                                </div>
                            </div>
                            <div class="col-md-3 mb-10">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text"><?php echo $this->lang->line('remark'); ?></span>
                                    </div>
                                    <textarea rows="1" class="form-control" v-model="adf.note" id="note" aria-label="<?php echo $this->lang->line('remark'); ?>"><?php echo isset($note) ?  $note : ''; ?></textarea>
                                </div>
                            </div>
                            <?php if ($this->session->userdata('role_id') == SUPER_ADMIN || !empty(custom_permission('discount'))) { ?>
                                <div class="col-md-2 mb-10">
                                    <div class="form-group">
                                        <select class="form-control custom-select" v-model="adf.authorized_person" name="authorized_person" id="authorized_person">
                                            <option selected value=""><?php echo $this->lang->line('select'); ?> Authorizer</option>
                                            <?php foreach ($authorized_person as $obj) { ?>
                                                <option value="<?php echo $obj->user_id; ?>" <?php echo isset($authorized_person) && $authorized_person == $obj->user_id ? 'selected="selected"' : ""; ?>><?php echo $obj->name; ?> [<?php echo $obj->phone; ?>]</option>
                                            <?php } ?>
                                        </select>
                                    </div>
                                </div>
                            <?php } ?>
                            <div class="col-md-3 mb-10">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text" for="reference_employee"><?php echo $this->lang->line('employee'); ?></label>
                                    </div>
                                    <input id="reference_employee" type="text" list="emps" class="form-control" v-model="adf.reference_employee" v-on:keyup="searchEmp" autocomplete="off">
                                    <datalist id="emps">
                                        <option v-for="e in emps">{{ e.id +' - '+ e.name }}</option>
                                    </datalist>
                                </div>
                            </div>
                        </div>
                        <!-- Form Row End -->
                        <div class="row">
                            <div class="col-md-8">
                                <div class="invoice-details" style="min-height: 300px;">
                                    <div class="table-wrap">
                                        <div class="table-responsive">
                                            <table class="table table-sm table-border mb-0">
                                                <thead class="text-center bg-gradient-sunset">
                                                    <tr>
                                                        <th class="text-white font-weight-700 text-center w-15">SL. No</th>
                                                        <th class="text-white font-weight-700 text-center w-50">Service Name</th>
                                                        <th class="text-white font-weight-700 text-center w-15">Quantity</th>
                                                        <th class="text-white font-weight-700 text-center w-10">Rate</th>
                                                        <th class="text-white font-weight-700 text-center w-10">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody v-if="adf.tests.length>0">
                                                    <tr v-for="(test, index) in adf.tests">
                                                        <td class="text-center">{{ index + 1 }}</td>
                                                        <td class="text-left">{{ test.name }} - {{ test.code }}</td>
                                                        <td class="text-center">
                                                            <input v-on:keyup="updateQty" type="text" class="form-control form-control-sm" v-model="test.quantity" disabled>
                                                        </td>
                                                        <td class="text-right">
                                                            {{ test.rate.toFixed(2) }}
                                                        </td>
                                                        <td class="text-right">
                                                            <button type="button" v-on:click="removeItem(test)" class="btn btn-xs btn-danger"><i class="fa fa-trash txt-danger"></i></button>
                                                        </td>
                                                    </tr>
                                                    <tr v-for="(tube, index) in adf.tubes">
                                                        <td class="text-center">#</td>
                                                        <td class="text-left">{{ tube.name }}</td>
                                                        <td class="text-center">
                                                            <input disabled type="text" class="form-control form-control-sm" v-model="tube.quantity">
                                                        </td>
                                                        <td class="text-right">
                                                            {{ tube.price }}
                                                        </td>
                                                        <td class="text-right">
                                                            <button type="button" v-on:click="removeTube(tube)" class="btn btn-xs btn-danger"><i class="fa fa-trash txt-danger"></i></button>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                                <tfoot>
                                                    <tr>
                                                        <th colspan="2" class="text-right font-weight-600">Total</th>
                                                        <th class="text-center font-weight-600">{{ calc.qty }}</th>
                                                        <th colspan="2" class="text-left font-weight-600">{{ calc.bill }}</th>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                                <?php if ($this->input->get('invoice') && !empty($this->input->get('invoice'))) { ?>
                                    <div class="form-group">
                                        <select class="form-control custom-select" v-model="adf.created_by" name="created_by" id="created_by">
                                            <option selected value=""><?php echo $this->lang->line('select'); ?> <?php echo $this->lang->line('employee'); ?></option>
                                            <?php foreach ($employees as $obj) { ?>
                                                <option value="<?php echo $obj->user_id; ?>" <?php echo isset($created_by) && $created_by == $obj->user_id ? 'selected="selected"' : ""; ?>><?php echo $obj->name; ?> [<?php echo $obj->phone; ?>]</option>
                                            <?php } ?>
                                        </select>
                                    </div>
                                <?php } ?>
                            </div>
                            <!-- Discount -->
                            <div class="col-md-4">
                                <div class="table-wrap">
                                    <div class="table-responsive">
                                        <table class="table table-sm table-border mb-0">
                                            <thead>
                                                <th colspan="2" class="text-center text-white bg-gradient-royston">
                                                    Bill Summary
                                                </th>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td class="text-right w-50 font-weight-700">Total Bill</td>
                                                    <td class="text-right w-50 font-weight-700">{{ calc.bill }}</td>
                                                </tr>
                                                <!-- <tr>
                                                    <td class="text-right w-50 font-weight-700">Special Discount</td>
                                                    <td class="text-right w-50 font-weight-700">{{ calc.total_special_discount }}</td>
                                                </tr> -->
                                                <tr>
                                                    <td class="text-right">Discount(-)</td>
                                                    <td class="text-right pr-10">
                                                        <div class="input-group input-group-sm">
                                                            <div class="input-group-prepend">
                                                                <span class="input-group-text" style="padding: 0.2rem .5rem;">%</span>
                                                            </div>
                                                            <input type="text" v-model="percentage" v-on:keyup="calcPercentage()" class="form-control form-control-sm text-right">
                                                        </div>
                                                        <div class="input-group input-group-sm mt-1">
                                                            <div class="input-group-prepend">
                                                                <span class="input-group-text" style="padding: 0.2rem .5rem;">Tk.</span>
                                                            </div>
                                                            <input type="text" v-model="discount" v-on:keyup="updateQty()" class="form-control form-control-sm text-right">
                                                        </div>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right font-weight-700">Net Payable</td>
                                                    <td class="text-right font-weight-700">{{ calc.payable }}</td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right">Advanced Amount</td>
                                                    <td class="text-right pr-10">
                                                        <input type="text" v-model="advanced" v-on:keyup="updateQty()" class="form-control form-control-sm text-right">
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right font-weight-700">Total Commission</td>
                                                    <td class="text-right font-weight-700">{{ calc.net_commission }}</td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right">Payable Commission</td>
                                                    <td class="text-right pr-10">
                                                        <input v-model="commission" type="text" class="form-control form-control-sm text-right">
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right font-weight-700 text-success">Net Commission</td>
                                                    <td class="text-right font-weight-700 text-success">
                                                        <span v-if="adf.commission_user_id">{{ calc.net_commission - discount }}</span>
                                                        <span v-else>0</span>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right font-weight-700 text-red">Due Amount</td>
                                                    <td class="text-right font-weight-700 text-red">{{ calc.due }}</td>
                                                </tr>
                                                <tr>
                                                    <td colspan="2">
                                                        <div class="button-list">
                                                            <a class="btn btn-sm btn-gradient-danger mt-5  float-left" href="<?php echo site_url('billing'); ?>"><?php echo $this->lang->line('cancel'); ?></a>
                                                            <button :disabled="adf.tests.length==0" class="btn btn-sm btn-gradient-primary mt-5 float-right" type="submit"><?php echo $this->lang->line('submit'); ?></button>
                                                        </div>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

    </div>
    <!-- /Row -->
</div>
<!-- /Container -->

<!-- Add Employee Modal-->
<div class="modal fade" id="addEmployeeModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalForms" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo $this->lang->line('add'); ?> <?php echo $this->lang->line('commission'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="addEmployeeForm" enctype="multipart/form-data" method="POST" action="<?php echo site_url('billing/addemployee'); ?>">
                <div class="modal-body">
                    <div class="form-row">
                        <div class="col-md-6 mb-10">
                            <label for="name"><?php echo $this->lang->line('name'); ?> <span class="required">*</span></label>
                            <input type="text" class="form-control" name="name" id="name" value="<?php echo isset($name) ?  $name : ''; ?>" placeholder="<?php echo $this->lang->line('name'); ?>" required autocomplete="off">
                        </div>
                        <div class="col-md-3 mb-10">
                            <label for="phone"><?php echo $this->lang->line('phone'); ?> <span class="required">*</span></label>
                            <input type="text" class="form-control" name="phone" id="phone" value="<?php echo isset($phone) ?  $phone : ''; ?>" placeholder="<?php echo $this->lang->line('phone'); ?>" required autocomplete="off">
                        </div>
                        <div class="col-md-3 mb-10">
                            <label for="commission_type"><?php echo $this->lang->line('commission'); ?> <?php echo $this->lang->line('type'); ?> <span class="required">*</span></label>
                            <select class="form-control custom-select" name="commission_type" id="commission_type" required>
                                <option value="vd"><?php echo $this->lang->line('vd'); ?></option>
                                <option value="mbbs"><?php echo $this->lang->line('mbbs'); ?></option>
                                <option value="emp"><?php echo $this->lang->line('emp'); ?></option>
                                <option value="corporate"><?php echo $this->lang->line('corporate'); ?></option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer pt-0">
                    <div class="button-list">
                        <input type="hidden" name="role_id" value="<?php echo VD; ?>">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo $this->lang->line('cancel'); ?></button>
                        <button class="btn btn-gradient-primary" type="submit" id="submit"><?php echo $this->lang->line('submit'); ?></button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Employee Modal -->
<script type="text/javascript">
    $(document).ready(function(e) {
        $("#addEmployeeForm").on('submit', (function(e) {
            e.preventDefault();
            $.ajax({
                url: '<?php echo base_url('billing/addemployee'); ?>',
                type: "POST",
                data: new FormData(this),
                dataType: 'json',
                contentType: false,
                cache: false,
                processData: false,
                success: function(data) {
                    if (data.status == "failed") {
                        var message = "";
                        $.each(data.error, function(index, value) {
                            message += value;
                        });
                        $.toast({
                            text: message,
                            position: 'top-right',
                            loaderBg: '#7a5449',
                            class: 'jq-toast-danger',
                            hideAfter: 3500,
                            stack: 6,
                            showHideTransition: 'fade'
                        });
                    } else {
                        $.toast({
                            text: data.message,
                            position: 'top-right',
                            loaderBg: '#7a5449',
                            class: 'jq-toast-primary',
                            hideAfter: 3500,
                            stack: 6,
                            showHideTransition: 'fade'
                        });
                        location.reload();
                    }
                }
            });
        }));
    });
</script>

<!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script> -->


<link rel="stylesheet" href="<?php echo VENDOR_URL; ?>vue/jquery-confirm.min.css">
<script src="<?php echo VENDOR_URL; ?>vue/jquery-confirm.min.js"></script>


<!-- Daterangepicker -->
<link href="<?php echo VENDOR_URL; ?>daterangepicker/daterangepicker.css" rel="stylesheet" type="text/css" />
<script src="<?php echo VENDOR_URL; ?>moment/min/moment.min.js"></script>
<script src="<?php echo VENDOR_URL; ?>daterangepicker/daterangepicker.js"></script>

<!-- Autocomplete -->
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/collect.js/4.28.4/collect.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.20.0/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<link href="https://unpkg.com/vue-bootstrap-typeahead/dist/VueBootstrapTypeahead.css" rel="stylesheet">
<script src="https://unpkg.com/vue-bootstrap-typeahead"></script> -->

<script src="<?php echo VENDOR_URL; ?>vue/collect.min.js"></script>
<script src="<?php echo VENDOR_URL; ?>vue/axios.min.js"></script>
<script src="<?php echo VENDOR_URL; ?>vue/vue@2.js"></script>
<link href="<?php echo VENDOR_URL; ?>vue/VueBootstrapTypeahead.css" rel="stylesheet">
<script src="<?php echo VENDOR_URL; ?>vue/VueBootstrapTypeahead.umd.min.js"></script>

<script>
    const app = new Vue({
        el: '#vue-app',
        components: {
            VueBootstrapTypeahead
        },
        created() {
            if (this.invoice_id != "") {
                this.getInvoice(this.invoice_id);
            }
        },
        data: {
            inv_urgent: false,
            inv_self: false,
            invoice_id: "<?php echo $this->input->get('invoice'); ?>",
            investigetions: [],
            investigetion: '',
            selectedInvestigetion: null,
            tableData: [],
            percentage: null,
            discount: null,
            advanced: null,
            commission: null,
            reference_employee: null,
            coms: [],
            docs: [],
            emps: [],
            tubes: <?php echo json_encode($tubes); ?>,
            adf: {
                tubes: [],
                tests: [],
                commission_user_id: '',
                doctor_id: "<?php echo isset($doctor->doctor_id) && !empty($doctor->doctor_id) ? $doctor->doctor_id . ' - ' . $doctor->doctor : ''; ?>",
                custom_invoice_id: '<?php echo get_custom_id('invoices', 'INV-', date('Y'), date('m')); ?>',
                patient_id: '<?php echo $patient->user_id; ?>',
                appointment_id: '<?php echo isset($marketing->appointment_id) ? $marketing->appointment_id : null; ?>',
                marketing_id: '<?php echo isset($marketing->marketing_id) ? $marketing->marketing_id : null; ?>',
                self: null,
                urgent: null,
                note: '',
                bill_date: moment().format('YYYY-MM-DD HH:mm'),
                created_by: "<?php echo isset($created->created_by) && !empty($created->created_by) ? $created->created_by : ''; ?>",
                authorized_person: "<?php echo isset($created->authorized_person) && !empty($created->authorized_person) ? $created->authorized_person : ''; ?>",
                reference_employee: "<?php echo isset($reference_emp->user_id) && !empty($reference_emp->user_id) ? $reference_emp->user_id . ' - ' . $reference_emp->name : ''; ?>",
            },
            calc: {
                qty: 0,
                bill: 0,
                total_special_discount: 0,
                percentage: 0,
                discount: 0,
                payable: 0,
                net_total: 0,
                advanced: 0,
                due: 0,
                net_commission: 0
            }
        },
        mounted() {
            let _this = this;
            $("#bill_date").daterangepicker({
                singleDatePicker: true,
                startDate: new Date(),
                showDropdowns: true,
                minYear: 1901,
                timePicker: true,
                timePicker24Hour: true,
                timePickerIncrement: 1,
                timePickerSeconds: false,
                autoUpdateInput: true,
                locale: {
                    format: 'YYYY-MM-DD HH:mm',
                }
            }, function(start, end, label) {
                _this.adf.bill_date = start.format('YYYY-MM-DD HH:mm');
            });
        },
        watch: {
            investigetion(newQuery) {
                if (this.selectedInvestigetion && newQuery == this.selectedInvestigetion.name + ' (' + this.selectedInvestigetion.code + ')') {
                    this.setDataToTable(this.selectedInvestigetion);
                } else {
                    this.selectedInvestigetion = null;
                    this.getInvestigations(newQuery);
                }
            }
        },
        methods: {
            submitRequest(event) {
                event.preventDefault();
                let _this = this;
                if (_this.adf.self) {
                    _this.adf.self = 1;
                } else {
                    _this.adf.self = 0
                }
                if (_this.adf.urgent) {
                    _this.adf.urgent = 1;
                } else {
                    _this.adf.urgent = 0
                }
                $('button[type=submit]').attr('disabled', true);
                let fd = new FormData();
                fd.append('patient_id', _this.adf.patient_id);
                fd.append('appointment_id', _this.adf.appointment_id);
                fd.append('marketing_id', _this.adf.marketing_id);
                fd.append('doctor_id', _this.adf.doctor_id);
                fd.append('prev_invoice_id', _this.invoice_id);
                fd.append('commission_user_id', _this.adf.commission_user_id);
                fd.append('custom_invoice_id', _this.adf.custom_invoice_id);
                fd.append('self', _this.adf.self);
                fd.append('urgent', _this.adf.urgent);
                fd.append('note', _this.adf.note);
                fd.append('bill_date', _this.adf.bill_date);
                fd.append('discount', _this.discount);
                fd.append('special_discount', _this.calc.total_special_discount);
                fd.append('advanced', _this.advanced);
                fd.append('commission', _this.commission);
                fd.append('created_by', _this.adf.created_by);
                fd.append('authorized_person', _this.adf.authorized_person);
                fd.append('reference_employee', _this.adf.reference_employee);

                _this.adf.tests.forEach(function(item, index) {
                    fd.append('tests[' + _this.adf.tests[index].id + ']', _this.adf.tests[index].quantity);
                });

                _this.adf.tubes.forEach(function(item, index) {
                    fd.append('tubes[' + _this.adf.tubes[index].id + ']', _this.adf.tubes[index].quantity);
                });
                axios.post(event.target.action, fd).then((res) => {
                    $('button[type=submit]').attr('disabled', true);
                    if (res.data.id) {
                        window.location.href = "<?php echo site_url('billing/invoice/'); ?>" + res.data.id;
                    } else {
                        if (res.data.status == "failed") {
                            $.toast({
                                text: res.data.error,
                                position: 'top-right',
                                loaderBg: '#7a5449',
                                class: 'jq-toast-danger',
                                hideAfter: 3500,
                                stack: 6,
                                showHideTransition: 'fade'
                            });
                        }
                    }
                }).catch((err) => {
                    $('button[type=submit]').attr('disabled', false);
                    $.toast({
                        text: err.response.data.message,
                        position: 'top-right',
                        loaderBg: '#7a5449',
                        class: 'jq-toast-danger',
                        hideAfter: 3500,
                        stack: 6,
                        showHideTransition: 'fade'
                    });
                });
            },
            onSubmit(event) {
                let _this = this;
                let allow_dis = ((_this.calc.bill - _this.calc.total_special_discount) * <?php echo $this->global_setting->is_discount ? ($this->global_setting->is_discount / 100) : 1; ?>);
                // if (_this.adf.commission_user_id && (_this.discount > _this.commission)) {
                //     $.confirm({
                //         title: 'Warning! Attention Please!!!',
                //         content: 'Discount amount is higher then net payeble commission amount',
                //         type: 'red',
                //         typeAnimated: true,
                //         buttons: {
                //             close: function() {}
                //         }
                //     });
                // } else 
                if (_this.advanced > _this.calc.payable) {
                    $.confirm({
                        title: 'Warning! Attention Please!!!',
                        content: 'Advanced amount is higher then net payeble amount',
                        type: 'red',
                        typeAnimated: true,
                        buttons: {
                            close: function() {}
                        }
                    });
                } else if ((_this.adf.authorized_person == "" || !_this.adf.authorized_person) &&
                    allow_dis < _this.discount
                ) {
                    $.confirm({
                        title: 'Warning! Attention Please!!!',
                        content: 'Discount amount is not more than ' + allow_dis,
                        type: 'red',
                        typeAnimated: true,
                        buttons: {
                            close: function() {}
                        }
                    });
                } else {
                    _this.submitRequest(event);
                }
            },
            searchDoc(event) {
                let _this = this;
                let fd = new FormData();
                fd.append('name', _this.adf.doctor_id);
                axios.post("<?php echo site_url('billing/doctor_search'); ?>", fd).then((res) => {
                    _this.docs = res.data;
                }).catch((err) => {
                    $.toast({
                        text: err.response.data.message,
                        position: 'top-right',
                        loaderBg: '#7a5449',
                        class: 'jq-toast-danger',
                        hideAfter: 3500,
                        stack: 6,
                        showHideTransition: 'fade'
                    });
                });
                _this.$forceUpdate();
            },
            searchCom(event) {
                let _this = this;
                let fd = new FormData();
                fd.append('name', _this.adf.commission_user_id);
                axios.post("<?php echo site_url('billing/commission_search'); ?>", fd).then((res) => {
                    if (collect(res.data).count() > 0) {
                        _this.coms = res.data;
                    }
                }).catch((err) => {
                    $.toast({
                        text: err.response.data.message,
                        position: 'top-right',
                        loaderBg: '#7a5449',
                        class: 'jq-toast-danger',
                        hideAfter: 3500,
                        stack: 6,
                        showHideTransition: 'fade'
                    });
                });
                _this.$forceUpdate();
            },
            searchEmp(event) {
                let _this = this;
                let fd = new FormData();
                fd.append('name', _this.adf.reference_employee);
                axios.post("<?php echo site_url('billing/employee_search'); ?>", fd).then((res) => {
                    if (collect(res.data).count() > 0) {
                        _this.emps = res.data;
                    }
                }).catch((err) => {
                    $.toast({
                        text: err.response.data.message,
                        position: 'top-right',
                        loaderBg: '#7a5449',
                        class: 'jq-toast-danger',
                        hideAfter: 3500,
                        stack: 6,
                        showHideTransition: 'fade'
                    });
                });
                _this.$forceUpdate();
            },
            updateQty() {
                const data = collect(this.adf.tests).map(function(item) {
                    item.total = Math.abs(item.quantity) * item.rate
                    item.total_special_discount = Math.abs(item.quantity) * item.special_discount
                    return item;
                }).all();
                this.adf.tests = data;
                this.percentage = this.calc.bill > 0 ? parseInt((this.discount * 100) / this.calc.bill) : '';
                this.calcAmount();
            },
            calcPercentage() {
                let _this = this;
                _this.discount = ((_this.calc.bill * _this.percentage) / 100);
                this.calcAmount();
            },
            calcAmount() {
                let _this = this;
                _this.commission = 0;

                Object.keys(_this.calc).forEach(key => {
                    _this.calc[key] = 0;
                });
                const data = collect(_this.adf.tests);
                const tubes = collect(_this.adf.tubes);
                _this.calc.qty = data.sum('quantity');
                _this.calc.bill = data.sum('total') + tubes.sum('total');
                _this.calc.total_special_discount = data.sum('total_special_discount');
                _this.calc.payable = _this.calc.net_total = _this.calc.bill;
                if (_this.adf.commission_user_id) {
                    let cid = _this.adf.commission_user_id.split(' - ');
                    var user = collect(_this.coms).where('id', cid[0]).first();
                    if (data.count() > 0 && user) {
                        data.each(function(item) {
                            _this.calc.net_commission += (parseFloat(item[user.commission_type]) * item.quantity);
                        });
                        //_this.calc.net_commission = _this.calc.bill - _this.calc.net_commission;
                        _this.calc.net_commission = _this.calc.bill - (_this.calc.net_commission + tubes.sum('total'));
                        _this.commission = _this.calc.net_commission;
                    }
                }

                if (_this.calc.total_special_discount > 0) {
                    _this.calc.payable -= _this.calc.total_special_discount;
                    _this.calc.net_total = _this.calc.payable;
                }

                if (_this.discount > 0) {
                    _this.calc.payable -= _this.discount;
                    _this.calc.net_total = _this.calc.payable;
                }
                if (_this.advanced > 0) {
                    _this.calc.net_total -= _this.advanced;
                }
                if (_this.calc.net_total > 0) {
                    _this.calc.due = _this.calc.net_total;
                }
            },
            removeItem(test) {
                const index = this.adf.tests.indexOf(test);
                if (index > -1) {
                    this.adf.tests.splice(index, 1);
                }
                $('input[type="search"]').focus();
                this.calcAmount();
            },
            removeTube(tube) {
                const index = this.adf.tubes.indexOf(tube);
                if (index > -1) {
                    this.adf.tubes.splice(index, 1);
                }
                $('input[type="search"]').focus();
                this.calcAmount();
            },
            clearItem() {
                this.investigetion = "";
                this.$refs.investigetion.inputValue = '';
                $('input[type="search"]').focus();
                this.commission = null;
                this.percentage = null;
                this.discount = null;
                this.advanced = null;
                this.calcAmount();
            },
            setDataToTable(data) {
                var exists = collect(this.adf.tests).where('id', data.id).first();
                var needle_id = parseInt(data.needle_id);
                var tube_id = parseInt(data.tube_id);
                if (needle_id > 0) {
                    var needle_exists = collect(this.adf.tubes).where('id', data.needle_id).first();
                    if (!needle_exists) {
                        var needle = collect(this.tubes).where('id', data.needle_id).first();
                        if (needle) {
                            var newNeedle = {
                                id: needle.id,
                                name: needle.name,
                                price: needle.price,
                                quantity: 1,
                                total: 1 * parseFloat(needle.price)
                            };
                            this.adf.tubes.push(newNeedle);
                        }
                    }
                }
                if (tube_id > 0) {
                    var tube_exists = collect(this.adf.tubes).where('id', data.tube_id).first();
                    if (!tube_exists) {
                        var tube = collect(this.tubes).where('id', data.tube_id).first();
                        if (tube) {
                            var newTube = {
                                id: tube.id,
                                name: tube.name,
                                price: tube.price,
                                quantity: 1,
                                total: 1 * parseFloat(tube.price)
                            };
                            this.adf.tubes.push(newTube);
                        }
                    }
                };
                if (!exists) {
                    var newData = {
                        id: data.id,
                        name: data.name,
                        code: data.code,
                        rate: parseFloat(data.rate),
                        special_discount: parseFloat(data.special_discount),
                        total_special_discount: 1 * parseFloat(data.special_discount),
                        quantity: 1,
                        mbbs: parseFloat(data.mbbs),
                        vd: parseFloat(data.vd),
                        emp: parseFloat(data.emp),
                        corporate: parseFloat(data.corporate),
                        total: 1 * parseFloat(data.rate)
                    };
                    this.adf.tests.push(newData);
                } else {
                    $.toast({
                        text: data.name + ' already added in list',
                        position: 'top-right',
                        loaderBg: '#7a5449',
                        class: 'jq-toast-danger',
                        hideAfter: 3500,
                        stack: 6,
                        showHideTransition: 'fade'
                    });
                }
                this.clearItem();
            },
            async getInvestigations(query) {
                let _this = this;
                let fd = new FormData();
                fd.append('name', query);
                axios.post("<?php echo site_url('billing/test_search'); ?>", fd).then((res) => {
                    _this.investigetions = res.data;
                }).catch((err) => {
                    $.toast({
                        text: err.response.data.message,
                        position: 'top-right',
                        loaderBg: '#7a5449',
                        class: 'jq-toast-danger',
                        hideAfter: 3500,
                        stack: 6,
                        showHideTransition: 'fade'
                    });
                });
            },
            getInvoice(invoice_id) {
                let _this = this;
                let url = '/billing/get_invoice/' + invoice_id;
                axios.get("<?php echo site_url(); ?>" + url).then((res) => {
                    res.data.tests.forEach(function(item) {
                        var newData = {
                            id: item.id,
                            name: item.name,
                            code: item.code,
                            rate: parseFloat(item.rate),
                            special_discount: parseFloat(item.special_discount),
                            total_special_discount: parseInt(item.quantity) * parseFloat(item.special_discount),
                            quantity: parseInt(item.quantity),
                            mbbs: parseFloat(item.mbbs),
                            vd: parseFloat(item.vd),
                            emp: parseFloat(item.emp),
                            corporate: parseFloat(item.corporate),
                            total: parseInt(item.quantity) * parseFloat(item.rate)
                        };
                        _this.adf.tests.push(newData);
                    });
                    // Tube List
                    res.data.tubes.forEach(function(item) {
                        var newNeedle = {
                            id: item.id,
                            name: item.name,
                            price: parseFloat(item.rate),
                            quantity: parseInt(item.quantity),
                            total: parseInt(item.quantity) * parseFloat(item.rate)
                        };
                        _this.adf.tubes.push(newNeedle);
                    });

                    if (res.data.doctor_name) {
                        _this.adf.doctor_id = res.data.doctor_name;
                    } else if (res.data.doctor) {
                        _this.adf.doctor_id = res.data.doctor.user_id + ' - ' + res.data.doctor.name;
                        _this.docs.push(res.data.doctor);
                    }

                    if (res.data.com_name) {
                        _this.adf.commission_user_id = res.data.commission_name;
                    } else if (res.data.commission) {
                        _this.adf.commission_user_id = res.data.commission.id + ' - ' + res.data.commission.name;
                        _this.coms.push(res.data.commission);
                    }
                    if (parseFloat(res.data.invoice.discount) > 0) {
                        _this.discount = parseInt(res.data.invoice.discount);
                    }
                    if (parseFloat(res.data.invoice.payable_commission) > 0) {
                        _this.commission = parseInt(res.data.invoice.payable_commission);
                    }
                    if (parseFloat(res.data.invoice.advanced) > 0) {
                        _this.advanced = parseInt(res.data.invoice.advanced);
                    }

                    _this.adf.note = res.data.invoice.note;
                    _this.adf.bill_date = moment(res.data.invoice.bill_date).format('YYYY-MM-DD HH:mm');

                    if (res.data.invoice.self == "1") {
                        $("#self").attr("checked", true);
                        _this.adf.self = true;
                    }
                    if (res.data.invoice.delivery_status == "urgent") {
                        _this.adf.urgent = true;
                        $("#urgent").attr("checked", true);
                    }
                    _this.calcAmount();
                }).catch((err) => {
                    $.toast({
                        text: err.response.data.message,
                        position: 'top-right',
                        loaderBg: '#7a5449',
                        class: 'jq-toast-danger',
                        hideAfter: 3500,
                        stack: 6,
                        showHideTransition: 'fade'
                    });
                });
            }
        }
    });
</script>