<!-- Breadcrumb -->
<nav class="hk-breadcrumb" aria-label="breadcrumb">
    <ol class="breadcrumb breadcrumb-light bg-transparent">
        <li class="breadcrumb-item"><a href="<?php echo site_url('dashboard'); ?>"><?php echo $this->lang->line('dashboard'); ?></a></li>
        <li class="breadcrumb-item active" aria-current="page"><?php echo $this->lang->line('billing'); ?></li>
    </ol>
</nav>
<!-- /Breadcrumb -->

<!-- Container -->
<div class="container">
    <!-- Title -->
    <div class="hk-pg-header">
        <h4 class="hk-pg-title">
            <span class="pg-title-icon"><i class="fa fa-arrow-circle-o-down"></i></span>
            <?php echo $this->lang->line('manage_billing'); ?>
        </h4>
        <div class="d-flex">
            <a href="<?php echo site_url('billing/bill'); ?>" class="btn btn-danger btn-sm mr-10"><?php echo $this->lang->Line('bill'); ?> <?php echo $this->lang->Line('list'); ?></a>
            <a href="<?php echo site_url('billing'); ?>" class="btn btn-success btn-sm"><?php echo $this->lang->Line('create'); ?> <?php echo $this->lang->Line('bill'); ?></a>
        </div>
    </div>
    <!-- /Title -->

    <!-- Row -->
    <div class="row" id="vue-app">
        <!-- col-lg-12 -->
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header 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-circle font-30 mr-10"></i>
                            <?php echo $this->lang->line('search'); ?> <?php echo $this->lang->line('test_price'); ?>
                        </h6>
                    <?php } ?>
                </div>
                <div class="card-body pt-0">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <div class="input-group">
                                    <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" class="w-80" v-model="investigetion" :maxMatches="50" ref="investigetion" placeholder="Investigetion Search..." :serializer="item => item.name +' ('+item.code+')'" @hit="selectedInvestigetion = $event">
                                </div>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-group">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text" for="commission_user_id">Reference Name</label>
                                    </div>
                                    <input 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 }}</option>
                                    </datalist>
                                </div>
                            </div>
                        </div>
                    </div>

                    <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">
                                                    </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>
                        </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">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-red">Due Amount</td>
                                                <td class="text-right font-weight-700 text-red">{{ calc.due }}</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- /Row -->
</div>
<!-- /Container -->



<!-- 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
        },
        data: {
            investigetions: [],
            investigetion: '',
            selectedInvestigetion: null,
            tableData: [],
            percentage: null,
            discount: null,
            advanced: null,
            commission: null,
            coms: [],
            docs: [],
            tubes: <?php echo json_encode($tubes); ?>,
            adf: {
                tests: [],
                tubes: [],
                commission_user_id: '',
            },
            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;
        },
        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: {
            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();
            },
            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 + 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'
                    });
                });
            }
        }
    });
</script>