<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$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,
            });
        });
    </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;
                    $po_number = $getInvoice->po_number;
                } 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;
                    $data['po_number'] = $po_number;

                    $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) {
                                $productSetup = ProductSetup::GetProductSetupById($prRow);
                                if (!$productSetup) {
                                    array_push($errors, "Product setup not found for product ID " . $prRow);
                                    continue;
                                }

                                $dataProduct['invoice_id'] = $q;
                                $dataProduct['product_id'] = $prRow;
                                $dataProduct['product_qty'] = $qty[$prKey];
                                $dataProduct['carton_piece'] = $carton_piece[$prKey];
                                // Cost price must always come from product_setup, not invoice_rate or posted form value
                                $dataProduct['unit_cost_price'] = $productSetup->cost_price;
                                $dataProduct['unit_distributor_price'] = $unitdistributor[$prKey];
                                $dataProduct['unit_sale_price'] = $unitsale[$prKey];
                                $qp = Invoice::AddInvoiceProduct($dataProduct);

                                $availability = 0;
                                $availability = $productSetup->availability;
                                $availability = ($availability - $qty[$prKey]);

                                $dataProductSetup['availability'] = $availability;
                                ProductSetup::UpdateProductSetup($prRow, $dataProductSetup);

                                // Ledger Edit Functionality Product Add
                                //$ledger = Ledger::GetLedgerSetupByHead('product', $prRow);
                                //$ledgreFigure = $ledger->figure;
                                //$ledgreFigure += $qty[$prKey];

                                //$dataLedger['figure'] = $ledgreFigure;
                                //$dataLedger['datetime'] = 'NOW()';

                                //$led = Ledger::UpdateLedgerSetup($ledger->id, $dataLedger);
                                // Ledger Edit Functionality Customer Add
                            }

                            // Ledger Edit Functionality Customer Add
                            //$dataLedger = '';
                            //$ledgreFigure = 0;

                            //$ledger = Ledger::GetLedgerSetupByHead('customer', $customer_name);
                            //$ledgreFigure = $ledger->figure;
                            //$ledgreFigure += $total_price;

                            //$dataLedger['figure'] = $ledgreFigure;
                            //$dataLedger['datetime'] = 'NOW()';

                            //$led = Ledger::UpdateLedgerSetup($ledger->id, $dataLedger);
                            // Ledger Edit Functionality Customer Add

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

                            // Ledger Edit Functionality Customer Add
                            //$dataLedger = '';
                            //$ledgreFigure = 0;

                            //$ledger = Ledger::GetLedgerSetupByHead('customer', $customer_name);
                            //$ledgreFigure = $ledger->figure;

                            if ($customerAmount->total_amount > $total_price) {
                                $totalCustomer = $customerAmount->total_amount - $total_price;
                                //$ledgreFigure = ($ledgreFigure - $totalCustomer);
                            } else if ($customerAmount->total_amount < $total_price) {
                                $totalCustomer = $total_price - $customerAmount->total_amount;
                                //$ledgreFigure = ($totalCustomer + $ledgreFigure);
                            }

                            //$dataLedger['figure'] = $ledgreFigure;
                            //$dataLedger['datetime'] = 'NOW()';
                            //$led = Ledger::UpdateLedgerSetup($ledger->id, $dataLedger);
                            // Ledger Edit Functionality Customer Add
                            $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);
                            }
                            //print_r($productActualQty);
                            //echo 'asdasd';
                            Invoice::DeleteInvoiceProducts($_GET['id']);
                            foreach ($products AS $prKey => $prRow) {
                                $availability = 0;
                                $productSetup = ProductSetup::GetProductSetupById($prRow);
                                if (!$productSetup) {
                                    array_push($errors, "Product setup not found for product ID " . $prRow);
                                    continue;
                                }

                                $dataProduct['invoice_id'] = $_GET['id'];
                                $dataProduct['product_id'] = $prRow;
                                $dataProduct['product_qty'] = $qty[$prKey];
                                $dataProduct['carton_piece'] = $carton_piece[$prKey];
                                // Cost price must always come from product_setup, not invoice_rate or posted form value
                                $dataProduct['unit_cost_price'] = $productSetup->cost_price;
                                $dataProduct['unit_distributor_price'] = $unitdistributor[$prKey];
                                $dataProduct['unit_sale_price'] = $unitsale[$prKey];
                                $qp = Invoice::AddInvoiceProduct($dataProduct);

                                $availability = $productSetup->availability;

                                // Ledger Edit Functionality Product Add
                                //$dataLedger = '';
                                //$ledgreFigure = 0;
                                //$ledger = Ledger::GetLedgerSetupByHead('product', $prRow);
                                //$ledgreFigure = $ledger->figure;

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

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

                                    //$ledgreFigure = ($stockableProduct + $ledgreFigure);
                                }

                                $dataProductSetup['availability'] = $availability;
                                ProductSetup::UpdateProductSetup($prRow, $dataProductSetup);


                                //$dataLedger['figure'] = $ledgreFigure;
                                //$dataLedger['datetime'] = 'NOW()';
                                //$led = Ledger::UpdateLedgerSetup($ledger->id, $dataLedger);
                                // Ledger Edit Functionality Customer Add
                            }
                        }
                        //exit;
                        if ($qp) {
                            $output = '';
                            //header("Location: invoice.php?view&sucess"); ?>
                            <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'";
                                            $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 s6">-->
                                <!--                                                <label class="control-label">Payment Type *</label>-->
                                <!--                                                <select class="form-control" id="payment_type" name="payment_type">-->
                                <!--                                                    <option></option>-->
                                <!--                                                    <option value="cash">Cash</option>-->
                                <!--                                                    <option value="cheque">Cheque</option>-->
                                <!--                                                </select><br/>-->
                                <!--                                            </div>-->
                                <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 m6 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 class="col m6 col s12">
                                    <div class="row margin">
                                        <div class="input-field col s12">
                                            <input class="form-control" type="text" id="po_number"
                                                   name="po_number" maxlength="100"
                                                   value='<?php echo $po_number; ?>'/><br/>
                                            <label for="po_number" class="control-label">PO Number</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)" readonly class="form-control" type="text" name="unitcost[]" value="' . $qry->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>
                                                    $('#trashing<?=$qry->id?>').on('click', function () {
                                                        $(this).parent('td').parent('tr').remove();
                                                        numbering();
                                                        Calculate();
                                                    });
                                                    function handleChange<?=$qry->id?>(input) {
                                                        var total = <?=($qry->availability+$invoiceProductsRow->product_qty)?>;
                                                        if (input.value < 0) input.value = 0;
                                                        if (input.value > total) {
                                                            input.value = total;
                                                            dialog.alert({
                                                                title: "Stock Availability",
                                                                message: "Stock not available, max " + total,
                                                                button: "Close",
                                                                animation: "fade",
                                                                callback: function (value) {
                                                                    console.log(value);
                                                                }
                                                            });
                                                            return false;
                                                        }
                                                    }
                                                </script>
                                                <?php
                                            }
                                        }
                                    }
                                    ?>
                                    </tbody>
                                    <tbody>
                                    <?php
                                    if (PROJECT_DISCOUNT == 1 || !empty($discount)) { ?>
                                        <tr>
                                            <td id="show1" style="display: none;"></td>
                                            <td colspan="8" style="text-align: right;">Sub Total</td>
                                            <td id="subAmount">0</td>
                                        </tr>
                                      <tr>
                                        <td></td>
                                        <td></td>
                                        <td><strong>Totals:</strong></td>
                                        <!-- Carton total under Carton column -->
                                        <td id="totalCartons"></td>
                                        <!-- Quantity total under Quantity column -->
                                        <td id="totalQty"></td>
                                        <!-- Remaining columns (UOM, Unit Cost, Distributor, Unit Sales, Sub Total) -->
                                        <td colspan="5"></td>
                                    </tr>
                                        <tr>
                                            <td id="show2" style="display: none;"></td>
                                            <td colspan="8"
                                                style="text-align: right; vertical-align: middle;">
                                                Discount (%)
                                            </td>
                                            <td><input style="width:100%!important;"
                                                       class="form-control" type="text" name="discount"
                                                       id="discount" maxlength="2"
                                                       onkeypress="return isNumberKey(event)"
                                                       value="<?= $discount ?>">
                                                <input style="width:100%!important;"
                                                       class="form-control" type="hidden"
                                                       name="discount_price"
                                                       id="discount_price"
                                                       value="<?= $discount_price ?>">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td id="show3" style="display: none;"></td>
                                            <td colspan="8"
                                                style="text-align: right; vertical-align: middle;">
                                                Discount Amount
                                            </td>
                                            <td id="discount_amount">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td id="show3" style="display: none;"></td>
                                            <td colspan="8"
                                                style="text-align: right; vertical-align: middle;">
                                                Discounted Sub Total
                                            </td>
                                            <td id="discounted_sub_total">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td id="show2" style="display: none;"></td>
                                            <td colspan="8"
                                                style="text-align: right; vertical-align: middle;">
                                                Additional Discount (%)
                                            </td>
                                            <td>
                                                <input style="width:100%!important;"
                                                       class="form-control" type="text" name="add_discount"
                                                       id="add_discount" maxlength="2"
                                                       onkeypress="return isNumberKey(event)"
                                                       value="<?= $add_discount ?>" />
                                                <input style="width:100%!important;"
                                                       class="form-control" type="hidden"
                                                       name="add_discount_price"
                                                       id="add_discount_price"
                                                       value="<?= $add_discount_price ?>" readonly/>
                                            </td>

                                        </tr>
                                        <tr>
                                            <td id="show3" style="display: none;"></td>
                                            <td colspan="8"
                                                style="text-align: right; vertical-align: middle;">
                                                Additional Discount Amount
                                            </td>
                                            <td id="add_discount_amount">
                                            </td>
                                        </tr>
                                    <?php } ?>
                                    <tr>
                                        <td id="show4" style="display: none;"></td>
                                        <td colspan="8" style="text-align: right;">Total</td>
                                        <td id="totalAmount">0</td>
                                        <input type="hidden" name="total_price" id="total_price"/>
                                    </tr>

                                    <!-- NEW: Totals row for Cartons & Quantity -->
                                    

                                    </tbody>
                                </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'); ?>
<script type="application/javascript">
    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', true);
        }
    });
    $('#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);
    });

    /* ---------- NEW carton/qty logic (same pattern as previous invoice) ---------- */

    // When user types in QTY, recalc that row + totals
    $(document).on('input', "input[name='qty[]']", function () {
        var tr = $(this).closest('tr');
        recalcRow(tr, {driver: 'qty'});
        Calculate();
    });

    // When user types in CARTON (totcarton[] or totcarton1[]), recalc that row + totals
    $(document).on('input', "input[name^='totcarton']", function () {
        var tr = $(this).closest('tr');
        recalcRow(tr, {driver: 'carton'});
        Calculate();
    });

    // When user changes unit sale price, update subtotal + totals
    $(document).on('input', "input[name='unitsale[]']", function () {
        var tr = $(this).closest('tr');
        recalcRow(tr, {driver: 'price'});
        Calculate();
    });

    // Per-row recalculation helper
    function recalcRow(tr, opts) {
        var driver = (opts && opts.driver) || 'qty';

        var qtyInput        = tr.find("input[name='qty[]']");
        var cartonsInput    = tr.find("input[name^='totcarton']");
        var cartonPiecesInp = tr.find("input[name='carton_piece[]']");
        var unitSaleInp     = tr.find("input[name='unitsale[]']");
        var subTotalCell    = tr.find("td#subTotal");

        var cp      = parseFloat(cartonPiecesInp.val()); if (isNaN(cp)) cp = 0;
        var cartons = parseFloat(cartonsInput.val());    if (isNaN(cartons)) cartons = 0;
        var qty     = parseFloat(qtyInput.val());        if (isNaN(qty)) qty = 0;
        var price   = parseFloat(unitSaleInp.val());     if (isNaN(price)) price = 0;

        if (driver === 'carton') {
            if (cp > 0) {
                qty = Math.max(0, Math.floor(cartons * cp));
                qtyInput.val(qty);
            }
        } else if (driver === 'qty') {
            if (cp > 0) {
                var c = Math.floor(qty / cp);
                cartonsInput.val(c);
            } else {
                cartonsInput.val(0);
            }
        }

        var sub = qty * price;
        subTotalCell.text(isFinite(sub) ? sub.toFixed(2) : '0.00');
    }

    <?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 totalQty = 0;

        $("#addNewItem tr").each(function () {
            var tr = $(this);

            var qty = parseFloat(tr.find("input[name='qty[]']").val());
            if (isNaN(qty)) qty = 0;

            var price = parseFloat(tr.find("input[name='unitsale[]']").val());
            if (isNaN(price)) price = 0;

            var cp = parseFloat(tr.find("input[name='carton_piece[]']").val());
            if (isNaN(cp)) cp = 0;

            var sub = qty * price;
            tr.find("td#subTotal").text(isFinite(sub) ? sub.toFixed(2) : '0.00');
            ptotal += isFinite(sub) ? sub : 0;

            totalQty += qty;

            if (cp > 0) {
                var c = Math.floor(qty / cp);
                tr.find("input[name^='totcarton']").val(c);
                totalCartons += c;
            } else {
                tr.find("input[name^='totcarton']").val(0);
            }
        });

        $('#totalCartons').text(totalCartons.toFixed(0));
        $('#totalQty').text(totalQty.toFixed(0));

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

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

        <?php if (PROJECT_TAX == 1 || !empty($tax)) { ?>
        var tax = parseFloat($('#tax').val());
        if (isNaN(tax)) {
            tax = 0;
        }
        var tax_price = (ptotal * tax / 100);
        $('#tax_price').val(tax_price.toFixed(2));
        $('#tax_amount').text(tax_price.toFixed(2));
        ptotal += tax_price;

        var adv_tax = parseFloat($('#adv_tax').val());
        if (isNaN(adv_tax)) {
            adv_tax = 0;
        }
        var adv_tax_price = (ptotal * adv_tax / 100);
        $('#adv_tax_price').val(adv_tax_price.toFixed(2));
        $('#adv_tax_amount').text(adv_tax_price.toFixed(2));
        ptotal += adv_tax_price;
        <?php } ?>

        if (isNaN(ptotal)) {
            ptotal = 0;
        }
        $('#totalAmount').text(ptotal.toFixed(2));
        $('#total_price').val(ptotal.toFixed(2));
    }

    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>
