<!-- Container -->
<div class="container-fulid">
    <!-- Row -->
    <div class="row">
        <!-- 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, 'ipd', 'ipd')) { ?>
                        <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, 'ipd', 'ipd')) { ?>
                            <a href="<?php echo site_url('ipd/new'); ?>" class="btn btn-xs btn-success">
                                <i class="fa fa-plus font-12 mr-5"></i>
                                <?php echo $this->lang->line('new'); ?> <?php echo $this->lang->line('patient'); ?>
                            </a>
                        <?php } ?>
                        <?php if (has_permission(VIEW, 'ipd', 'ipd')) { ?>
                            <a href="<?php echo site_url('ipd/admitted'); ?>" class="btn btn-xs btn-primary">
                                <i class="fa fa-list font-12 mr-5"></i>
                                <?php echo $this->lang->line('admitted'); ?> <?php echo $this->lang->line('patient'); ?> <?php echo $this->lang->line('list'); ?>
                            </a>
                        <?php } ?>
                    </div>
                </div>

                <div class="card-body pt-0" id="vue-app">
                    <!-- Patient Information Start-->
                    <div class="table-wrap">
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered table-info mt-0">
                                <thead>
                                    <tr>
                                        <th colspan="5" class="text-center bg-primary text-white font-weight-700 text-uppercase">
                                            <?php echo $this->lang->line('patient'); ?> <?php echo $this->lang->line('info'); ?>
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('patient'); ?> <?php echo $this->lang->line('name'); ?>:</span>
                                            <?php echo $patient->patient_name; ?>
                                        </td>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('patient_id'); ?></span>
                                            <?php echo $patient->patient_unique_id; ?>
                                        </td>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('registration_no'); ?> :</span>
                                            <?php echo $patient->registration_no; ?>
                                        </td>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('admission_id'); ?> :</span>
                                            <?php echo $patient->ipd_no; ?>
                                        </td>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('age'); ?>: </span>
                                            <?php echo get_age($patient->dob); ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('gender'); ?> :</span>
                                            <?php echo  $this->lang->line($patient->gender); ?>
                                        </td>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('phone'); ?>:</span>
                                            <?php echo $patient->phone; ?>
                                        </td>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('address'); ?> :</span>
                                            <?php echo $patient->address; ?>
                                        </td>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('ward'); ?> :</span>
                                            <span class="font-weight-bold text-red"><?php echo $patient->ward_name; ?></span>
                                        </td>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('bed'); ?> :</span>
                                            <span class="font-weight-bold text-red">
                                                <i class="fa fa-bed"></i>
                                                <?php echo $patient->bed; ?> - <?php echo $patient->floor; ?>
                                            </span>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="3">
                                            <span class="font-weight-bold"><?php echo $this->lang->line('ref_by'); ?> :</span>
                                            <?php
                                            if ($patient->doctor_id > 0 && !empty($patient->doctor_id)) {
                                                echo $patient->doctor . ', ' . $patient->specialist;
                                            } else {
                                                echo $this->lang->line('self');
                                            } ?>
                                        </td>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('contract'); ?> <?php echo $this->lang->line('person'); ?> :</span>
                                            <span class="font-weight-bold text-red"><?php echo $patient->contract_person; ?></span>
                                        </td>
                                        <td>
                                            <span class="font-weight-bold"><?php echo $this->lang->line('contract'); ?> <?php echo $this->lang->line('amount'); ?> :</span>
                                            <span class="font-weight-bold text-red"><?php echo $patient->contract_amount; ?></span>
                                        </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('ipd/add'); ?>">
                        <div class="form-row">
                            <input type="hidden" id="ipd_id" v-model="adf.ipd_id">
                            <input type="hidden" id="patient_id" v-model="adf.patient_id">
                            <div class="col-md-2 mb-10">
                                <input type="text" readonly id="custom_invoice_id" v-model="adf.custom_invoice_id" class="form-control">
                            </div>
                            <div class="col-md-3 mb-10">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text" for="bill_date"><?php echo $this->lang->line('bill'); ?> <?php echo $this->lang->line('date'); ?></span>
                                    </div>
                                    <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>
                            <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.user_id +' - '+ c.name }}</option>
                                    </datalist>
                                </div>
                                <small class="form-text text-center text-red"><?php echo isset($patient->reference) && !empty($patient->reference) ? $patient->reference_id . ' - ' . $patient->reference : ''; ?></small>
                            </div>
                            <div class="col-md-3 mb-10">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text" for="note"><?php echo $this->lang->line('remark'); ?></label>
                                    </div>
                                    <input type="text" class="form-control" v-model="adf.note" id="note" placeholder="<?php echo $this->lang->line('remark'); ?>" autocomplete="off">
                                </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="service"><?php echo $this->lang->line('service'); ?></label>
                                    </div>
                                    <vue-bootstrap-typeahead :data="services" v-model="service" :maxMatches="50" ref="service" placeholder="Service Search..." :serializer="item => item.name +' ('+item.code+')'" @hit="selectedService = $event">
                                </div>
                            </div>
                            <div class="col-md-4 mb-10">
                                <div class="input-group">
                                    <div class="input-group-append">
                                        <span class="input-group-text" id="basic-addon2">Package</span>
                                    </div>
                                    <input type="text" class="form-control" placeholder="Package" aria-label="Package" aria-describedby="basic-addon2">
                                </div>
                            </div>
                            <div class="col-md-4 mb-10 text-right">
                                <span class="font-26 text-red">
                                    Total Advanced:
                                    <?php echo number_format($total_advanced, 0); ?>
                                </span>
                            </div>
                        </div>
                        <!-- Form Row End -->
                        <div class="row">
                            <div class="col-md-9">
                                <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-10">SL. No</th>
                                                        <th class="text-white font-weight-700 text-left w-40">Service Name</th>
                                                        <th class="text-white font-weight-700 text-center w-10">Qty</th>
                                                        <th class="text-white font-weight-700 text-left w-20">Rate</th>
                                                        <th class="text-white font-weight-700 text-center w-10">Total</th>
                                                        <th class="text-white font-weight-700 text-center w-10">Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody v-if="adf.charges.length>0">
                                                    <tr v-for="(charge, index) in adf.charges">
                                                        <td class="text-center">{{ index + 1}}</td>
                                                        <td class="text-left">
                                                            <span v-html="charge.name"></span>
                                                        </td>
                                                        <td class="text-center">
                                                            <input v-if="charge.type == 'others'" v-on:keyup="updateQty" type="text" class="form-control form-control-sm" v-model="charge.quantity">
                                                            <span v-else>{{ charge.quantity }}</span>
                                                        </td>
                                                        <td class="text-left">
                                                            <input v-if="charge.type == 'others'" v-on:keyup="updateQty" type="text" class="form-control form-control-sm" v-model="charge.price">
                                                            <span v-else v-html="charge.price"></span>
                                                        </td>
                                                        <td class="text-center">
                                                            {{ charge.total }}
                                                        </td>
                                                        <td class="text-center">
                                                            <button v-if="charge.type == 'others'" type="button" v-on:click="removeItem(charge)" 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="3" class="text-left font-weight-600">{{ calc.bill }}</th>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <!-- Discount -->
                            <div class="col-md-3">
                                <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-60 font-weight-700">Total Bill</td>
                                                    <td class="text-right w-40 font-weight-700">{{ calc.bill }}</td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right w-60 font-weight-700">Paid Amount</td>
                                                    <td class="text-right w-40 font-weight-700">{{ paid }}</td>
                                                </tr>
                                                <tr>
                                                    <td class="text-right">Discount(-)</td>
                                                    <td class="text-right pr-10">
                                                        <input type="text" v-model="discount" v-on:keyup="updateQty()" class="form-control form-control-sm text-right">
                                                    </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">Payable Commission</td>
                                                    <td class="text-right pr-10">
                                                        <input :disabled="adf.commission_user_id.length==0" v-model="commission" type="text" class="form-control form-control-sm text-right">
                                                    </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('ipd/admitted'); ?>"><?php echo $this->lang->line('cancel'); ?></a>
                                                            <button :disabled="adf.charges.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 -->


<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>

<!-- 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>
    const app = new Vue({
        el: '#vue-app',
        components: {
            VueBootstrapTypeahead
        },
        created() {
            this.initSetadata();
        },
        data: {
            inits: {
                bed: <?php echo json_encode($bed_amounts); ?>,
                surgeon: <?php echo json_encode($surgeon_amounts); ?>,
                anesthesia: <?php echo json_encode($anesthesia_amounts); ?>,
                assistant: <?php echo json_encode($assistant_amounts); ?>,
                consultant: <?php echo json_encode($consultant_amounts); ?>,
                charge: <?php echo json_encode($charge_amounts); ?>
            },
            invoice_id: "<?php echo $this->input->get('invoice'); ?>",
            services: [],
            service: '',
            selectedService: null,
            tableData: [],
            discount: '',
            advanced: '',
            paid: <?php echo $total_advanced > 0 ? $total_advanced : 0; ?>,
            commission: null,
            coms: [],
            adf: {
                ipd_id: '<?php echo $patient->id; ?>',
                patient_id: '<?php echo $patient->patient_id; ?>',
                custom_invoice_id: '<?php echo get_custom_id('ipd_invoices', 'INV-', date('Y'), date('m')); ?>',
                bill_date: moment().format('YYYY-MM-DD HH:mm'),
                commission_user_id: '',
                note: '',
                charges: []
            },
            calc: {
                qty: 0,
                bill: 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: {
            service(newQuery) {
                if (this.selectedService && newQuery == this.selectedService.name + ' (' + this.selectedService.code + ')') {
                    this.setDataToTable(this.selectedService);
                } else {
                    this.selectedService = null;
                    this.getServices(newQuery);
                }
            }
        },
        methods: {
            initSetadata() {
                let _this = this;
                Object.keys(_this.inits).forEach(key => {
                    if (_this.inits && _this.inits[key].length > 0) {
                        _this.inits[key].forEach(function(item) {
                            let newData = {
                                id: null,
                                name: "",
                                type: "fixed",
                                code: null,
                                price: "",
                                commissions: 0,
                                quantity: 0,
                                total: 0
                            };
                            //var name = item.name + " (" + item.dates + ")<br>";
                            var type = item.type == '' ? "" : " (" + item.type + ")";
                            var name = item.name + type + "<br>";
                            var price = item.price;
                            newData.name += name;
                            newData.price += price;
                            newData.quantity += parseFloat(item.qty);
                            newData.total += parseFloat(item.amount);
                            _this.adf.charges.push(newData);
                        });
                    }
                });
                _this.calcAmount();
            },
            submitRequest(event) {
                event.preventDefault();
                let _this = this;
                event.preventDefault();
                $('button[type=submit]').attr('disabled', true);
                let fd = new FormData();

                fd.append('ipd_id', _this.adf.ipd_id);
                fd.append('patient_id', _this.adf.patient_id);
                fd.append('custom_invoice_id', _this.adf.custom_invoice_id);
                fd.append('prev_invoice_id', _this.invoice_id);
                fd.append('bill_date', _this.adf.bill_date);
                fd.append('commission_user_id', _this.adf.commission_user_id);
                fd.append('note', _this.adf.note);
                fd.append('discount', _this.discount);
                fd.append('advanced', _this.advanced);
                fd.append('paid', _this.paid);
                fd.append('net_commission', _this.calc.net_commission);
                fd.append('commission', _this.commission);

                _this.adf.charges.forEach(function(item, index) {
                    fd.append('charges[' + index + '][name]', _this.adf.charges[index].name);
                    fd.append('charges[' + index + '][price]', _this.adf.charges[index].price);
                    fd.append('charges[' + index + '][quantity]', _this.adf.charges[index].quantity);
                    fd.append('charges[' + index + '][total]', _this.adf.charges[index].total);
                });
                axios.post(event.target.action, fd).then((res) => {
                    $('button[type=submit]').attr('disabled', false);
                    if (res.data.id) {
                        window.location.href = "<?php echo site_url('ipd/invoice/'); ?>" + _this.adf.ipd_id + '/' + 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;
                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 {
                    _this.submitRequest(event);
                }
            },
            searchCom(event) {
                let _this = this;
                let fd = new FormData();
                fd.append('name', _this.adf.commission_user_id);
                axios.post("<?php echo site_url('ipd/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();
            },
            updateQty() {
                const data = collect(this.adf.charges).map(function(item) {
                    if (item.type == 'others') {
                        item.total = Math.abs(item.quantity) * parseFloat(item.price);
                    }
                    return item;
                }).all();
                this.adf.charges = data;
                this.calcAmount();
            },
            calcAmount() {
                let _this = this;
                _this.commission = 0;

                Object.keys(_this.calc).forEach(key => {
                    _this.calc[key] = 0;
                });

                const data = collect(_this.adf.charges);
                _this.calc.qty = data.sum('quantity');
                _this.calc.bill = data.sum('total');
                _this.calc.payable = _this.calc.net_total = data.sum('total');
                if (_this.adf.commission_user_id) {
                    let cid = _this.adf.commission_user_id.split(' - ');
                    var user = collect(_this.coms).where('user_id', cid[0]).first();
                    if (data.count() > 0 && user) {
                        data.each(function(item) {
                            _this.calc.net_commission += (parseFloat(item.commissions) * item.quantity);
                        });
                        _this.commission = _this.calc.net_commission;
                    }
                }

                if (_this.paid > 0) {
                    _this.calc.payable -= _this.paid;
                    _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(charge) {
                const index = this.adf.charges.indexOf(charge);
                if (index > -1) {
                    this.adf.charges.splice(index, 1);
                }
                $('input[type="search"]').focus();
                this.calcAmount();
            },
            clearItem() {
                this.service = "";
                this.$refs.service.inputValue = '';
                $('input[type="search"]').focus();

                this.commission = null;
                this.discount = null;
                this.advanced = null;
                this.calcAmount();
            },
            setDataToTable(data) {
                var exists = collect(this.adf.charges).where('id', data.id).first();

                if (!exists) {
                    var newData = {
                        id: data.id,
                        name: data.name,
                        code: data.code,
                        type: "others",
                        price: parseFloat(data.price),
                        commissions: parseFloat(data.commission),
                        quantity: 1,
                        total: 1 * parseFloat(data.price)
                    };
                    this.adf.charges.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 getServices(query) {
                let _this = this;
                let fd = new FormData();
                fd.append('name', query);
                fd.append('ipd_id', _this.adf.ipd_id);
                axios.post("<?php echo site_url('ipd/service_search'); ?>", fd).then((res) => {
                    _this.services = 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'
                    });
                });
            }
        }
    });
</script>