<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$id = 0;
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
$current_date = date('d-m-Y');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
    <script>
        $(function () {
            $('#datepicker').pickadate({
                format: 'dd-mm-yyyy',
                selectMonths: true,
            });
        });
    </script>
</head>
<body>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('../includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Rate List</h3>
            </div>
            <hr>
            <?php if ($_SESSION['sess_role'] == 'VEC') {
                if (isset($_GET['view'])) { ?>
                    <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;" href="?add">Add <i
                            class="mdi-content-add-box"></i></a>
                    <div class="clearfix"></div>
                <?php }
            } ?>
            <br/>
            <?php
            if (isset($_GET['add'])) {
                if (isset($_GET['edit'])) {
                    extract($_REQUEST);
                    $getInvoice = Invoice::GetInvoiceSetupById($id);
                    $customer_name = $getInvoice->customer_id;
                    $date = date('d-m-Y', strtotime($getInvoice->create_date));
                    $invoiceNumber = $getInvoice->code;
                    $discount = $getInvoice->discount;
                    $discount_price = $getInvoice->discount_price;
                }
                ?>
                <form action="print/ratelist.php" method="post" id="rate_list_form" novalidate="novalidate">
                    <div class="row">
                        <div class="col s12 form-group">
                            <?php echo $output; ?>
                            <div class="row">
                                <div class="col m6 s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="customer_name"
                                                   name="customer_name"/>
                                            <label for="customer_name" class="control-label">Customer Name / Address
                                                *</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col m6 s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="datepicker"
                                                   name="invoice_date"/>
                                            <label for="datepicker" class="control-label">Date *</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col m6 s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="discount_input"
                                                   name="discount_input"
                                                   onkeypress="return isDoubleNumberKey(event)"
                                                   maxlength="2"/>
                                            <label for="discount_input" class="control-label">Discount(%)</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="clearfix"></div>
                            <div class="row">
                                <table style="margin-top: 60px;"
                                       class="bordered responsive-table table dataTable">
                                    <thead>
                                    <th>Action</th>
                                    <th>Product Name</th>
                                    <th>Barcode</th>
                                    <th>Weight</th>
                                    <th>T.P</th>
                                    <th>Discount</th>
                                    <th>Sub Total</th>
                                    </thead>
                                    <tbody id="addNewItem">
                                    <?php
                                    if (isset($_GET['add'])) {
                                        $filterproducts = " WHERE status = 'active'";
                                        $product = ProductSetup::GetProductSetupList($filterproducts);

                                        $filterinvoiceproducts = " WHERE invoice_id = '$id'";
                                        $invoiceProducts = Invoice::GetInvoiceProducts($filterinvoiceproducts);
                                        foreach ($product AS $invoiceProductsRow) {
                                            $qry = $invoiceProductsRow->id;
                                            $productName = $invoiceProductsRow->name;
                                            $productBarcode = $invoiceProductsRow->barcode;
                                            $productWeight = $invoiceProductsRow->weight . ' ' . $invoiceProductsRow->unit;
                                            $productTPRate = $invoiceProductsRow->tp_rate;
                                            //$qry = ProductSetup::GetProductSetupById($invoiceProductsRow->product_id);
                                            if ($invoiceProductsRow->status == 'active') {
                                                echo "<tr id='tr" . $qry . "'>";
                                                echo '<td style="width: 30px; height: 30px; font-size: 12px; line-height: 15px; margin-top: 11px;" class="mini-stat-icon orange darken-2">';
                                                echo '<i id="trashing' . $qry . '" style="cursor: pointer;font-size: 18px;margin-top: 7px;" class="mdi-action-delete"></i>';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $productName . '">';
                                                echo '<input type="hidden" name="products[]" id="product" value="' . $qry . '">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $productBarcode . '">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $productWeight . '">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" name="tpRate[]" value="' . $productTPRate . '" id="tpRate">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="" id="discountProductsText">';
                                                echo '<input type="hidden" name="discountProducts[]" id="discountProducts" value="">';
                                                echo '</td>';
                                                echo '<td id="subTotal">';
                                                echo '';
                                                echo '</td>';
                                                echo "</tr>";
                                                ?>
                                                <script>
                                                    $('#trashing<?=$qry?>').on('click', function () {
                                                        $(this).parent('td').parent('tr').remove();
                                                        Calculate();
                                                    });
                                                </script>
                                                <?php
                                            }
                                        }
                                    }
                                    ?>
                                    </tbody>
                                </table>
                            </div>
                            <hr>
                            <div class="clearfix"></div>
                            <div class="row">
                                <div class="col m3 s12">
                                    <?php
                                    $filter = " where status = 'active'";
                                    $qry = ProductSetup::GetProductSetupList($filter, $pageno = "null", $pagesize = "null");
                                    if ($qry) {
                                        echo '<select id="productsItem" style="width: 100%!important;" class="form-control"><option></option>';
                                        foreach ($qry as $qery) {
                                            echo '<option value=' . $qery->id . '>' . $qery->name . '</option>';
                                        }
                                        echo '</select>';
                                    }
                                    ?>
                                </div>
                            </div>
                            <div class="row">
                                <div class="clearfix"></div>
                                <div class="col m3 s12">
                                    <div class="btn-group">
                                        <button id="newItem" type="button" class="btn waves-effect waves-light">
                                            Add New <i class="fa fa-plus"></i>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="clearfix"></div>
                    <button id="btnsubmit" type="submit" class="btn waves-effect waves-light">Print</button>
                    <button type="button" class="btn waves-effect waves-light"
                            onclick="location.href='../dboardorderslist.php'">Cancel
                    </button>
                </form>
                <?php

            } // close view
            ?>
        </div>
    </div>
</div>
</div>
<?php include('../includes/inc_footer.php'); ?>
<?php include('../includes/inc_js.php'); ?>
<script type="application/javascript">
    $(document).ready(function () {
        var fewSeconds = 2;
        $('#btnsubmit').click(function () {
            // Ajax request
            var btn = $(this);
            btn.hide();
            setTimeout(function () {
                btn.show();
            }, fewSeconds * 1000);
        });
        $('#show1').hide();
        $('#show2').hide();
        $('#show3').hide();
        $('#show4').hide();
        Calculate();
    });

    $('#newItem').on('click', function () {
        $('#newItem').attr('disabled', true);
        var product = $('#productsItem').val();
        var fewSeconds = 2;
        if (!$('#tr' + product).html() && product != '') {
            $('body #container').block({message: 'Loading...'});
            $.get('addItemRatelist.php?id=' + $('#productsItem').val() + '&discount=' + $('#discount_input').val(), function (data) {
                $("#addNewItem").append(data);
                $('body #container').unblock();
            })
            setTimeout(function () {
                $('body #container').unblock();
            }, fewSeconds * 500);
        }
        $('#newItem').attr('disabled', false);

    });
    $('#discount_input').attr('required', true);
    $(document).on('keyup', "input[name='discount_input']", function () {
        Calculate();
    });
    $(document).on('keyup', "input[name='tpRate[]']", function () {
        Calculate();
    });
    $('document').ready(function () {
        $('#discount_input').rules('add', {
            required: true,
            messages: {
                required: "<span class='label label-warning val_mes'>Please enter discount percentage</span>"
            }
        });
    });
    function Calculate() {
        $("input[name='discountProducts[]']").each(function (index, value) {
            //console.log($(this).val());
            $(this).val($("input[name='discount_input']").val());
            $(this).parent('td').children('#discountProductsText').val($("input[name='discount_input']").val());
        });

        var ptotal = 0;
        var count = 0;
        $("input[name='tpRate[]']").each(function (index, value) {
            if (isNaN(parseFloat($(this).val())) || parseFloat($(this).val()) == '') {
                $(this).val('0');
            } else {
                var unitsale = $("input[name='discountProducts[]']").eq(index).val();
                if (isNaN(parseFloat(unitsale)) || parseFloat(unitsale) == '') {
                    $("input[name='discountProducts[]']").eq(index).val('0');
                }
            }
            var subtotal = parseFloat(parseFloat($(this).val()) - ($(this).val()) * (unitsale / 100)).toFixed(2);
            if (isNaN(subtotal)) {
                subtotal = parseFloat(0).toFixed(2)
            }
            $(this).parent('td').parent('tr').children('#subTotal').text(subtotal);
            count++;
        });
    }
    function isDoubleNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode != 46 && charCode > 31
            && (charCode < 48 || charCode > 57))
            return false;

        return true;
    }
    function isNumberKey(evt) {
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31
            && (charCode < 48 || charCode > 57))
            return false;

        return true;
    }
</script>
</section>
</section>
</body>
</html>