<?php
include("../../classes/manager.class.php");
$m = new Manager();
$output = '';
$description = '';
$discount = 0;
$discount_price = 0;
$add_discount = 0;
$add_discount_price = 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,
            });
        });

        function numbering() {
            var count = 0;
            $('#addNewItem tr td:first-child').each(function () {
                count++;
                $(this).html(count);
            });
        }

        $(document).ready(function () {
            var selectedvall = $('#customer_name').find(':selected').data('discountdisable');
            if(selectedvall == 1){
                $('#discount').attr('readonly', true);
                $('#add_discount').attr('readonly', true);
            }

            var fewSeconds = 2;
            $('#btnsubmit').click(function () {
                var btn = $(this);
                btn.hide();
                setTimeout(function () {
                    btn.show();
                }, fewSeconds * 1000);
            });
            if ($('#customer_name').find(':selected').attr('data-mart') == 1) {
                $('#distributorHeader').hide();
                $("input[name='unitdistributor[]']").each(function () {
                    $(this).parent('td').hide();
                });
                $('#show1').hide();
                $('#show2').hide();
                $('#show3').hide();
                $('#show4').hide();
            } else {
                $('#distributorHeader').hide();
                $("input[name='unitdistributor[]']").each(function () {
                    $(this).parent('td').hide();
                });
                $('#show1').hide();
                $('#show2').hide();
                $('#show3').hide();
                $('#show4').hide();
            }
            Calculate();
        });

        $('#customer_name').on('change', function(){
            var selectedval = $(this).find(':selected').data('discountdisable');
            if(selectedval == 1){
                <?php if (isset($_GET['edit'])) {?>
                $('#discount').val(0);
                $('#add_discount').val(0);
                Calculate();
                <?php }?>
                $('#discount').attr('readonly', true);
                $('#add_discount').attr('readonly', true);
            }else{
                $('#discount').val($(this).find(':selected').data('disperc'));
                $('#discount').attr('readonly', false);
                $('#add_discount').val($(this).find(':selected').data('adddisperc'));
                $('#add_discount').attr('readonly', false);
            }
        });

        $('#customer_name').on('change', function () {
            if ($(this).find(':selected').attr('data-mart') == 1) {
                $('#distributorHeader').hide();
                $("input[name='unitdistributor[]']").each(function () {
                    $(this).parent('td').hide();
                });
                $('#show1').hide();
                $('#show2').hide();
                $('#show3').hide();
                $('#show4').hide();
            } else {
                $('#distributorHeader').hide();
                $("input[name='unitdistributor[]']").each(function () {
                    $(this).parent('td').hide();
                });
                $('#show1').hide();
                $('#show2').hide();
                $('#show3').hide();
                $('#show4').hide();
            }
        });

        $('#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('addItem.php?id=' + $('#productsItem').val() + '&customer=' + $('#customer_name').find(':selected').attr('data-mart') + '&customerid=' + $('#customer_name').find(':selected').val(), function (data) {
                    $("#addNewItem").append(data);
                    numbering();
                    $('body #container').unblock();
                })
                setTimeout(function () {
                    $('body #container').unblock();
                }, fewSeconds * 500);
                $('#newAll').remove();
            }
            $('#newItem').attr('disabled', false);
        });

        $('#newAll').on('click', function () {
            var fewSeconds = 2;
            $('body #container').block({message: 'Loading...'});
            $.get('addAll.php?id=' + $('#customer_name').val() + '&customer=' + $('#customer_name').find(':selected').attr('data-mart'), function (data) {
                $("#addNewItem").append(data);
                numbering();
                $('body #container').unblock();
            })
            $('#newAll').remove();
            setTimeout(function () {
                $('body #container').unblock();
            }, fewSeconds * 500);
        });

        $(document).on('keyup', "input[name='qty[]']", function () {
            Calculate();
        });

        $(document).on('keyup', "input[name='totcarton[]']", function () {
            $("input[name='totcarton[]']").each(function (index, value) {
                var cartonvalue = ($(this).val() * $(this).parent('td').parent('tr').children('td').children('#cartonval').val());
                if(cartonvalue == "Infinity" || isNaN(cartonvalue)){
                    $(this).parent('td').parent('tr').children('td').children('#qty').val(0);
                }else{
                    $(this).parent('td').parent('tr').children('td').children('#qty').val(cartonvalue.toFixed(0));
                }
                console.log(cartonvalue);
            });
            Calculate();
        });

        $(document).on('keyup', "input[name='unitsale[]']", function () {
            Calculate();
        });

        <?php if (PROJECT_DISCOUNT == 1 || !empty($discount)) { ?>
        $('#discount').attr('required', true);
        $('#add_discount').attr('required', true);
        $(document).on('keyup', "input[name='discount']", function () {
            Calculate();
        });
        $(document).on('keyup', "input[name='add_discount']", function () {
            Calculate();
        });
        $('document').ready(function () {
            $('#discount').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter discount price</span>"
                }
            });
            $('#add_discount').rules('add', {
                required: true,
                messages: {
                    required: "<span class='label label-warning val_mes'>Please enter additional discount price</span>"
                }
            });
        });
        <?php }?>

        function Calculate() {
            var ptotal = 0;
            var totalCartons = 0;
            var totalQuantity = 0;
            var count = 0;
            $("input[name='qty[]']").each(function (index, value) {
                if (isNaN(parseFloat($(this).val())) || parseFloat($(this).val()) == '') {
                    $(this).val('0');
                } else {
                    var unitsale = $("input[name='unitsale[]']").eq(index).val();
                    if (isNaN(parseFloat(unitsale)) || parseFloat(unitsale) == '') {
                        $("input[name='unitsale[]']").eq(index).val('0');
                    }
                    ptotal += (parseFloat($(this).val()) * unitsale);
                    totalQuantity += parseFloat($(this).val());
                }
                var subtotal = parseFloat(parseFloat($(this).val()) * unitsale).toFixed(2);
                if (isNaN(subtotal)) {
                    subtotal = parseFloat(0).toFixed(2)
                }
                var cartonvalue = ($(this).val() / $(this).parent('td').parent('tr').children('td').children('#cartonval').val());
                if(cartonvalue == "Infinity" || isNaN(cartonvalue)){
                    $(this).parent('td').parent('tr').children('td').children('#totcarton').val(0);
                    totalCartons += 0;
                }else{
                    $(this).parent('td').parent('tr').children('td').children('#totcarton').val(cartonvalue.toFixed(0));
                    totalCartons += parseFloat(cartonvalue.toFixed(0));
                }
                $(this).parent('td').parent('tr').children('#subTotal').text(subtotal);
                count++;
            });

            // Update total cartons and quantities
            $('#totalCartons').text(totalCartons);
            $('#totalQuantity').text(totalQuantity);

            <?php if (PROJECT_DISCOUNT == 1 || !empty($discount)) { ?>
            $('#subAmount').text(parseFloat(ptotal).toFixed());
            var discount = $('#discount').val();
            if (isNaN(discount)) {
                discount = parseFloat(0).toFixed(2)
            }
            var discount_price = (parseFloat(ptotal) * parseFloat(discount / 100));
            $('#discount_price').val(discount_price);
            $('#discount_amount').text(discount_price);

            ptotal = ptotal - parseFloat(discount_price);
            $('#discounted_sub_total').text(ptotal);

            var add_discount = $('#add_discount').val();
            if (isNaN(add_discount)) {
                add_discount = parseFloat(0).toFixed(2)
            }
            var add_discount_price = (parseFloat(ptotal) * parseFloat(add_discount / 100));
            $('#add_discount_price').val(parseFloat(add_discount_price).toFixed(2));
            $('#add_discount_amount').text(parseFloat(add_discount_price).toFixed(2));

            ptotal = ptotal - parseFloat(add_discount_price);
            <?php }?>
            if (isNaN(ptotal)) {
                ptotal = parseFloat(0).toFixed(2)
            }
            $('#totalAmount').text(parseFloat(ptotal).toFixed());
            $('#total_price').val(parseFloat(ptotal).toFixed());
        }

        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>
</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>Invoice</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']) || isset($_GET['edit'])) {
                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;
                    $add_discount = $getInvoice->add_discount;
                    $description = $getInvoice->description;
                    $discount_price = $getInvoice->discount_price;
                    $add_discount_price = $getInvoice->add_discount_price;
                } else if (isset($_GET['add'])) {
                    $invoicefilter = " ORDER BY id DESC limit 1 ";
                    $invoices = Invoice::GetInvoiceList($invoicefilter);
                    if (!empty($invoices[0]->code)) {
                        $invoiceNumber = intval($invoices[0]->code);
                        $invoiceNumber = $invoiceNumber + 1;
                    } else {
                        $invoiceNumber = __INVOICE__;
                    }
                }
            if (isset($_POST) && !empty($_POST)) {
                extract($_REQUEST);
                $data['customer_id'] = $customer_name;
                $data['sales_person_id'] = $sales_person_id;
                $data['total_amount'] = $total_price;
                $data['discount'] = $discount;
                $data['discount_price'] = $discount_price;
                $data['add_discount'] = $add_discount;
                $data['add_discount_price'] = $add_discount_price;
                $data['create_date'] = date('Y-m-d H:i:s', strtotime(date('H:i:s'), strtotime($invoice_date)));
                $data['code'] = $invoice_number;
                $data['datetime'] = 'NOW()';
                $data['description'] = $description;

                $errors = array();
                // Validate the input

                if ((strlen($customer_name) == 0) || (strlen($customer_name) > 255))
                    array_push($errors, "Please enter customer name");
                if ((strlen($invoice_date) == 0))
                    array_push($errors, "Please enter invoice date");
                if (($total_price <= 0))
                    array_push($errors, "Total amount of invoice is not less than or equal to 0");
                if (!isset($products) || (count($products) == 0))
                    array_push($errors, "Please select atleast one product");

            if (count($errors) == 0) {
                if (isset($_GET['add'])) {
					$invoicefilter = " ORDER BY id DESC limit 1 ";
                    $invoices = Invoice::GetInvoiceList($invoicefilter);
                    if (!empty($invoices[0]->code)) {
                        $invoiceNumber = intval($invoices[0]->code);
                        $invoiceNumber = $invoiceNumber + 1;
                    } else {
                        $invoiceNumber = __INVOICE__;
                    }
					$data['code'] = $invoiceNumber;
                    $data['status'] = 'Draft';
                    $q = Invoice::AddInvoice($data);
                    foreach ($products AS $prKey => $prRow) {
                        $dataProduct['invoice_id'] = $q;
                        $dataProduct['product_id'] = $prRow;
                        $dataProduct['product_qty'] = $qty[$prKey];
                        $dataProduct['carton_piece'] = $carton_piece[$prKey];
                        $dataProduct['unit_cost_price'] = $unitcost[$prKey];
                        $dataProduct['unit_distributor_price'] = $unitdistributor[$prKey];
                        $dataProduct['unit_sale_price'] = $unitsale[$prKey];
                        $qp = Invoice::AddInvoiceProduct($dataProduct);

                        $productSetup = ProductSetup::GetProductSetupById($prRow);
                        $availability = 0;
                        $availability = $productSetup->availability;
                        $availability = ($availability - $qty[$prKey]);

                        $dataProductSetup['availability'] = $availability;
                        ProductSetup::UpdateProductSetup($prRow, $dataProductSetup);
                    }
                } elseif (isset($_GET['edit'])) {
                    $customerAmount = Invoice::GetInvoiceSetupById($_GET['id']);
                    $q = Invoice::UpdateInvoiceSetup($_GET['id'], $data);

                    $invoiceId = $_GET["id"];
                    foreach ($products AS $prKey => $prRow) {
                        $filterInvoiceProduct = " WHERE invoice_id = '$invoiceId' AND product_id = '$prRow'";
                        $productSetups = Invoice::GetInvoiceProducts($filterInvoiceProduct);
                        $productActualQty[$prRow] = intval($productSetups[0]->product_qty);
                    }
                    Invoice::DeleteInvoiceProducts($_GET['id']);
                    foreach ($products AS $prKey => $prRow) {
                        $availability = 0;
                        $dataProduct['invoice_id'] = $_GET['id'];
                        $dataProduct['product_id'] = $prRow;
                        $dataProduct['product_qty'] = $qty[$prKey];
                        $dataProduct['carton_piece'] = $carton_piece[$prKey];
                        $dataProduct['unit_cost_price'] = $unitcost[$prKey];
                        $dataProduct['unit_distributor_price'] = $unitdistributor[$prKey];
                        $dataProduct['unit_sale_price'] = $unitsale[$prKey];
                        $qp = Invoice::AddInvoiceProduct($dataProduct);

                        $productSetup = ProductSetup::GetProductSetupById($prRow);
                        $availability = $productSetup->availability;

                        if ($productActualQty[$prRow] > $qty[$prKey]) {
                            $stockableProduct = $productActualQty[$prRow] - $qty[$prKey];
                            $availability = ($stockableProduct + $availability);
                        } else if ($productActualQty[$prRow] < $qty[$prKey]) {
                            $stockableProduct = $qty[$prKey] - $productActualQty[$prRow];
                            $availability = ($availability - $stockableProduct);
                        }

                        $dataProductSetup['availability'] = $availability;
                        ProductSetup::UpdateProductSetup($prRow, $dataProductSetup);
                    }
                }
                if ($qp) {
                    $output = '';
                    ?>
                    <script>window.location.href = 'invoice.php?view&sucess'</script>
                <?php
                echo "<div id='card-alert' class='card green lighten-5'>
                          <div class='card-content green-text'>
                            <p>SUCCESS : <strong>Attention! </strong>Submitted!</p>
                          </div>
                          <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                          </button>
                        </div>";
                } else {
                    $output = '';
                    echo "<div id='card-alert' class='card orange lighten-5'>
                          <div class='card-content orange-text'>
                            <p>WARNING : <strong>Attention! </strong>Some error occurred!</p>
                          </div>
                          <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                          </button>
                        </div>";
                }
            } else {
                //Prepare errors for output
                foreach ($errors as $val) {
                    $output .= "<div id='card-alert' class='card orange lighten-5'>
                      <div class='card-content orange-text'>
                        <p>WARNING : <strong>Attention! </strong>$val</p>
                      </div>
                      <button type='button' class='close orange-text' data-dismiss='alert' aria-label='Close'>
                        <span aria-hidden='true'>x</span>
                      </button>
                    </div>";
                }
            }
            }
            ?>
                <form action="" method="post" id="invoice_create_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">
                                            <?php
                                            $customersfilter = " WHERE status = 'active' ORDER BY name";
                                            $customers = CustomerSetup::GetCustomerSetupList($customersfilter);
                                            ?>
                                            <select class="form-control" required id="customer_name"
                                                    name="customer_name">
                                                <option></option>
                                                <?php
                                                foreach ($customers AS $customersRow) {
                                                    $selected = $customersRow->id == $customer_name ? "selected" : "";
                                                    echo '<option ' . $selected . ' value="' . $customersRow->id . '" data-mart="' . $customersRow->is_mart . '" data-disperc="' . $customersRow->discount_perc . '" data-adddisperc="' . $customersRow->add_discount_perc . '" data-discountdisable="' . $customersRow->is_discountdisable . '" >' . $customersRow->name . '</option>';
                                                }
                                                ?>
                                            </select>
                                            <label for="customer_name" class="control-label">Customer *</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col m6 s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" required type="text" id="datepicker"
                                                   name="invoice_date"
                                                   placeholder="<?= date('01-01-Y') ?>"
                                                   value='<?= !empty($date) ? $date : $current_date; ?>'/><br/>
                                            <label for="invoice_date" class="control-label">Invoice Date *</label>
                                        </div>
                                    </div>
                                </div>

                            </div>
                            <div class="clearfix"></div>
                            <div class="row">
                                <div class="col m6 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="sales_person"
                                                   name="sales_person" readonly
                                                   value='<?php echo $_SESSION['sess_username']; ?>'/>
                                            <input class="form-control" type="hidden" id="sales_person_id"
                                                   name="sales_person_id"
                                                   value='<?php echo $_SESSION['sess_userid']; ?>'/><br/>
                                            <label for="sales_person" class="control-label">Sales Person *</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col m6 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="invoice_number"
                                                   name="invoice_number" readonly
                                                   value='<?php echo $invoiceNumber; ?>'/><br/>
                                            <label for="invoice_number" class="control-label">Invoice No. *</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="clearfix"></div>
                            <div class="row">
                                <div class="col m12 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="description"
                                                   name="description" maxlength="100"
                                                   value='<?php echo $description; ?>'/><br/>
                                            <label for="description" class="control-label">Description</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="clearfix"><br><br></div>
                            <div class="row">
                                <table style="margin-top: 60px;"
                                       class="bordered responsive-table table dataTable">
                                    <thead>
                                    <th>S.No</th>
                                    <th>Action</th>
                                    <th style="width: 210px;">Product Name</th>
                                    <th>Carton</th>
                                    <th>Quantity</th>
                                    <th>Unit Of Measure</th>
                                    <th>Unit Cost Price</th>
                                    <th id="distributorHeader" style="display: none;">Unit Distributor
                                        Price
                                    </th>
                                    <th>Unit Sales Price</th>
                                    <th>Sub Total</th>
                                    </thead>
                                    <tbody id="addNewItem">
                                    <?php
                                    if (isset($_GET['edit'])) {
                                        $filterinvoiceproducts = " WHERE invoice_id = '$id'";
                                        $invoiceProducts = Invoice::GetInvoiceProducts($filterinvoiceproducts);
                                        $counting = 0;
                                        foreach ($invoiceProducts AS $invoiceProductsRow) {
                                            $qry = ProductSetup::GetProductSetupById($invoiceProductsRow->product_id);
                                            if ($qry) {
                                                $counting++;
                                                echo "<tr id='tr" . $qry->id . "'>";
                                                echo '<td>' . $counting . ' </td>';
                                                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->id . '" 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="' . $qry->name . '">';
                                                echo '<input type="hidden" name="products[]" id="product" value="' . $qry->id . '">';
                                                echo '</td>';
                                                echo '<td id="carton">';
                                                echo '<input '.($qry->carton_pieces==0?'disabled':'').' value="'.($invoiceProductsRow->carton_piece != 0?($invoiceProductsRow->product_qty / $invoiceProductsRow->carton_piece):0).'" style="width:100%!important;" required maxlength="10" onkeypress="return isNumberKey(event)" class="form-control" type="text" name="totcarton'.($qry->carton_pieces==0?'1':'').'[]" id="totcarton">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isNumberKey(event)" class="form-control" type="text" onchange="handleChange' . $qry->id . '(this);" value="' . $invoiceProductsRow->product_qty . '" name="qty[]" id="qty">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input value="' . $qry->carton_pieces . '" type="hidden" name="carton_piece[]" id="cartonval">';
                                                echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $qry->unit . '">';
                                                echo '<input type="hidden" name="units[]" id="unit" value="' . $qry->unit . '">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" name="unitcost[]" value="' . $invoiceProductsRow->unit_cost_price . '" id="unitcost">';
                                                echo '</td>';
                                                echo '<td id="distributorField">';
                                                echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" name="unitdistributor[]" value="' . $invoiceProductsRow->unit_distributor_price . '" id="unitdistributor">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" name="unitsale[]"  value="' . $invoiceProductsRow->unit_sale_price . '" id="unitsale">';
                                                echo '</td>';
                                                echo '<td id="subTotal">';
                                                echo '';
                                                echo '</td>';
                                                echo "</tr>";
                                                ?>
                                                <script>
    function numbering() {
        var count = 0;
        $('#addNewItem tr td:first-child').each(function () {
            count++;
            $(this).html(count);
        });
    }
    $(document).ready(function () {
        var selectedvall = $('#customer_name').find(':selected').data('discountdisable');
        if(selectedvall == 1){
            $('#discount').attr('readonly', true);
            $('#add_discount').attr('readonly', true);
        }

        var fewSeconds = 2;
        $('#btnsubmit').click(function () {
            // Ajax request
            var btn = $(this);
            btn.hide();
            setTimeout(function () {
                btn.show();
            }, fewSeconds * 1000);
        });
        if ($('#customer_name').find(':selected').attr('data-mart') == 1) {
            $('#distributorHeader').hide();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').hide();
            });
            $('#show1').hide();
            $('#show2').hide();
            $('#show3').hide();
            $('#show4').hide();
        } else {
            $('#distributorHeader').hide();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').hide();
            });
            $('#show1').hide();
            $('#show2').hide();
            $('#show3').hide();
            $('#show4').hide();
        }
        Calculate();
    });
    $('#customer_name').on('change', function(){
        var selectedval = $(this).find(':selected').data('discountdisable');
        if(selectedval == 1){
            <?php if (isset($_GET['edit'])) {?>
            $('#discount').val(0);
            $('#add_discount').val(0);
            Calculate();
            <?php }?>
            $('#discount').attr('readonly', true);
            $('#add_discount').attr('readonly', true);
        }else{
            $('#discount').val($(this).find(':selected').data('disperc'));
            $('#discount').attr('readonly', false);
            $('#add_discount').val($(this).find(':selected').data('adddisperc'));
            $('#add_discount').attr('readonly', false);
        }
    });
    $('#customer_name').on('change', function () {
        if ($(this).find(':selected').attr('data-mart') == 1) {
            $('#distributorHeader').hide();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').hide();
//                $(this).rules('add', {
//                    required: true,
//                    messages: {
//                        required: "<span class='label label-warning val_mes'>Please enter distributor price</span>"
//                    }
//                });
            });
            $('#show1').hide();
            $('#show2').hide();
            $('#show3').hide();
            $('#show4').hide();
        } else {
            $('#distributorHeader').hide();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').hide();
            });
            $('#show1').hide();
            $('#show2').hide();
            $('#show3').hide();
            $('#show4').hide();
        }
    })

    $('#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('addItem.php?id=' + $('#productsItem').val() + '&customer=' + $('#customer_name').find(':selected').attr('data-mart') + '&customerid=' + $('#customer_name').find(':selected').val(), function (data) {
                $("#addNewItem").append(data);
                numbering();
                $('body #container').unblock();
            })
            setTimeout(function () {
                $('body #container').unblock();
            }, fewSeconds * 500);
            $('#newAll').remove();
        }
        $('#newItem').attr('disabled', false);

    });
    $('#newAll').on('click', function () {
        //alert('asdasdjaskdj');
        //$('#newAll').attr('disabled', true);
        //var product = $('#productsItem').val();
        var fewSeconds = 2;
        //if (!$('#tr' + product).html() && product != '') {
        $('body #container').block({message: 'Loading...'});
        $.get('addAll.php?id=' + $('#customer_name').val() + '&customer=' + $('#customer_name').find(':selected').attr('data-mart'), function (data) {
            $("#addNewItem").append(data);
            numbering();
            $('body #container').unblock();
        })
        $('#newAll').remove();
        setTimeout(function () {
            $('body #container').unblock();
        }, fewSeconds * 500);
        //}
        //$('#newItem').attr('disabled', false);

    });
    $(document).on('keyup', "input[name='qty[]']", function () {
        Calculate();
    });
    $(document).on('keyup', "input[name='totcarton[]']", function () {
        $("input[name='totcarton[]']").each(function (index, value) {
            var cartonvalue = ($(this).val() * $(this).parent('td').parent('tr').children('td').children('#cartonval').val());
            if(cartonvalue == "Infinity" || isNaN(cartonvalue)){
                $(this).parent('td').parent('tr').children('td').children('#qty').val(0);
            }else{
                $(this).parent('td').parent('tr').children('td').children('#qty').val(cartonvalue.toFixed(0));
            }
            console.log(cartonvalue);
            //$(this).parent('td').parent('tr').children('#subTotal').text(subtotal);
            //count++;
        });
        Calculate();
    });
    $(document).on('keyup', "input[name='unitsale[]']", function () {
        Calculate();
    });
    <?php if (PROJECT_DISCOUNT == 1 || !empty($discount)) { ?>
    $('#discount').attr('required', true);
    $('#add_discount').attr('required', true);
    $(document).on('keyup', "input[name='discount']", function () {
        Calculate();
    });
    $(document).on('keyup', "input[name='add_discount']", function () {
        Calculate();
    });
    $('document').ready(function () {
        $('#discount').rules('add', {
            required: true,
            messages: {
                required: "<span class='label label-warning val_mes'>Please enter discount price</span>"
            }
        });
        $('#add_discount').rules('add', {
            required: true,
            messages: {
                required: "<span class='label label-warning val_mes'>Please enter additional discount price</span>"
            }
        });
    });
    <?php }?>
    function Calculate() {
        var ptotal = 0;
        var count = 0;
        var totalCartons = 0;
        var totalQuantity = 0;

        $("input[name='qty[]']").each(function (index, value) {
            if (isNaN(parseFloat($(this).val())) || parseFloat($(this).val()) == '') {
                $(this).val('0');
            } else {
                var unitsale = $("input[name='unitsale[]']").eq(index).val();
                if (isNaN(parseFloat(unitsale)) || parseFloat(unitsale) == '') {
                    $("input[name='unitsale[]']").eq(index).val('0');
                }
                ptotal += (parseFloat($(this).val()) * unitsale);
            }
            var subtotal = parseFloat(parseFloat($(this).val()) * unitsale).toFixed(2);
            if (isNaN(subtotal)) {
                subtotal = parseFloat(0).toFixed(2)
            }
            var cartonvalue = ($(this).val() / $(this).parent('td').parent('tr').children('td').children('#cartonval').val());
            if(cartonvalue == "Infinity" || isNaN(cartonvalue)){
                $(this).parent('td').parent('tr').children('td').children('#totcarton').val(0);
                //$(this).parent('td').parent('tr').children('#carton').text(0);
            }else{
                $(this).parent('td').parent('tr').children('td').children('#totcarton').val(cartonvalue.toFixed(0));
                //$(this).parent('td').parent('tr').children('#carton').text(cartonvalue.toFixed(0));
            }
            totalQuantity += parseFloat($(this).val()) || 0;
            totalCartons += parseFloat(cartonvalue) || 0;

            $(this).parent('td').parent('tr').children('#subTotal').text(subtotal);
            count++;
        });
        $('#totalCartons').text(totalCartons.toFixed(0));
        $('#totalQuantity').text(totalQuantity.toFixed(0));

        <?php if (PROJECT_DISCOUNT == 1 || !empty($discount)) { ?>
        $('#subAmount').text(parseFloat(ptotal).toFixed());
        var discount = $('#discount').val();
        if (isNaN(discount)) {
            discount = parseFloat(0).toFixed(2)
        }
        var discount_price = (parseFloat(ptotal) * parseFloat(discount / 100));
        $('#discount_price').val(discount_price);
        $('#discount_amount').text(discount_price);

        ptotal = ptotal - parseFloat(discount_price);
        $('#discounted_sub_total').text(ptotal);

        var add_discount = $('#add_discount').val();
        if (isNaN(add_discount)) {
            add_discount = parseFloat(0).toFixed(2)
        }
        var add_discount_price = (parseFloat(ptotal) * parseFloat(add_discount / 100));
        $('#add_discount_price').val(parseFloat(add_discount_price).toFixed(2));
        $('#add_discount_amount').text(parseFloat(add_discount_price).toFixed(2));



        ptotal = ptotal - parseFloat(add_discount_price);
        <?php }?>
        if (isNaN(ptotal)) {
            ptotal = parseFloat(0).toFixed(2)
        }
        $('#totalAmount').text(parseFloat(ptotal).toFixed());
        $('#total_price').val(parseFloat(ptotal).toFixed());
    }
    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>

                                                <?php
                                            }
                                        }
                                    }
                                    ?>
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <td colspan="3" style="text-align: right; font-weight: bold;">Total</td>
                                            <td id="totalCartons">0</td>
                                            <td id="totalQuantity">0</td>
                                            <td colspan="5"></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                            <hr>
                            <div class="clearfix"></div>
                            <div class="row">
                                <div class="input-field col m3 col s12">
                                    <?php
                                    $filter = " where status = 'active' ORDER BY name";
                                    $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>';
                                        echo '<label for="productsItem">Products</label>';
                                    }
                                    ?>
                                </div>
                            </div>
                            <div class="row">
                                <div class="clearfix"></div>
                                <div class="col m12 col 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>
                                        <?php if (isset($_GET['add'])) { ?>
                                            <button id="newAll" type="button" class="btn waves-effect waves-light">
                                                Add All Products<i class="fa fa-plus"></i>
                                            </button>
                                        <?php } ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

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

            } // close view
            ?>
        </div>
    </div>
</div>
</div>
<?php include('../includes/inc_footer.php'); ?>

<?php include('../includes/inc_js.php'); ?>
</body>
</html>
