<?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");

                    // Helper: total sell qty per product (so we can pre-check stock sufficiency)
                    $sellQtyMap = [];
                    if (!empty($products) && is_array($products)) {
                        foreach ($products as $k => $pid) {
                            $p = (int)$pid;
                            $q = isset($qty[$k]) ? (int)$qty[$k] : 0;
                            if ($p > 0 && $q > 0) {
                                if (!isset($sellQtyMap[$p])) $sellQtyMap[$p] = 0;
                                $sellQtyMap[$p] += $q;
                            }
                        }
                    }

                    // Pre-check stock availability per product (FIFO lots sum)
                    if (count($errors) == 0 && !empty($sellQtyMap)) {
                        global $db;

                        // When editing, add back the invoice's prior usage to availability
                        $priorUse = [];
                        if (isset($_GET['edit']) && !empty($_GET['id'])) {
                            $invoiceId = (int)$_GET['id'];
                            $rows = $db->fetch_all_array("
                                SELECT product_id, SUM(qty_used) AS used
                                FROM ".TABLE_INVOICE_STOCK_USAGE."
                                WHERE invoice_id = '{$invoiceId}'
                                GROUP BY product_id
                            ");
                            if ($rows && $db->affected_rows > 0) {
                                foreach ($rows as $r) {
                                    $priorUse[(int)$r->product_id] = (int)$r->used;
                                }
                            }
                        }

                        foreach ($sellQtyMap as $pid => $needQty) {
                            // sum remaining across lots
                            $sumRow = $db->query_first("
                                SELECT SUM(remaining_qty) AS rem
                                FROM ".TABLE_STOCK."
                                WHERE product_id='".(int)$pid."' AND remaining_qty>0
                            ");
                            $available = ($sumRow && isset($sumRow->rem)) ? (int)$sumRow->rem : 0;

                            // add back what this invoice had previously deducted (edit mode)
                            if (isset($priorUse[$pid])) {
                                $available += $priorUse[$pid];
                            }

                            if ($available < $needQty) {
                                $errors[] = "Insufficient stock for product ID $pid. Available $available, required $needQty.";
                            }
                        }
                    }


                    if (count($errors) == 0) {
                        global $db;

                        // Wrap everything in a transaction for consistency
                        $db->query("START TRANSACTION");
                        $okAll = true;
                        $qp = false; // last added invoice product id (kept for your redirect condition)

                        try {
                            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); // header insert -> invoice id

                                if (!$q) {
                                    throw new Exception("Failed to create invoice header.");
                                }

                                // For each product row
                                foreach ($products AS $prKey => $prRow) {
                                    $prodId = (int)$prRow;
                                    $sellQty = isset($qty[$prKey]) ? (int)$qty[$prKey] : 0;
                                    if ($prodId <= 0 || $sellQty <= 0) continue;

                                    $dataProduct = [];
                                    $dataProduct['invoice_id'] = $q;
                                    $dataProduct['product_id'] = $prodId;
                                    $dataProduct['product_qty'] = $sellQty; // final sold qty
                                    $dataProduct['carton_piece'] = isset($carton_piece[$prKey]) ? $carton_piece[$prKey] : 0;
                                    $dataProduct['unit_cost_price'] = isset($unitcost[$prKey]) ? $unitcost[$prKey] : 0; // keep existing fields
                                    $dataProduct['unit_distributor_price'] = 0;
                                    $dataProduct['unit_sale_price'] = isset($unitsale[$prKey]) ? $unitsale[$prKey] : 0;

                                    $qp = Invoice::AddInvoiceProduct($dataProduct); // line insert -> invoice_item_id
                                    if (!$qp) {
                                        throw new Exception("Failed to create invoice item for product $prodId.");
                                    }

                                    // FIFO Deduct from stock & record usage
                                    $left = $sellQty;
                                    $lots = $db->fetch_all_array("SELECT * FROM ".TABLE_STOCK."
                                              WHERE product_id='$prodId' AND remaining_qty > 0
                                              ORDER BY datetime ASC, id ASC");
                                    if (!$lots || $db->affected_rows == 0) {
                                        throw new Exception("Insufficient stock for product $prodId (no lots available).");
                                    }

                                    foreach ($lots as $lot) {
                                        if ($left <= 0) break;
                                        $avail = (int)$lot->remaining_qty;
                                        if ($avail <= 0) continue;

                                        $take = ($left <= $avail) ? $left : $avail;

                                        // update lot
                                        $db->query_update(TABLE_STOCK, [
                                            'deducted_qty'  => ((int)$lot->deducted_qty + $take),
                                            'remaining_qty' => ($avail - $take)
                                        ], "id='".(int)$lot->id."'");

                                        // record usage
                                        $isuData = [
                                            'invoice_id'       => $q,
                                            'invoice_item_id'  => $qp,
                                            'stock_id'         => (int)$lot->id,
                                            'purchase_id'      => (int)$lot->purchase_id,
                                            'purchase_item_id' => (int)$lot->purchase_item_id,
                                            'product_id'       => $prodId,
                                            'qty_used'         => $take,
                                            'unit_cost'        => $lot->unit_cost,
                                            'datetime'         => 'NOW()'
                                        ];
                                        // simple insert
                                        $isuId = $db->query_insert(TABLE_INVOICE_STOCK_USAGE, $isuData);
                                        if (!$isuId) {
                                            throw new Exception("Failed to write invoice stock usage for product $prodId.");
                                        }
                                        $left -= $take;
                                    }

                                    if ($left > 0) {
                                        throw new Exception("Insufficient stock for product $prodId (short by $left).");
                                    }
                                } // end foreach product

                            } elseif (isset($_GET['edit'])) {
                                // UPDATE header
                                $invoiceId = (int)$_GET['id'];
                                $q = Invoice::UpdateInvoiceSetup($invoiceId, $data);

                                if ($q === -1) {
                                    throw new Exception("Failed to update invoice header.");
                                }

                                // RESTOCK prior usage for this invoice
                                $usages = $db->fetch_all_array("SELECT * FROM ".TABLE_INVOICE_STOCK_USAGE." WHERE invoice_id='$invoiceId'");
                                if ($usages && $db->affected_rows > 0) {
                                    foreach ($usages as $u) {
                                        $db->query("UPDATE ".TABLE_STOCK."
                                                    SET deducted_qty = deducted_qty - ".(int)$u->qty_used.",
                                                        remaining_qty = remaining_qty + ".(int)$u->qty_used."
                                                    WHERE id = ".(int)$u->stock_id);
                                    }
                                    // clear usage rows
                                    $db->query("DELETE FROM ".TABLE_INVOICE_STOCK_USAGE." WHERE invoice_id='$invoiceId'");
                                }

                                // Delete existing invoice items
                                Invoice::DeleteInvoiceProducts($invoiceId);

                                // Reinsert items + FIFO deduct again
                                foreach ($products AS $prKey => $prRow) {
                                    $prodId = (int)$prRow;
                                    $sellQty = isset($qty[$prKey]) ? (int)$qty[$prKey] : 0;
                                    if ($prodId <= 0 || $sellQty <= 0) continue;

                                    $dataProduct = [];
                                    $dataProduct['invoice_id'] = $invoiceId;
                                    $dataProduct['product_id'] = $prodId;
                                    $dataProduct['product_qty'] = $sellQty;
                                    $dataProduct['carton_piece'] = isset($carton_piece[$prKey]) ? $carton_piece[$prKey] : 0;
                                    $dataProduct['unit_cost_price'] = isset($unitcost[$prKey]) ? $unitcost[$prKey] : 0;
                                    $dataProduct['unit_distributor_price'] = 0;
                                    $dataProduct['unit_sale_price'] = isset($unitsale[$prKey]) ? $unitsale[$prKey] : 0;

                                    $qp = Invoice::AddInvoiceProduct($dataProduct);
                                    if (!$qp) {
                                        throw new Exception("Failed to create invoice item for product $prodId (edit).");
                                    }

                                    // FIFO Deduct for edit
                                    $left = $sellQty;
                                    $lots = $db->fetch_all_array("SELECT * FROM ".TABLE_STOCK."
                                              WHERE product_id='$prodId' AND remaining_qty > 0
                                              ORDER BY datetime ASC, id ASC");
                                    if (!$lots || $db->affected_rows == 0) {
                                        throw new Exception("Insufficient stock for product $prodId (no lots available).");
                                    }

                                    foreach ($lots as $lot) {
                                        if ($left <= 0) break;
                                        $avail = (int)$lot->remaining_qty;
                                        if ($avail <= 0) continue;

                                        $take = ($left <= $avail) ? $left : $avail;

                                        $db->query_update(TABLE_STOCK, [
                                            'deducted_qty'  => ((int)$lot->deducted_qty + $take),
                                            'remaining_qty' => ($avail - $take)
                                        ], "id='".(int)$lot->id."'");

                                        $isuData = [
                                            'invoice_id'       => $invoiceId,
                                            'invoice_item_id'  => $qp,
                                            'stock_id'         => (int)$lot->id,
                                            'purchase_id'      => (int)$lot->purchase_id,
                                            'purchase_item_id' => (int)$lot->purchase_item_id,
                                            'product_id'       => $prodId,
                                            'qty_used'         => $take,
                                            'unit_cost'        => $lot->unit_cost,
                                            'datetime'         => 'NOW()'
                                        ];
                                        $isuId = $db->query_insert(TABLE_INVOICE_STOCK_USAGE, $isuData);
                                        if (!$isuId) {
                                            throw new Exception("Failed to write invoice stock usage for product $prodId (edit).");
                                        }

                                        $left -= $take;
                                    }

                                    if ($left > 0) {
                                        throw new Exception("Insufficient stock for product $prodId (short by $left).");
                                    }
                                } // foreach edit products
                            }

                            // everything ok
                            $db->query("COMMIT");

                        } catch (Exception $ex) {
                            $db->query("ROLLBACK");
                            $okAll = false;
                            $errors[] = $ex->getMessage();
                        }

                        if ($okAll && $qp) {
                            $output = '';
                            ?>
                            <script>window.location.href = 'invoice.php?view&sucess'</script>
                            <?php
                            echo "<div id='card-alert' class='card green lighten-5'>
                                      <div class='card-content green-text'>
                                        <p>SUCCESS : <strong>Attention! </strong>Submitted!</p>
                                      </div>
                                      <button type='button' class='close green-text' data-dismiss='alert' aria-label='Close'>
                                        <span aria-hidden='true'>x</span>
                                      </button>
                                    </div>";
                        } else {
                            $output = '';
                            echo "<div id='card-alert' class='card orange lighten-5'>
                                      <div class='card-content orange-text'>
                                        <p>WARNING : <strong>Attention! </strong>".htmlspecialchars(implode(' | ', $errors))."</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>".htmlspecialchars($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++;

                                                // ---- NEW: compute max qty for this line from STOCK table ----
                                                global $db;
                                                $sumRow = $db->query_first("
                                                    SELECT SUM(remaining_qty) AS rem
                                                    FROM ".TABLE_STOCK."
                                                    WHERE product_id = '".(int)$qry->id."'
                                                      AND remaining_qty > 0
                                                ");
                                                $stockRem = ($sumRow && isset($sumRow->rem) && $sumRow->rem !== null)
                                                    ? (int)$sumRow->rem
                                                    : 0;
                                                // Max allowed on this line = remaining stock + qty already on this invoice line
                                                $maxQtyForThisLine = $stockRem + (int)$invoiceProductsRow->product_qty;
                                                // -------------------------------------------------------------

                                                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;" 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;"  maxlength="10" onkeypress="return isNumberKey(event)" class="form-control" type="text" onchange="handleChange' . $qry->id . '(this);" value="' . $invoiceProductsRow->product_qty . '" name="qty[]" id="qty">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input value="' . $qry->carton_pieces . '" type="hidden" name="carton_piece[]" id="cartonval">';
                                                echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $qry->unit . '">';
                                                echo '<input type="hidden" name="units[]" id="unit" value="' . $qry->unit . '">';
                                                echo '</td>';
                                                echo '<td>';
                                                echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" name="unitcost[]" value="' . $invoiceProductsRow->unit_cost_price . '" id="unitcost">';
                                                echo '</td>';
                                             /*   echo '<td id="distributorField">';
                                                echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" name="unitdistributor[]" value="' . $invoiceProductsRow->unit_distributor_price . '" id="unitdistributor">';
                                                echo '</td>'; */
                                                echo '<td>';
                                                echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" name="unitsale[]"  value="' . $invoiceProductsRow->unit_sale_price . '" id="unitsale">';
                                                echo '</td>';
                                                echo '<td id="subTotal">';
                                                echo '';
                                                echo '</td>';
                                                echo "</tr>";
                                                ?>
                                                <script>
                                                    $('#trashing<?=$qry->id?>').on('click', function () {
                                                        $(this).parent('td').parent('tr').remove();
                                                        numbering();
                                                        Calculate();
                                                    });
                                                    function handleChange<?=$qry->id?>(input) {

                                                        var total = <?=$maxQtyForThisLine?>;
                                                        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 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>

                                    <tr>
                                        <td> </td>
                                        <td> </td>
                                        <td><strong>Total Cartons:</strong></td>
                                        <td id="totalCartons"></td>
                                        <td colspan="5"></td>
                                    </tr>   
                                    </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 product_order";
                                    $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 () {
  // quick UI things left as-is
  var selectedvall = $('#customer_name').find(':selected').data('discountdisable');
  if (selectedvall == 1) {
    $('#discount').prop('readonly', true);
    $('#add_discount').prop('readonly', true);
  }

  // Debounce the submit button a bit
  var fewSeconds = 2;
  $('#btnsubmit').on('click', function () {
    var btn = $(this);
    btn.hide();
    setTimeout(function () { btn.show(); }, fewSeconds * 1000);
  });

  // Initial total
  Calculate();
});

/* -----------------------------
   Product adding (unchanged)
----------------------------- */
$('#newItem').off('click').on('click', function () {
  $('#newItem').prop('disabled', true);
  var prod = $('#productsItem').val();
  var custOpt = $('#customer_name').find(':selected');
  if (!prod) { $('#newItem').prop('disabled', false); return; }

  $('body #container').block({message: 'Loading...'});

  $.ajax({
    url: 'addItem.php',
    method: 'GET',
    data: {
      id: prod,
      customer: custOpt.data('mart') || 0,
      customerid: custOpt.val() || ''
    },
    success: function (html) {
      $("#addNewItem").append(html);
      numbering();
      Calculate();
    },
    error: function (xhr) {
      alert("addItem.php error:\n" + (xhr.responseText || xhr.statusText));
    },
    complete: function () {
      $('body #container').unblock();
      $('#newItem').prop('disabled', false);
    }
  });
});

$('#newAll').off('click').on('click', function () {
  var custOpt = $('#customer_name').find(':selected');
  var cid = custOpt.val();
  if (!cid) { alert('Select a customer first.'); return; }

  $('body #container').block({message: 'Loading...'});

  $.ajax({
    url: 'addAll.php',
    method: 'GET',
    data: {
      id: cid,
      customer: custOpt.data('mart') || 0
    },
    success: function (html) {
      $("#addNewItem").append(html);
      numbering();
      Calculate();
      $('#newAll').remove();
    },
    error: function (xhr) {
      alert("addAll.php error:\n" + (xhr.responseText || xhr.statusText));
    },
    complete: function () {
      $('body #container').unblock();
    }
  });
});

/* ----------------------------------------
   Row-level live calculations (the fixes)
----------------------------------------- */

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

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

// 3) Price change updates row subtotal + totals
$(document).on('input', "input[name='unitsale[]']", function () {
  var tr = $(this).closest('tr');
  recalcRow(tr, {driver: 'price'});
  Calculate();
});

// Recalculate one row, safely scoped
function recalcRow(tr, opts) {
  var driver = (opts && opts.driver) || 'qty';

  // Read current row values
  var qtyInput        = tr.find("input[name='qty[]']");
  var cartonsInput    = tr.find("input[name^='totcarton']"); // could be [] or 1[]
  var cartonPiecesInp = tr.find("input[name='carton_piece[]']");
  var unitSaleInp     = tr.find("input[name='unitsale[]']");
  var subTotalCell    = tr.find("td#subTotal"); // id duplicated but scoped by tr

  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;

  // Choose the source of truth:
  // - If user changed cartons (driver==='carton') and cp>0, compute qty from cartons.
  // - Otherwise, leave qty as typed.
  if (driver === 'carton') {
    if (cp > 0) {
      qty = Math.max(0, Math.floor(cartons * cp)); // whole pieces
      qtyInput.val(qty);                            // write back only this row
    } else {
      // no carton logic possible for this product; keep qty as-is
    }
  } else if (driver === 'qty') {
    // Optionally reflect cartons from qty (display only),
    // but do NOT make cartons the driver here to avoid ping-pong effects.
    if (cp > 0) {
      var c = Math.floor(qty / cp);
      cartonsInput.val(c);
    } else {
      cartonsInput.val(0);
    }
  }

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

// Grand totals, run after any row change
function Calculate() {
  var ptotal = 0;
  var totalCartons = 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;

    // subtotal from existing cell if present; otherwise compute
    var subCell = tr.find("td#subTotal");
    var sub = qty * price;
    subCell.text(isFinite(sub) ? sub.toFixed(2) : '0.00');
    ptotal += isFinite(sub) ? sub : 0;

    // display cartons (derived, not driver)
    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));

  // ----- Discounts (keep your existing toggles) -----
  <?php if (PROJECT_DISCOUNT == 1 || !empty($discount)) { ?>
    $('#subAmount').text(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 } ?>

  // ----- Tax (if enabled) -----
  <?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 (!isFinite(ptotal)) ptotal = 0;
  $('#totalAmount').text(ptotal.toFixed(2));
  $('#total_price').val(ptotal.toFixed(2));
}

/* numeric guards */
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>


</body>
</html>
