<?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');
if (isset($_POST) && !empty($_GET['delete'])) {
    RateList::DeleteInvoiceRate($_GET['delete']);
    RateList::DeleteInvoiceRateDetails($_GET['delete']);
    header("Location: " . PROJECT_ADMIN_URL . "transaction/rate_list.php?view");
    exit();
}
$param_data = ControlConfifguration::GetConfiguration();
define('PROJECT_NAME', $param_data->name);
define('PROJECT_ADDRESS', $param_data->address);
define('PROJECT_TEL', $param_data->contact);
define('PROJECT_EMAIL', $param_data->email);
define('PROJECT_WEBSITE', $param_data->website);
define('PROJECT_COLOR', $param_data->color);
define('PROJECT_DISCOUNT', $param_data->is_discount);
define('PROJECT_TAX', $param_data->is_tax);
define('PROJECT_TAX_AMOUNT',$param_data->tax);

if (PROJECT_TAX == 1) {
    $tax = PROJECT_TAX_AMOUNT;
    $is_tax = PROJECT_TAX;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
    <script>
        $(function () {
            $('#datepicker').pickadate({
                format: 'dd-mm-yyyy',
                selectMonths: true,
              selectYears: true, // Creates a dropdown to control year
            });
        });
    </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($_POST) && !empty($_POST)) {
                    extract($_REQUEST);
                    $data['customer_name'] = $customer_name;
                    $data['type'] = $type;
                    $data['rate_date'] = date('Y-m-d H:i:s', strtotime($invoice_date));
                    $data['create_date'] = date('Y-m-d H:i:s');
                    //$checkInvoiceRate = RateList::CheckRateList($customer_name, 0);

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

                    if ((strlen($customer_name) == 0))
                        array_push($errors, "Please enter customer name");

                if (count($errors) == 0) {
                    $q = RateList::AddRateList($data);

                if ($q) {
                    if ($products) {
                        $dataProductRate['rate_list_id'] = $q;
                        $countrate = 0;
                        foreach ($products AS $productValue) {
                            $dataProductRate['tp_rate'] = $tpRate[$countrate];
                            $dataProductRate['discount'] = $discountProducts[$countrate];
                            $dataProductRate['gst'] = $gstProducts[$countrate];
                            $dataProductRate['piece_carton'] = $piece_carton[$countrate];
                            $dataProductRate['product_id'] = $productValue;
                            //print_r($dataProductRate);
                            RateList::AddRateListDetail($dataProductRate);
                            $countrate++;
                        }
                    }

                    $output = '';
                    //header("Location: ?view&sucess"); ?>
                    <script>window.location.href = '?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="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="10"/>
                                            <label for="discount_input" class="control-label">Discount(%)</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="col m6 s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <select class="form-control" id="type" name="type">
                                                <option value="tp">T.P Rate</option>
                                                <option value="net">Net Rate</option>
                                            </select>
                                            <label for="discount_input" class="control-label">Type</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># of Pieces</th>
                                    <th>T.P</th>
                                    <th>Discount</th>
                                    <th>Sub Total</th>
                                    <th>GST</th>
                                    <th>Sub Total With GST</th>
                                    </thead>
                                    <tbody id="addNewItem">
                                    <?php
                                    if (isset($_GET['add'])) {
                                        $filterproducts = " WHERE status = 'active' order by product_order";
                                        $product = ProductSetup::GetProductSetupList($filterproducts);

                                        foreach ($product AS $invoiceProductsRow) {
                                            $qry = $invoiceProductsRow->id;
                                            $productName = $invoiceProductsRow->name;
                                            $productBarcode = $invoiceProductsRow->barcode;
                                            $productWeight = $invoiceProductsRow->weight . ' ' . $invoiceProductsRow->unit;
                                            $pieceCarton = $invoiceProductsRow->carton_pieces;
                                            $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 required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" style="width:100%!important;" type="text" name="piece_carton[]" value="' . $pieceCarton . '">';
                                                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 '<td>';
                                                echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="'.$tax.'" id="gstProductsText">';
                                                echo '<input type="hidden" name="gstProducts[]" id="gstProducts" value="'.$tax.'">';
                                                echo '</td>';
                                                echo '<td id="subTotalWGST">';
                                                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' 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>';
                                    }
                                    ?>
                                </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">Submit</button>
                    <button type="button" class="btn waves-effect waves-light"
                            onclick="location.href='?view'">Cancel
                    </button>
                </form>
                <?php

            } // close view

            if (isset($_GET['view'])) {

                ?>
                <?php if (isset($_GET['sucess'])) { ?>
                    <div id='card-alert' class='card green lighten-5'>
                        <div class='card-content green-text'>
                            <p>Successfully updated!</p>
                        </div>
                        <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>x</span>
                        </button>
                    </div>
                <?php } ?>
                <?php if (isset($_GET['error'])) { ?>
                    <div id='card-alert' class='card orange lighten-5'>
                        <div class='card-content orange-text'>
                            <p>WARNING : <strong>Attention! </strong>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>
                <?php } ?>
                <div class="table-datatables">
                    <table id="data-table-simple" class="responsive-table display">
                        <thead>
                        <tr>
                            <th>Action</th>
                            <th>Customer Name</th>
                            <th>Type</th>
                            <th>Date</th>
                        </tr>
                        </thead>
                        <tfoot>
                        <tr>
                            <th>Action</th>
                            <th>Customer Name</th>
                            <th>Type</th>
                            <th>Date</th>
                        </tr>
                        </tfoot>
                        <tbody>
                        <?php
                        $qry = RateList::GetRateListList();
                        if ($qry) {
                            foreach ($qry as $qery) {
                                ?>
                                <tr>
                                    <td>
                                        <?php
                                        if ($_SESSION['sess_role'] == 'VEC' || $_SESSION['sess_role'] == 'VE') {
                                            ?>

                                            <a style="cursor:pointer;font-size: 10px;padding: 1px;" title="Delete">
                                                <span
                                                    style="width: 60px; height: 20px; border-radius: 5%; font-size: 12px; line-height: 20px;"
                                                    class="btn-warning-confirm<?= $qery->id ?> mini-stat-icon deep-orange darken-2"><i class="fa fa-arrows-alt">Delete</i></span>
                                            </a>
                                            <script>
                                                $('.btn-warning-confirm<?= $qery->id ?>').click(function () {
                                                    swal({
                                                            title: "Are you sure?",
                                                            text: "Are you sure you want to delete?",
                                                            type: "warning",
                                                            showCancelButton: true,
                                                            confirmButtonColor: '#DD6B55',
                                                            confirmButtonText: 'Yes',
                                                            closeOnConfirm: false
                                                        },
                                                        function () {
                                                            swal("Successful!", "Your status has been cancelled!", "success");
                                                            window.location.href = 'rate_list.php?delete=<?php echo $qery->id; ?>';
                                                        });
                                                });
                                            </script>

                                            <a href="print/ratelist.php?id=<?php echo $qery->id; ?>"
                                               target="_blank" title="Print Invoice">
                                                                    <span
                                                                        style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
                                                                        class="mini-stat-icon orange darken-2"><i
                                                                            class="mdi-action-print"></i></span>
                                            </a>
                                            <a href="?edit&id=<?php echo $qery->id; ?>" title="Edit">
                                                    <span
                                                        style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
                                                        class="mini-stat-icon orange"><i
                                                            class="mdi-image-edit"></i></span>
                                            </a>
                                        <?php } else { ?>
                                            <a href="?edit&id=<?php echo $qery->id; ?>&v" title="View">
                                                    <span
                                                        style="width: 20px; height: 20px; font-size: 12px; line-height: 20px;"
                                                        class="mini-stat-icon pink"><i
                                                            class="mdi-action-description"></i></span>
                                            </a>
                                        <?php } ?>
                                    </td>
                                    <td><?php echo ucwords($qery->customer_name); ?></td>
                                    <td><?php echo $qery->type=='tp'?'T.P Rate':'Net Rate'; ?></td>
                                    <td><?php echo date('Y-m-d h:i:s', strtotime($qery->create_date)); ?></td>
                                </tr>
                                <?php
                            }
                        } ?>
                        </tbody>
                    </table>
                </div>
                <?php

            } // close view

            if (isset($_GET['edit']) && !empty($_POST)) {
                extract($_REQUEST);
                $id = $_GET['id'];

                $data['customer_name'] = $customer_name;
                $data['type'] = $type;
                $data['rate_date'] = date('Y-m-d H:i:s', strtotime($invoice_date));
                $data['create_date'] = date('Y-m-d H:i:s');
                //$checkInvoiceRate = RateList::CheckRateList($customer_name, $id);

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

                if ((strlen($customer_name) == 0))
                    array_push($errors, "Please enter customer name");

//                if ($checkInvoiceRate)
//                    array_push($errors, "Customer already exist");
                if (count($errors) == 0) {
                    if(isset($saveas)){
                        $q = RateList::AddRateList($data);
                        $dataProductRate['rate_list_id'] = $q;
                    }else{
                        $q = RateList::UpdateRateListSetup($id, $data);
                        $dataProductRate['rate_list_id'] = $id;
                    }
                    if ($q) {
                        if(!isset($saveas)) {
                            RateList::DeleteInvoiceRateDetails($id);
                        }
                        if ($products) {
                            $countrate = 0;
                            foreach ($products AS $productValue) {
                                $dataProductRate['tp_rate'] = $tpRate[$countrate];
                                $dataProductRate['discount'] = $discountProducts[$countrate];
                                $dataProductRate['gst'] = $gstProducts[$countrate];
                                $dataProductRate['piece_carton'] = $piece_carton[$countrate];
                                $dataProductRate['product_id'] = $productValue;
                                //print_r($dataProductRate);
                                RateList::AddRateListDetail($dataProductRate);
                                $countrate++;
                            }
                        }
                        $output = '';
                        //header("Location: ?view&sucess"); ?>
                        <script>window.location.href = '?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>";
                    }
                }
            }
            if (isset($_GET['edit'])) {
                $id = $_GET['id'];
                if (empty($_POST)) {
                    $qry = RateList::GetRateListSetupById($id);
                    $customer_name = $qry->customer_name;
                    $type = $qry->type;
                    $invoice_date = date('d-m-Y', strtotime($qry->rate_date));
                }
                $filterRatelist = " WHERE rate_list_id = '".$id."'";
                $ratelistdetail = RateList::GetRateListDetails($filterRatelist);

                if ($_REQUEST['id']) {
                    ?>
                    <div class="row">
                        <!--  The form that will be parsed by jQuery before submit  -->
                        <form action="?edit&id=<?php echo $id ?>" 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"
                                                           value="<?=$customer_name?>"
                                                           name="customer_name"/>
                                                    <label for="customer_name" class="control-label active">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"
                                                           value="<?=$invoice_date?>"
                                                           name="invoice_date"/>
                                                    <label for="datepicker" class="control-label active">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"
                                                           value="<?=$ratelistdetail[0]->discount?>"
                                                           onkeypress="return isDoubleNumberKey(event)"
                                                           maxlength="5"/>
                                                    <label for="discount_input" class="control-label active">Discount(%)</label>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col m6 s12">
                                            <div class="row margin">
                                                <div class="input-field col s12">
                                                    <select class="form-control" id="type" name="type">
                                                        <option <?=$type=='tp'?'selected':''?> value="tp">T.P Rate</option>
                                                        <option <?=$type=='net'?'selected':''?> value="net">Net Rate</option>
                                                    </select>
                                                    <label for="discount_input" class="control-label">Type</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># of Pieces</th>
                                            <th>T.P</th>
                                            <th>Discount</th>
                                            <th>Sub Total</th>
                                            <th>GST</th>
                                            <th>Sub Total With GST</th>
                                            </thead>
                                            <tbody id="addNewItem">
                                            <?php
                                            if (isset($_GET['edit'])) {
                                                $filterproducts = " WHERE status = 'active' order by product_order";
                                                $product = ProductSetup::GetProductSetupList($filterproducts);

                                               foreach ($product AS $invoiceProductsRow) {
                                                    $qry = $invoiceProductsRow->id;
                                                    $productName = $invoiceProductsRow->name;
                                                    $productBarcode = $invoiceProductsRow->barcode;
                                                    $productWeight = $invoiceProductsRow->weight . ' ' . $invoiceProductsRow->unit;
                                                    $pieceCarton = $invoiceProductsRow->carton_pieces;
                                                    $productTPRate = $invoiceProductsRow->tp_rate;
                                                   foreach($ratelistdetail AS $ratelistdetails){
                                                       if($qry == $ratelistdetails->product_id){
                                                           if($ratelistdetails->tp_rate != $productTPRate){
                                                               $productTPRate = $ratelistdetails->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 required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" name="piece_carton[]" style="width:100%!important;" type="text" value="' . $pieceCarton . '">';
                                                        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 '<td>';
                                                        echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="'.$tax.'" id="gstProductsText">';
                                                        echo '<input type="hidden" name="gstProducts[]" id="gstProducts" value="'.$tax.'">';
                                                        echo '</td>';
                                                        echo '<td id="subTotalWGST">';
                                                        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' 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>';
                                            }
                                            ?>
                                        </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>
                            <?php
                            if (isset($_GET['edit'])){
                            ?>
                            <button id="btnsubmit" name="saveas" type="submit" class="btn waves-effect waves-light">Save As</button>
                            <?php } ?>
                            <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='?view'">Cancel
                            </button>
                        </form>
                    </div>
                <?php } ?>

                <?php
            }
            ?>
        </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);
            var taxAmount = <?=$tax?>;
            var totalAMount = parseFloat(parseFloat(subtotal)+((parseFloat(subtotal)*parseFloat(taxAmount))/100)).toFixed(2);
            $(this).parent('td').parent('tr').children('#subTotalWGST').text(totalAMount);
            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>