<!-- 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('purchase'); ?></li>
    </ol>
</nav>
<!-- /Breadcrumb -->

<!-- Container -->
<div class="container-fluid">
    <!-- 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_purchase'); ?>
        </h4>
        <div class="align-items-center">
            <?php if (has_permission(VIEW, 'pharmacy', 'refund')) { ?>
                <a href="<?php echo site_url('pharmacy/refund'); ?>" class="btn btn-xs btn-info">
                    <i class="fa fa-undo font-12 mr-5"></i>
                    <?php echo $this->lang->line('refund'); ?>
                </a>
            <?php } ?>
            <?php if (has_permission(VIEW, 'pharmacy', 'stock')) { ?>
                <a href="<?php echo site_url('pharmacy/stock'); ?>" class="btn btn-xs btn-success">
                    <i class="fa fa-bar-chart font-12 mr-5"></i>
                    <?php echo $this->lang->line('stock'); ?>
                </a>
            <?php } ?>
            <?php if (has_permission(VIEW, 'pharmacy', 'sale')) { ?>
                <a href="<?php echo site_url('pharmacy/sale'); ?>" class="btn btn-xs btn-danger">
                    <i class="fa fa-balance-scale font-12 mr-5"></i>
                    <?php echo $this->lang->line('sale'); ?>
                </a>
            <?php } ?>
        </div>
    </div>
    <!-- /Title -->

    <!-- Row -->
    <div class="row">
        <!-- col-xl-12 -->
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between">
                    <?php if (has_permission(EDIT, 'pharmacy', 'purchase')) { ?>
                        <h6 class="card-header d-flex align-items-center">
                            <i class="fa fa-cart-plus font-30 mr-10"></i>
                            <?php echo $this->lang->line('edit'); ?> <?php echo $this->lang->line('purchase'); ?>
                        </h6>
                    <?php } ?>
                    <?php if (has_permission(VIEW, 'pharmacy', 'purchase')) { ?>
                        <div class="align-items-center">
                            <a href="<?php echo site_url('pharmacy/purchase'); ?>" class="btn btn-xs btn-primary">
                                <i class="fa fa-list font-12 mr-5"></i>
                                <?php echo $this->lang->line('purchase'); ?> <?php echo $this->lang->line('list'); ?>
                            </a>
                        </div>
                    <?php } ?>
                </div>

                <?php echo form_open_multipart(site_url('pharmacy/purchase/edit/' . $invoice->id), array('name' => 'edit', 'id' => 'edit', 'class' => 'needs-validation', 'novalidate' => 'novalidate'), ''); ?>
                <div class="card-body">
                    <div class="form-row">
                        <div class="col-md-3 mb-10">
                            <label for="manufacturer_id"><?php echo $this->lang->line('manufacturer'); ?></label>
                            <select tabindex="1" class="form-control select2" name="manufacturer_id" id="manufacturer_id" onchange="medicine_list()">
                                <option selected value=""><?php echo $this->lang->line('select'); ?></option>
                                <?php foreach ($manufacturers as $obj) { ?>
                                    <option value="<?php echo $obj->id; ?>" <?php echo isset($invoice->manufacturer_id) && $invoice->manufacturer_id == $obj->id ? 'selected="selected"' : ""; ?>><?php echo $obj->name; ?></option>
                                <?php } ?>
                            </select>
                        </div>
                        <div class="col-md-2 mb-10">
                            <label for="purchase_date"><?php echo $this->lang->line('purchase'); ?> <?php echo $this->lang->line('date'); ?></label>
                            <input type="text" tabindex="2" class="form-control" name="purchase_date" id="purchase_date" value="<?php echo isset($invoice->purchase_date) ?  date('Y-m-d H:i', strtotime($invoice->purchase_date)) : ''; ?>" placeholder="<?php echo $this->lang->line('purchase'); ?> <?php echo $this->lang->line('date'); ?>">
                        </div>
                        <div class="col-md-2 mb-10">
                            <label for="invoice_no"><?php echo $this->lang->line('invoice_no'); ?></label>
                            <input type="text" tabindex="3" class="form-control" name="invoice_no" id="invoice_no" value="<?php echo isset($invoice->invoice_no) ?  $invoice->invoice_no : ''; ?>" placeholder="<?php echo $this->lang->line('invoice_no'); ?>">
                        </div>
                        <div class="col-md-3 mb-10">
                            <label for="note"><?php echo $this->lang->line('remark'); ?></label>
                            <input type="text" tabindex="4" class="form-control" name="note" id="note" value="<?php echo isset($invoice->note) ?  $invoice->note : ''; ?>" placeholder="<?php echo $this->lang->line('remark'); ?>">
                        </div>
                        <div class="col-md-2 mb-10">
                            <label for="payment_type"><?php echo $this->lang->line('payment'); ?> <?php echo $this->lang->line('type'); ?></label>
                            <select class="form-control" name="payment_type" id="payment_type">
                                <option value="cash" <?php echo isset($invoice->payment_type) && $invoice->payment_type == 'cash' ? 'selected="selected"' : ""; ?>><?php echo $this->lang->line('cash'); ?></option>
                                <option value="credit" <?php echo isset($invoice->payment_type) && $invoice->payment_type == 'credit' ? 'selected="selected"' : ""; ?>><?php echo $this->lang->line('credit'); ?></option>
                                <option value="due" <?php echo isset($invoice->payment_type) && $invoice->payment_type == 'due' ? 'selected="selected"' : ""; ?>><?php echo $this->lang->line('due'); ?></option>
                            </select>
                        </div>
                    </div>
                    <!-- Medicine Add Start-->
                    <style>
                        .table-wrap td:first-child {
                            padding-left: 0;
                        }

                        .table-wrap td:last-child {
                            padding-right: 0;
                        }
                    </style>
                    <div class="table-wrap">
                        <div class="table-responsive">
                            <table class="table table-sm table-border" id="purchaseTable">
                                <thead class="text-center bg-gradient-sunset">
                                    <tr>
                                        <th class="text-white font-weight-700 text-center w-20">Medicine Name</th>
                                        <th class="text-white font-weight-700 text-center w-10">Batch No</th>
                                        <th class="text-white font-weight-700 text-center w-15">Expiry Date</th>
                                        <th class="text-white font-weight-700 text-center w-10">Quantity</th>
                                        <th class="text-white font-weight-700 text-center w-10">Purchase</th>
                                        <th class="text-white font-weight-700 text-center w-10">Sale</th>
                                        <th class="text-white font-weight-700 text-center w-10">Wholesale</th>
                                        <th class="text-white font-weight-700 text-center w-10">Total</th>
                                        <th class="text-white font-weight-700 text-center w-5">Action</th>
                                    </tr>
                                </thead>
                                <tbody id="addPurchaseItem">
                                    <?php $sl = 1;
                                    if (isset($purchases) && !empty($purchases)) { ?>
                                        <?php foreach ($purchases as $obj) { ?>
                                            <tr>
                                                <td>
                                                    <input type="text" tabindex="5" class="form-control form-control-sm medicine_name medicineSelection" onkeypress="medicine_list(<?php echo $sl; ?>);" name="medicine_name" id="medicine_name_<?php echo $sl; ?>" value="<?php echo $obj->medicine_name ?? ''; ?>" placeholder="<?php echo $this->lang->line('medicine'); ?> <?php echo $this->lang->line('name'); ?>">
                                                    <input type="hidden" class="autocomplete_hidden_value medicine_id_<?php echo $sl; ?>" name="medicine_id[]" value="<?php echo $obj->medicine_id ?? ''; ?>" />
                                                    <input type="hidden" class="sl" value="<?php echo $sl; ?>">
                                                </td>
                                                <td>
                                                    <input type="text" tabindex="6" class="form-control form-control-sm" name="batch_no[]" id="batch_no_<?php echo $sl; ?>" value="<?php echo $obj->batch_no ?? ''; ?>" placeholder="Batch No">
                                                </td>
                                                <td>
                                                    <input type="text" tabindex="7" class="form-control form-control-sm date" name="expiry_date[]" id="expiry_date_<?php echo $sl; ?>" value="<?php echo $obj->expiry_date ?? ''; ?>" placeholder="Expiry Date">
                                                </td>
                                                <td class="text-right">
                                                    <input type="text" tabindex="8" class="form-control form-control-sm text-right" name="quantity[]" id="quantity_<?php echo $sl; ?>" value="<?php echo $obj->quantity ?? ''; ?>" onkeyup="calculate(<?php echo $sl; ?>),checkqty(<?php echo $sl; ?>);" onchange="calculate(<?php echo $sl; ?>);" placeholder="Quantity" min="0" required="required" />
                                                </td>
                                                <td class="test">
                                                    <input type="text" tabindex="9" class="form-control form-control-sm purchase_1 text-right" name="purchase[]" id="purchase_<?php echo $sl; ?>" value="<?php echo $obj->purchase ?? ''; ?>" onkeyup="calculate(<?php echo $sl; ?>),checkqty(<?php echo $sl; ?>);" onchange="calculate(<?php echo $sl; ?>);" placeholder="Purchase" min="0" />
                                                </td>
                                                <td class="test">
                                                    <input type="text" tabindex="10" class="form-control form-control-sm sale_1 text-right" name="sale[]" id="sale_<?php echo $sl; ?>" value="<?php echo $obj->sale ?? ''; ?>" onkeyup="calculate(<?php echo $sl; ?>),checkqty(<?php echo $sl; ?>);" onchange="calculate(<?php echo $sl; ?>);" placeholder="Sale" min="0" />
                                                </td>
                                                <td class="test">
                                                    <input type="text" tabindex="11" class="form-control form-control-sm wholesale_1 text-right" name="wholesale[]" id="wholesale_<?php echo $sl; ?>" value="<?php echo $obj->wholesale ?? ''; ?>" onkeyup="calculate(<?php echo $sl; ?>),checkqty(<?php echo $sl; ?>);" onchange="calculate(<?php echo $sl; ?>);" placeholder="Wholesale" min="0" />
                                                </td>
                                                <td class="text-right">
                                                    <input type="text" class="form-control form-control-sm total text-right" name="total[]" id="total_<?php echo $sl; ?>" value="<?php echo $obj->total ?? ''; ?>" readonly="readonly" />
                                                </td>
                                                <td class="text-right">
                                                    <button type="button" class="btn btn-xs btn-danger" onclick="deleteRow(this)"><i class="fa fa-trash txt-danger"></i></button>
                                                </td>
                                            </tr>
                                        <?php $sl++;
                                        } ?>
                                    <?php } ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="6">
                                            <button type="button" tabindex="12" class="btn btn-xs btn-info" id="add_invoice_item" name="add-invoice-item" onClick="addPurchaseOrderField1('addPurchaseItem');">
                                                <i class="fa fa-plus txt-danger"></i>
                                                <?php echo $this->lang->line('add'); ?> <?php echo $this->lang->line('new'); ?>
                                            </button>
                                        </td>
                                        <td class="text-right font-weight-bold"><?php echo $this->lang->line('total'); ?></td>
                                        <td colspan="2">
                                            <input type="text" class="text-right form-control form-control-sm" id="grandTotal" name="grand_total" value="<?php echo $invoice->total_bill; ?>" readonly="readonly" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="7" class="text-right font-weight-bold"><?php echo $this->lang->line('discount'); ?></td>
                                        <td colspan="2">
                                            <input type="text" class="text-right form-control form-control-sm" id="discount" name="discount" value="<?php echo $invoice->discount; ?>" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="7" class="text-right font-weight-bold"><?php echo $this->lang->line('net_payable'); ?></td>
                                        <td colspan="2">
                                            <input type="text" class="text-right form-control form-control-sm" id="net_payable" name="net_payable" value="<?php echo $invoice->net_payable; ?>" readonly="readonly" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="7" class="text-right font-weight-bold"><?php echo $this->lang->line('advanced'); ?></td>
                                        <td colspan="2">
                                            <input type="text" class="text-right form-control form-control-sm" id="advanced" name="advanced" value="<?php echo $invoice->advanced; ?>" />
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="7" class="text-right font-weight-bold"><?php echo $this->lang->line('due'); ?></td>
                                        <td colspan="2">
                                            <input type="text" class="text-right form-control form-control-sm" id="due" name="due_amount" value="<?php echo $invoice->due_amount; ?>" readonly="readonly" />
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    <!-- Medicine Add End -->
                </div>
                <!-- Card Footer -->
                <div class="card-footer pt-0">
                    <div class="button-list">
                        <input type="hidden" name="invoice_id" value="<?php echo $this->uri->segment(4, 0); ?>">
                        <a class="btn btn-gradient-danger" href="<?php echo site_url('pharmacy/purchase'); ?>"><?php echo $this->lang->line('cancel'); ?></a>
                        <button class="btn btn-gradient-primary" type="submit"><?php echo $this->lang->line('submit'); ?></button>
                    </div>
                </div>
                <?php echo form_close(); ?>
            </div>
        </div>
    </div>
    <!-- /Row -->
</div>
<!-- /Container -->

<!-- autocomplete  -->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.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>

<!-- Select2 -->
<link href="<?php echo VENDOR_URL; ?>select2/dist/css/select2.min.css" rel="stylesheet" type="text/css" />
<script src="<?php echo VENDOR_URL; ?>select2/dist/js/select2.full.min.js"></script>

<style>
    .select2-container .select2-selection--single {
        height: calc(2.25rem + 4px) !important
    }

    .select2-container--default .select2-search--dropdown .select2-search__field {
        color: #324148;
        border-width: 2px;
        border-color: #e0e3e4;
        padding: .375rem .75rem;
        height: calc(2.25rem + 4px);
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow b {
        margin-top: 5px;
    }
</style>

<script>
    $(".select2").select2();

    $("#purchase_date").daterangepicker({
        singleDatePicker: true,
        showDropdowns: true,
        minYear: 1901,
        timePicker: true,
        timePicker24Hour: true,
        timePickerIncrement: 1,
        timePickerSeconds: false,
        autoUpdateInput: true,
        locale: {
            format: 'YYYY-MM-DD HH:mm',
        }
    });

    $(".date").daterangepicker({
        singleDatePicker: true,
        showDropdowns: true,
        minYear: 1901,
        locale: {
            format: 'YYYY-MM-DD',
        }
    });
</script>

<script type="text/javascript">
    function medicine_list(sl) {
        var manufacturer_id = $('#manufacturer_id').val();
        if (manufacturer_id == 0) {
            alert('Please select manufacturer !');
            return false;
        }

        // Auto complete
        var options = {
            minLength: 0,
            source: function(request, response) {
                var medicine_name = $('#medicine_name_' + sl).val();
                $.ajax({
                    url: "<?php echo base_url('pharmacy/purchase/searchMedicine') ?>",
                    method: 'post',
                    dataType: "json",
                    data: {
                        manufacturer_id: $('#manufacturer_id').val(),
                        medicine_name: medicine_name,
                    },
                    success: function(data) {
                        response(data);
                    }
                });
            },
            focus: function(event, ui) {
                $(this).val(ui.item.label);
                return false;
            },
            select: function(event, ui) {
                $(this).parent().parent().find(".autocomplete_hidden_value").val(ui.item.value);
                var sl = $(this).parent().parent().find(".sl").val();
                var medicine_id = ui.item.value;
                var purchase = 'purchase_' + sl;
                var sale = 'sale_' + sl;
                var wholesale = 'wholesale_' + sl;

                $('#' + purchase).val(ui.item.purchase_price);
                $('#' + sale).val(ui.item.sell_price);
                $('#' + wholesale).val(ui.item.whole_sale_price);

                $(this).unbind("change");
                return false;
            }
        }

        $('body').on('keypress.autocomplete', '.medicine_name', function() {
            $(this).autocomplete(options);
        });

    }

    $(document).ready(function() {
        $('input, :input').attr('autocomplete', 'off');
    });
</script>
<script type="text/javascript">
    var count = (document.getElementById('purchaseTable').getElementsByTagName("tbody")[0].getElementsByTagName("tr").length) + 1;
    var limits = 500;

    function addPurchaseOrderField1(divName) {
        if (count == limits) {
            alert("You have reached the limit of adding " + count + " inputs");
        } else {
            var newdiv = document.createElement('tr');
            var tabin = "medicine_name_" + count;
            tabindex = count * 7,
                newdiv = document.createElement("tr");
            tab1 = tabindex + 1;
            tab2 = tabindex + 2;
            tab3 = tabindex + 3;
            tab4 = tabindex + 4;
            tab5 = tabindex + 5;
            tab6 = tabindex + 6;
            tab7 = tabindex + 7;
            tab8 = tabindex + 8;
            tab9 = tabindex + 9;
            tab10 = tab9 + 1;

            newdiv.innerHTML = '<td><input type="text" class="form-control form-control-sm medicine_name medicineSelection" name="medicine_name" id="medicine_name_' + count + '" tabindex="' + tab1 + '" onkeypress="medicine_list(' + count + ');" placeholder="Medicine Name"> <input type="hidden" class="autocomplete_hidden_value medicine_id_' + count + '" name="medicine_id[]"/> <input type="hidden" class="sl" value="' + count + '"></td><td><input type="text" class="form-control form-control-sm" name="batch_no[]" id="batch_no_' + count + '" tabindex="' + tab2 + '" placeholder="Batch No"/></td><td><input type="text" class="form-control form-control-sm date" name="expiry_date[]" id="expiry_date_' + count + '" tabindex="' + tab3 + '" placeholder="Expiry Date"/></td><td><input type="text" class="text-right form-control form-control-sm" name="quantity[]" id="quantity_' + count + '" tabindex="' + tab4 + '" onkeyup="calculate(' + count + '),checkqty(' + count + ');" onchange="calculate(' + count + ');" min="0" placeholder="Quantity"/></td><td><input type="text" name="purchase[]" onkeyup="calculate(' + count + '),checkqty(' + count + ');" onchange="calculate(' + count + ');" id="purchase_' + count + '" class="form-control form-control-sm purchase_' + count + ' text-right" placeholder="Purchase" min="0"/></td><td><input type="text" name="sale[]" onkeyup="calculate(' + count + '),checkqty(' + count + ');" onchange="calculate(' + count + ');" id="sale_' + count + '" class="form-control form-control-sm sale_' + count + ' text-right" placeholder="Sale" min="0"/></td><td><input type="text" name="wholesale[]" onkeyup="calculate(' + count + '),checkqty(' + count + ');" onchange="calculate(' + count + ');" id="wholesale_' + count + '" class="form-control form-control-sm wholesale_' + count + ' text-right" placeholder="Wholesale" min="0"/></td><td><input type="text" class="form-control form-control-sm total text-right total_' + count + '" name="total[]" id="total_' + count + '" readonly="readonly" /></td><td class="text-right"><button type="button" class="btn btn-xs btn-danger" onclick="deleteRow(this)"><i class="fa fa-trash txt-danger"></i></button></td>';
            document.getElementById(divName).appendChild(newdiv);
            document.getElementById(tabin).focus();
            document.getElementById("add_invoice_item").setAttribute("tabindex", tab10);
            count++;

            $(".date").daterangepicker({
                singleDatePicker: true,
                showDropdowns: true,
                minYear: 1901,
                locale: {
                    format: 'YYYY-MM-DD',
                }
            });
        }
    }

    //Add purchase input field
    function addPurchaseInputField(e) {
        var t = $("tbody#addPurchaseItem tr:first-child").html();
        count == limits ? alert("You have reached the limit of adding " + count + " inputs") : $("tbody#addPurchaseItem").append("<tr>" + t + "</tr>")
    }

    //Delete row
    function deleteRow(e) {
        var t = $("#purchaseTable > tbody > tr").length;
        if (1 == t) alert("There only one row you can't delete.");
        else {
            var a = e.parentNode.parentNode;
            a.parentNode.removeChild(a)
        }
        calculate();
        calculateSum();
    }
</script>

<script>
    function checkqty(sl) {
        var y = $("#quantity_" + sl).val();
        var x = $("#purchase_" + sl).val();
        var s = $("#sale_" + sl).val();
        var w = $("#wholesale_" + sl).val();
        if (isNaN(y)) {
            alert("Must input numbers!!!");
            document.getElementById("quantity_" + sl).value = '';
            return false;
        }
        if (isNaN(x)) {
            alert("Must input numbers!!!");
            document.getElementById("purchase_" + sl).value = '';
            return false;
        }
        if (isNaN(s)) {
            alert("Must input numbers!!!");
            document.getElementById("sale_" + sl).value = '';
            return false;
        }
        if (isNaN(w)) {
            alert("Must input numbers!!!");
            document.getElementById("wholesale_" + sl).value = '';
            return false;
        }
    }

    //Calculate
    function calculate(sl) {
        var grand_total = 0;
        var qty = $("#quantity_" + sl).val();
        var purchase = $("#purchase_" + sl).val();

        var total = qty * purchase;
        $("#total_" + sl).val(total.toFixed(2));

        //Total Price
        $(".total").each(function() {
            isNaN(this.value) || 0 == this.value.length || (grand_total += parseFloat(this.value))
        });

        $("#grandTotal").val(grand_total.toFixed(2, 2));

        $("#grandTotal, #discount").keyup(function() {
            if ($('#discount').val() != "") {
                $("#net_payable").val(parseFloat($("#grandTotal").val() - $("#discount").val()).toFixed(2, 2));
            } else {
                $("#net_payable").val(parseFloat($("#grandTotal").val()).toFixed(2, 2));
            }
        });
        $("#net_payable").val(parseFloat($("#grandTotal").val()).toFixed(2, 2));

        // Due Calculation
        $("#discount, #advanced").keyup(function() {
            if ($('#advanced').val() != "" || $('#discount').val() != "") {
                $("#due").val(parseFloat($("#net_payable").val() - $("#advanced").val()).toFixed(2, 2));
            } else {
                $("#due").val(parseFloat($("#net_payable").val()).toFixed(2, 2));
            }
        });
        $("#due").val(parseFloat($("#net_payable").val()).toFixed(2, 2));
    }

    //Calculate summation 
    function calculateSum() {
        var t = 0;
        //Total Price
        $(".total").each(function() {
                isNaN(this.value) || 0 == this.value.length || (t += parseFloat(this.value))
            }),
            e = t.toFixed(2, 2);
        var test = +e;
        $("#grandTotal").val(test.toFixed(2, 2));
        $("#discount").val('');
        $("#net_payable").val(test.toFixed(2, 2));
        $("#advanced").val('');
        $("#due").val('');
    }
</script>

<style>
    #add_invoice_item:focus {
        color: #fff;
        background-color: red !important;
        border-color: #eee !important;
    }
</style>