<!-- Container -->
<div class="container-fluid mt-20">
    <!-- Row -->
    <div class="row">
        <!-- col-xl-12 -->
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header pt-8 pb-8 d-flex justify-content-between">
                    <?php if (has_permission(VIEW, 'pharmacy', 'sale')) { ?>
                        <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, 'patient', 'patient')) { ?>
                            <button type="button" data-toggle="modal" data-target="#addPaitentModal" 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('patient'); ?>
                            </button>
                        <?php } ?>

                        <?php if (has_permission(ADD, 'pharmacy', 'sale')) { ?>
                            <a href="<?php echo site_url('pharmacy/sale/gui'); ?>" class="btn btn-xs btn-success">
                                <i class="fa fa-plus font-12 mr-5"></i>
                                <?php echo $this->lang->line('gui_pos'); ?>
                            </a>
                        <?php } ?>
                        <?php if (has_permission(VIEW, 'pharmacy', 'sale')) { ?>
                            <a href="<?php echo site_url('pharmacy/sale'); ?>" class="btn btn-xs btn-primary">
                                <i class="fa fa-list font-12 mr-5"></i>
                                <?php echo $this->lang->line('sale'); ?> <?php echo $this->lang->line('list'); ?>
                            </a>
                        <?php } ?>
                    </div>
                </div>

                <div class="card-body" id="vue-app">
                    <form enctype="multipart/form-data" method="POST" v-on:submit.prevent="onSubmit" action="<?php echo site_url('pharmacy/sale/add_sale'); ?>">
                        <div class="form-row">
                            <div class="col-md-5 mb-10">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text" for="customer_id"><?php echo $this->lang->line('customer'); ?></label>
                                    </div>
                                    <input id="customer_id" type="text" list="cust" class="form-control" v-model="adf.customer_id" v-on:keyup="searchCust" autocomplete="off">
                                    <datalist id="cust">
                                        <option v-for="c in cust">{{ c.patient_unique_id +' - '+ c.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="walking" v-model="adf.walking">
                                                <label class="custom-control-label text-white" for="walking"><?php echo $this->lang->line('walking'); ?></label>
                                            </div>
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-2 mb-10">
                                <input type="text" class="form-control" value="<?php echo get_custom_id('invoices', 'INV-', date('Y'), date('m')); ?>" placeholder="<?php echo $this->lang->line('invoice_no'); ?>">
                            </div>
                            <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-3 mb-10">
                                <select class="form-control" v-model="adf.payment_type" id="payment_type">
                                    <option value="cash"><?php echo $this->lang->line('cash'); ?></option>
                                    <option value="credit"><?php echo $this->lang->line('credit'); ?></option>
                                </select>
                            </div>
                            <div class="col-md-5 mb-10">
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <label class="input-group-text" for="medicine"><?php echo $this->lang->line('medicine'); ?></label>
                                    </div>
                                    <vue-bootstrap-typeahead :data="medicines" v-model="medicine" :maxMatches="50" ref="medicine" placeholder="Medicine Search..." :serializer="item => item.medicine_name +' ('+item.code+')'" @hit="selectedMedicine = $event">
                                </div>
                            </div>
                            <div class="col-md-7 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>
                        </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-center w-35">Medicine</th>
                                                        <th class="text-white font-weight-700 text-center w-15">Batch No</th>
                                                        <th class="text-white font-weight-700 text-center w-10">Qty</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">Total</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.medicine_name }}</td>
                                                        <td class="text-center">
                                                            <select v-model="test.batch_no" class="form-control form-control-sm" name="batch_no" id="batch_no">
                                                                <option value="">Select One</option>
                                                                <option v-for="batch in test.batches" :value="batch.bid">{{ batch.bid }} S#{{ parseInt(batch.stock) - parseInt(batch.sale) }}</option>
                                                            </select>
                                                        </td>
                                                        <td class="text-center">
                                                            <input :disabled="!test.batch_no || test.batch_no == ''" v-on:keyup="updateQty" type="text" class="form-control form-control-sm" v-model="test.quantity">
                                                        </td>
                                                        <td class="text-center">
                                                            {{ test.rate.toFixed(2) }}
                                                        </td>
                                                        <td class="text-center">
                                                            {{ test.total.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>
                                                </tbody>
                                                <tfoot>
                                                    <tr>
                                                        <th colspan="3" class="text-right font-weight-600">Total</th>
                                                        <th class="text-center font-weight-600">{{ calc.qty }}</th>
                                                        <th class="text-center font-weight-600">{{ calc.total_rate.toFixed(2) }}</th>
                                                        <th class="text-center font-weight-600">{{ calc.bill.toFixed(2) }}</th>
                                                        <th class="text-left font-weight-600"></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-50 font-weight-700">Total Bill</td>
                                                    <td class="text-right w-50 font-weight-700">{{ calc.bill.toFixed(2) }}</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.toFixed(2) }}</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 text-red">Due Amount</td>
                                                    <td class="text-right font-weight-700 text-red">{{ calc.due.toFixed(2) }}</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('pharmacy/sale'); ?>"><?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 Paitent Modal-->
<div class="modal fade" id="addPaitentModal" 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('patient'); ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="addPatientForm">
                <div class="modal-body">
                    <div class="form-row">
                        <div class="col-md-5 mb-10">
                            <label for="name"><?php echo $this->lang->line('patient'); ?> <?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('patient'); ?> <?php echo $this->lang->line('name'); ?>" autocomplete="off" required>
                        </div>
                        <div class="col-md-3 mb-10">
                            <label for="gender"><?php echo $this->lang->line('gender'); ?> <span class="required">*</span></label>
                            <select class="form-control custom-select" name="gender" id="gender" required>
                                <option selected value=""><?php echo $this->lang->line('select'); ?></option>
                                <?php $genders = get_genders(); ?>
                                <?php foreach ($genders as $key => $value) { ?>
                                    <option value="<?php echo $key; ?>" <?php echo isset($gender) && $gender == $key ? 'selected="selected"' : ""; ?>><?php echo $value; ?></option>
                                <?php } ?>
                            </select>
                        </div>
                        <div class="col-md-4 mb-10">
                            <label for="phone"><?php echo $this->lang->line('phone'); ?> <span class="required">*</span></label>
                            <input type="number" class="form-control" name="phone" id="phone" value="<?php echo isset($phone) ?  $phone : ''; ?>" placeholder="<?php echo $this->lang->line('phone'); ?>" autocomplete="off" required>
                        </div>
                        <div class="col-md-4 mb-10">
                            <label for="cdob"><?php echo $this->lang->line('birth_date'); ?></label>
                            <div class="input-group">
                                <div class="input-group-append col-md-6">
                                    <input type="number" class="form-control" id="age" name="age" placeholder="Age" autocomplete="off">
                                </div>
                                <input type="text" class="form-control col-md-6" id="dob" name="dob" value="<?php echo isset($dob) ?  $dob : ''; ?>" placeholder="<?php echo $this->lang->line('birth_date'); ?>" required>
                            </div>
                        </div>
                        <div class="col-md-4 mb-10">
                            <label for="address"><?php echo $this->lang->line('address'); ?></label>
                            <input type="text" class="form-control" name="address" id="address" value="<?php echo isset($address) ?  $address : ''; ?>" placeholder="<?php echo $this->lang->line('address'); ?>" autocomplete="off">
                        </div>
                        <div class="col-md-4 mb-10">
                            <label for="note"><?php echo $this->lang->line('remark'); ?></label>
                            <input type="text" class="form-control" name="note" id="note" value="<?php echo isset($note) ?  $note : ''; ?>" placeholder="<?php echo $this->lang->line('remark'); ?>" autocomplete="off">
                        </div>
                    </div>
                </div>
                <div class="modal-footer pt-0">
                    <div class="button-list">
                        <input type="hidden" name="role_id" value="<?php echo PATIENT; ?>">
                        <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>


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

<script type="text/javascript">
    $(document).ready(function(e) {
        $("#addPatientForm").on('submit', (function(e) {
            e.preventDefault();
            $.ajax({
                url: '<?php echo base_url('pharmacy/sale/addpatient'); ?>',
                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>
<script>
    $("#age").on("change", function() {
        var age = parseInt(document.getElementById('age').value, 10);
        var today = new Date();
        var months = ["01", "02", "03", "04", "05", "06", "07",
            "08", "09", "10", "11", "12"
        ];
        var currentYear = today.getFullYear();
        var birthYear = currentYear - age;
        document.getElementById('dob').value = birthYear + '/' + months[today.getMonth()] + '/' + today.getDate();
    });
</script>

<script>
    $("#dob").daterangepicker({
        singleDatePicker: true,
        showDropdowns: true,
        minYear: 1901,
        locale: {
            format: 'YYYY/MM/DD'
        }
    });
</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>

<!-- 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() {

        },
        data: {
            invoice_id: "<?php echo $this->input->get('invoice'); ?>",
            medicines: [],
            medicine: '',
            selectedMedicine: null,
            tableData: [],
            discount: null,
            advanced: null,
            cust: [],
            adf: {
                tests: [],
                custom_invoice_id: '<?php echo get_custom_id('invoices', 'INV-', date('Y'), date('m')); ?>',
                customer_id: "",
                walking: null,
                bill_date: moment().format('YYYY-MM-DD HH:mm'),
                payment_type: 'cash',
                note: '',
            },
            calc: {
                qty: 0,
                total_rate: 0,
                total: 0,
                bill: 0,
                discount: 0,
                payable: 0,
                net_total: 0,
                advanced: 0,
                due: 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: {
            medicine(newQuery) {
                if (this.selectedMedicine && newQuery == this.selectedMedicine.medicine_name + ' (' + this.selectedMedicine.code + ')') {
                    this.setDataToTable(this.selectedMedicine);
                } else {
                    this.selectedMedicine = null;
                    this.getMedicines(newQuery);
                }
            }
        },
        methods: {
            submitRequest(event) {
                event.preventDefault();
                let _this = this;
                event.preventDefault();
                if (_this.adf.walking) {
                    _this.adf.walking = 1;
                } else {
                    _this.adf.walking = 0
                }
                $('button[type=submit]').attr('disabled', true);
                let fd = new FormData();
                fd.append('prev_invoice_id', _this.invoice_id);
                fd.append('custom_invoice_id', _this.adf.custom_invoice_id);
                fd.append('customer_id', _this.adf.customer_id);
                fd.append('walking', _this.adf.walking);
                fd.append('bill_date', _this.adf.bill_date);
                fd.append('payment_type', _this.adf.payment_type);
                fd.append('note', _this.adf.note);
                fd.append('discount', _this.discount);
                fd.append('advanced', _this.advanced);

                _this.adf.tests.forEach(function(item, index) {
                    let value = _this.adf.tests[index].quantity + '__' + _this.adf.tests[index].batch_no;
                    fd.append('tests[' + _this.adf.tests[index].id + ']', value);
                });
                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('pharmacy/sale/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;
                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);
                }
            },
            searchCust(event) {
                let _this = this;
                let fd = new FormData();
                fd.append('customer', _this.adf.customer_id);
                axios.post("<?php echo site_url('pharmacy/sale/customer_search'); ?>", fd).then((res) => {
                    _this.cust = 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
                    return item;
                }).all();
                this.adf.tests = data;
                this.calcAmount();
            },
            calcAmount() {
                let _this = this;
                Object.keys(_this.calc).forEach(key => {
                    _this.calc[key] = 0;
                });
                const data = collect(_this.adf.tests);
                _this.calc.qty = data.sum('quantity');
                _this.calc.total_rate = data.sum('rate');
                _this.calc.bill = data.sum('total');
                _this.calc.payable = _this.calc.net_total = data.sum('total');

                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();
            },
            clearItem() {
                this.medicine = "";
                this.$refs.medicine.inputValue = '';
                $('input[type="search"]').focus();
                this.discount = null;
                this.advanced = null;
                this.calcAmount();
            },
            setDataToTable(data) {
                var exists = collect(this.adf.tests).where('id', data.id).first();
                if (!exists) {
                    var newData = {
                        id: data.id,
                        medicine_name: data.medicine_name,
                        code: data.code,
                        rate: parseFloat(data.sell_price),
                        quantity: 1,
                        batch_no: '',
                        batches: data.batches,
                        total: 1 * parseFloat(data.sell_price)
                    };
                    this.adf.tests.push(newData);
                } else {
                    $.toast({
                        text: data.medicine_name + ' already added in list',
                        position: 'top-right',
                        loaderBg: '#7a5449',
                        class: 'jq-toast-danger',
                        hideAfter: 3500,
                        stack: 6,
                        showHideTransition: 'fade'
                    });
                }
                this.clearItem();
            },
            async getMedicines(query) {
                let _this = this;
                let fd = new FormData();
                fd.append('medicine_name', query);
                axios.post("<?php echo site_url('pharmacy/sale/medicine_search'); ?>", fd).then((res) => {
                    _this.medicines = 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>