<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
global $db;
$output = '';
$description = '';
$discount = 0;
$discount_price = 0;
$tax = 0;
$adv_tax = 0;
$adv_tax_price = 0;
$is_tax = 0;
$tax_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',
               format: 'yyyy-mm-dd',
                selectMonths: true,
              selectYears: true, // Creates a dropdown to control year
            });
        });
    </script>
</head>

<body>
    <!-- Start Page Loading -->
    <div id="loader-wrapper">
        <div id="loader"></div>
        <div class="loader-section section-left"></div>
        <div class="loader-section section-right"></div>
    </div>
    <!-- End Page Loading -->
    <div id="container">
        <?php include('../includes/inc_top.php'); ?>
        <div class="row">
            <div class="col s12 m12">
                <div class="">
                    <h3>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;
                        $description = $getInvoice->description;
                        $discount_price = $getInvoice->discount_price;
                        $tax = $getInvoice->tax;
                        $adv_tax = $getInvoice->adv_tax;
                        $adv_tax_price = $getInvoice->adv_tax_price;
                        $is_tax = $getInvoice->is_tax;
                        $tax_price = $getInvoice->tax_price;
                        $poNumber = $getInvoice->po_number;
                    } else if (isset($_GET['add'])) {
                        if (PROJECT_TAX == 1) {
                            $tax = PROJECT_TAX_AMOUNT;
                            $is_tax = PROJECT_TAX;
                            $adv_tax = PROJECT_ADV_TAX_AMOUNT;
                        }
                      if (empty($invoice_date)) {
                         $invoice_date = $current_date; // Use current date if invoice date is not set
                          $dateInvoice = date('Ymd', strtotime($invoice_date));
                      }
                      if ($_SESSION['clone'] == 1) {
                            $invoicefilter = " WHERE code like '$dateInvoice%' 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 = $dateInvoice . '001';
                            }
                        } else {
                             $invoicefilter = " WHERE code like '$dateInvoice%' 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 = $dateInvoice . '001';
                            }
                        }
                    }
                    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['tax'] = $tax;
                        $data['is_tax'] = $is_tax;
                        $data['tax_price'] = $tax_price;
                        $data['adv_tax'] = $adv_tax;
                        $data['adv_tax_price'] = $adv_tax_price;
                        $invoice_date = $_POST['invoice_date'];
                        $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'] = $_POST['po_number'];

                        $errors = array();
                        $qp = false;

                        // 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 at least one product");

                        // Validate posted product quantities before processing
                        if (isset($products) && is_array($products)) {
                            foreach ($products as $prKey => $prRow) {
                                $currentQty = isset($qty[$prKey]) ? floatval($qty[$prKey]) : 0;
                                if ($currentQty <= 0) {
                                    array_push($errors, "Invalid quantity for product ID $prRow");
                                }
                            }
                        }

                        if (count($errors) == 0) {
                            try {
                                $db->query("START TRANSACTION");

                                if (isset($_GET['add'])) {
                                    if ($_SESSION['clone'] == 1) {
                                        $dateInvoice = date('Ymd', strtotime($invoice_date));
                                        $invoicefilter = " WHERE code like '$dateInvoice%' 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 = $dateInvoice . '001';
                                        }
                                    } else {
                                        $dateInvoice = date('Ymd', strtotime($invoice_date));
                                        $invoicefilter = " WHERE code like '$dateInvoice%' 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 = $dateInvoice . '001';
                                        }
                                    }

                                    $data['code'] = $invoiceNumber;
                                    $data['status'] = 'Draft';
                                    $q = Invoice::AddInvoice($data);

                                    if (!$q) {
                                        throw new Exception("Invoice could not be created.");
                                    }

                                    foreach ($products as $prKey => $prRow) {
                                        $requestedQty = isset($qty[$prKey]) ? floatval($qty[$prKey]) : 0;
                                        if ($requestedQty <= 0) {
                                            throw new Exception("Invalid quantity for product ID $prRow");
                                        }

                                        $productSetup = ProductSetup::GetProductSetupById($prRow);
                                        if (!$productSetup) {
                                            throw new Exception("Product setup not found for product ID $prRow");
                                        }

                                        $dataProduct = array();
                                        $dataProduct['invoice_id'] = $q;
                                        $dataProduct['product_id'] = $prRow;
                                        $dataProduct['product_qty'] = $requestedQty;
                                        $dataProduct['carton_piece'] = $carton_piece[$prKey];
                                        $dataProduct['unit_cost_price'] = $unitcost[$prKey];
                                        $dataProduct['unit_distributor_price'] = $unitdistributor[$prKey];
                                        $dataProduct['unit_sale_price'] = $unitsale[$prKey];
                                        $dataProduct['actual_cost_price'] = $productSetup->actual_cost_price;

                                        $qp = Invoice::AddInvoiceProduct($dataProduct);
                                        if (!$qp) {
                                            throw new Exception("Invoice product could not be added for product ID $prRow");
                                        }

                                        // Draft invoice flow:
                                        // Do not check stock and do not deduct stock / create PSD here.
                                        // Stock will be checked and deducted only on invoice validation.
                                    }

                                    // 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']);
                                    $invoiceId = $_GET["id"];

                                    if (!$customerAmount) {
                                        throw new Exception("Invoice not found for edit.");
                                    }

                                    $q = Invoice::UpdateInvoiceSetup($invoiceId, $data);
                                    if (!$q) {
                                        throw new Exception("Invoice could not be updated.");
                                    }

                                    // 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

                                    // 4.1 Draft invoice flow:
                                    // Do not reverse stock or delete PSD here because draft invoices do not post stock.
                                    // Simply replace the invoice product rows.
                                    Invoice::DeleteInvoiceProducts($invoiceId);

                                    // 4.2 Add the new/updated products
                                    foreach ($products as $prKey => $prRow) {
                                        $requestedQty = isset($qty[$prKey]) ? floatval($qty[$prKey]) : 0;
                                        if ($requestedQty <= 0) {
                                            throw new Exception("Invalid quantity for product ID $prRow");
                                        }

                                        $productSetup = ProductSetup::GetProductSetupById($prRow);
                                        if (!$productSetup) {
                                            throw new Exception("Product setup not found for product ID $prRow");
                                        }

                                        $dataProduct = array();
                                        $dataProduct['invoice_id'] = $invoiceId;
                                        $dataProduct['product_id'] = $prRow;
                                        $dataProduct['product_qty'] = $requestedQty;
                                        $dataProduct['carton_piece'] = $carton_piece[$prKey];
                                        $dataProduct['unit_cost_price'] = $unitcost[$prKey];
                                        $dataProduct['unit_distributor_price'] = $unitdistributor[$prKey];
                                        $dataProduct['unit_sale_price'] = $unitsale[$prKey];
                                        $dataProduct['actual_cost_price'] = $productSetup->actual_cost_price;

                                        $qp = Invoice::AddInvoiceProduct($dataProduct);
                                        if (!$qp) {
                                            throw new Exception("Invoice product could not be added for product ID $prRow");
                                        }

                                        // Draft invoice flow:
                                        // Do not check stock and do not deduct stock / create PSD here.
                                        // Stock will be checked and deducted only on invoice validation.
                                    }
                                }

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

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

                                </div>
                                <div class="clearfix"></div>
                                <div class="row">
                                    <div class="col m6 col s12">
                                        <div class="row margin">
                                            <div class="input-field col s12">
                                                <input class="form-control" type="text" id="sales_person"
                                                    name="sales_person" readonly
                                                    value='<?php echo $_SESSION['sess_username']; ?>' />
                                                <input class="form-control" type="hidden" id="sales_person_id"
                                                    name="sales_person_id"
                                                    value='<?php echo $_SESSION['sess_userid']; ?>' /><br />
                                                <label for="sales_person" class="control-label">Sales Person *</label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col m6 col s12">
                                        <div class="row margin">
                                            <div class="input-field col s12">
                                                <input class="form-control" type="text" id="invoice_number"
                                                    name="invoice_number" readonly
                                                    value='<?php echo $invoiceNumber; ?>' /><br />
                                                <label for="invoice_number" class="control-label">Invoice No. *</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>


                                <div class="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"
                                                value='<?php echo $poNumber; ?>' /><br />
                                            <label for="po_number" class="control-label">PO No. *</label>
                                        </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> -->
                                    <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>Product Name</th>
                                                <th>Carton</th>
                                                <th>Quantity</th>
                                                <th>Unit Of Measure</th>
                                                <th>Unit Cost Price</th>
                                                <th id="distributorHeader" style="display: none;">Unit Distributor
                                                    Price
                                                </th>
                                                <th>Unit Sales Price</th>
                                                <th>Sub Total</th>
                                            </thead>
                                            <tbody id="addNewItem">
                                                <?php
                                                if (isset($_GET['edit'])) {
                                                    $filterinvoiceproducts = " WHERE invoice_id = '$id'";
                                                    $invoiceProducts = Invoice::GetInvoiceProducts($filterinvoiceproducts);
                                                    $counting = 0;
                                                    foreach ($invoiceProducts as $invoiceProductsRow) {
                                                        $qry = ProductSetup::GetProductSetupById($invoiceProductsRow->product_id);
                                                        if ($qry) {
                                                            $counting++;
                                                            echo "<tr id='tr" . $qry->id . "'>";
                                                            echo '<td>' . $counting . ' </td>';
                                                            echo '<td style="width: 30px; height: 30px; font-size: 12px; line-height: 15px; margin-top: 11px;" class="mini-stat-icon orange darken-2">';
                                                            echo '<i id="trashing' . $qry->id . '" style="cursor: pointer;font-size: 18px;margin-top: 7px;" class="mdi-action-delete"></i>';
                                                            echo '</td>';
                                                            echo '<td>';
                                                            echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $qry->name . '">';
                                                            echo '<input type="hidden" name="products[]" id="product" value="' . $qry->id . '">';
                                                            echo '</td>';
                                                            echo '<td id="carton">';
                                                            echo '<input ' . ($qry->carton_pieces == 0 ? 'disabled' : '') . ' value="' . ($invoiceProductsRow->carton_piece != 0 ? ($invoiceProductsRow->product_qty / $invoiceProductsRow->carton_piece) : 0) . '" style="width:100%!important;" required maxlength="10" onkeypress="return isNumberKey(event)" class="form-control" type="text" name="totcarton' . ($qry->carton_pieces == 0 ? '1' : '') . '[]" id="totcarton">';
                                                            echo '</td>';
                                                            echo '<td>';
                                                            echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isNumberKey(event)" class="form-control" type="text" onchange="handleChange' . $qry->id . '(this);" value="' . $invoiceProductsRow->product_qty . '" name="qty[]" id="qty">';
                                                            echo '</td>';
                                                            echo '<td>';
                                                            echo '<input value="' . $qry->carton_pieces . '" type="hidden" name="carton_piece[]" id="cartonval">';
                                                            echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $qry->unit . '">';
                                                            echo '<input type="hidden" name="units[]" id="unit" value="' . $qry->unit . '">';
                                                            echo '</td>';
                                                            echo '<td>';
                                                            echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" readonly name="unitcost[]" value="' . number_format((float) $invoiceProductsRow->actual_cost_price, 2, ".", "" ) . '" id="unitcost' . $qry->id . '">';
                                                            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 product_id = <?= $qry->id ?>;
                                                                    $.ajax({
                                                                        type: "POST",
                                                                        url: "check_stock.php",
                                                                        data: { product_id: product_id },
                                                                        dataType: "json",
                                                                        success: function(response) {
                                                                            var total = response.total + <?= $invoiceProductsRow->product_qty ?>;  // Add back the product quantity already in the invoice
                                                                            if (input.value < 0) input.value = 0;
                                                                            if (input.value > total) {
                                                                                input.value = total;
                                                                                swal({
                                                                                    title: "Stock Availability 1",
                                                                                    text: "Stock not available, max quantity is ffff" + total,
                                                                                    type: "error",
                                                                                    confirmButtonColor: '#DD6B55',
                                                                                    closeOnConfirm: false
                                                                                });
                                                                                Calculate();
                                                                                return false;
                                                                            }
                                                                        }
                                                                    });
                                                                }

                                                                function handleCh<?= $qry->id ?>(val) {
                                                                    var product_id = <?= $qry->id ?>;
                                                                    $.ajax({
                                                                        type: "POST",
                                                                        url: "check_stock.php",  // This is the same PHP endpoint we discussed earlier
                                                                        data: { product_id: product_id },
                                                                        dataType: "json",
                                                                        success: function(response) {
                                                                            var total = response.total + <?= $invoiceProductsRow->product_qty ?>;  // Add back the product quantity already in the invoice
                                                                            if (val.val() < 0) val.val(0);
                                                                            if (val.val() > total) {
                                                                                val.val(total);
                                                                                swal({
                                                                                    title: "Stock Availability 2",
                                                                                    text: "Stock not available, max quantity is 999999999" + total,
                                                                                    type: "error",
                                                                                    confirmButtonColor: '#DD6B55',
                                                                                    closeOnConfirm: false
                                                                                });
                                                                                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="6"
                                                                   onkeypress="return isDoubleNumberKey(event)"
                                                                   value="<?= number_format((float)$discount, 2, '.', '') ?>">
                                                            <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>
                                                <?php } ?>
                                                <?php
                                                if (PROJECT_TAX == 1 || $tax != 0) { ?>
                                                    <tr>
                                                        <td id="show5" style="display: none;"></td>
                                                        <td colspan="8" style="text-align: right; vertical-align: middle;">
                                                            Tax (<span id="tax_percent_display"><?= $tax ?>%</span>)
                                                        </td>
                                                        <td id="tax_amount">
                                                        </td>
                                                        <input class="form-control" type="hidden" name="is_tax" id="is_tax"
                                                            maxlength="6" value="<?= $is_tax ?>">
                                                        <input style="width:100%!important;" class="form-control" type="hidden"
                                                            name="tax" id="tax" maxlength="6" value="<?= $tax ?>">
                                                        <input style="width:100%!important;" class="form-control" type="hidden"
                                                            name="tax_price" id="tax_price" value="<?= $tax_price ?>">
                                                    </tr>
                                                
                                               <tr>
                                                        <td id="show5" style="display: none;"></td>
                                                        <td colspan="8" style="text-align: right; vertical-align: middle;">
                                                            Adv Tax (<span id="adv_tax_percent_display"><?= $adv_tax ?>%</span>)
                                                        </td>
                                                        <td id="adv_tax_amount">
                                                        </td>
                                                        <input style="width:100%!important;" class="form-control" type="hidden"
                                                            name="adv_tax" id="adv_tax" maxlength="6" value="<?= $adv_tax ?>">
                                                        <input style="width:100%!important;" class="form-control" type="hidden"
                                                            name="adv_tax_price" id="adv_tax_price" value="<?= $adv_tax_price ?>">
                                                    </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><strong>Total Pieces:</strong></td>
                                                  <td id="totalPieces"></td>
                                                  <td colspan="4"></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 () {
        var selectedvall = $('#customer_name').find(':selected').data('discountdisable');
        if (selectedvall == 1) {
            $('#discount').attr('readonly', true);
        }

        var advTax = $('#customer_name').find(':selected').data('advancetax');
        if (advTax != undefined && advTax != null && advTax != '') {
            $('#adv_tax').val(advTax);
        } else {
            $('#adv_tax').val(0);
        }

        // ✅ GST to Tax
        var tax = $('#customer_name').find(':selected').data('gst');
        if (tax != undefined && tax != null && tax != '') {
            $('#tax').val(tax);
        } else {
            $('#tax').val(0);
        }

        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').show();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').show();
            });
            $('#show1').show();
            $('#show2').show();
            $('#show3').show();
            $('#show4').show();
            $('#show5').show();
        } else {
            $('#distributorHeader').hide();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').hide();
            });
            $('#show1').hide();
            $('#show2').hide();
            $('#show3').hide();
            $('#show4').hide();
            $('#show5').hide();
        }
        Calculate();
    });

    $('#customer_name').on('change', function () {
        var selected = $(this).find(':selected');

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

        var advTax = selected.data('advancetax');
        if (advTax != undefined && advTax != null && advTax !== '') {
            $('#adv_tax').val(advTax);
        } else {
            $('#adv_tax').val(0);
        }

        // ✅ GST to Tax
        var tax = selected.data('gst');
        if (tax != undefined && tax != null && tax !== '') {
            $('#tax').val(tax);
        } else {
            $('#tax').val(0);
        }
      var tax = selected.data('gst');
if (tax != undefined && tax != null && tax !== '') {
    $('#tax').val(tax);
} else {
    $('#tax').val(0);
}
$('#tax_percent_display').text($('#tax').val() + '%');

var advTax = selected.data('advancetax');
if (advTax != undefined && advTax != null && advTax !== '') {
    $('#adv_tax').val(advTax);
} else {
    $('#adv_tax').val(0);
}
$('#adv_tax_percent_display').text($('#adv_tax').val() + '%');

        if (selected.attr('data-mart') == 1) {
            $('#distributorHeader').show();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').show();
                $(this).rules('add', {
                    required: true,
                    messages: {
                        required: "<span class='label label-warning val_mes'>Please enter distributor price</span>"
                    }
                });
            });
            $('#show1').show();
            $('#show2').show();
            $('#show3').show();
            $('#show4').show();
            $('#show5').show();
        } else {
            $('#distributorHeader').hide();
            $("input[name='unitdistributor[]']").each(function () {
                $(this).parent('td').hide();
            });
            $('#show1').hide();
            $('#show2').hide();
            $('#show3').hide();
            $('#show4').hide();
            $('#show5').hide();
        }

        Calculate();
    });

    $('#newItem').on('click', function () {
        $('#newItem').attr('disabled', true);
        var product = $('#productsItem').val();
        var fewSeconds = 2;
        if (!$('#tr' + product).html() && product != '') {
            $('body #container').block({ message: 'Loading...' });
            $.get('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);
    });

    // Handle quantity change
    $(document).on('keyup', "input[name='qty[]']", function () {
        var qtyInput = $(this);
        var qty = qtyInput.val();
        checkAvailableQuantityAndFetchCost(qtyInput);
        Calculate();
    });

    // Handle carton change
    $(document).on('keyup', "input[name='totcarton[]']", function () {
        var cartonInput = $(this);
        var carton = cartonInput.val();
        var cartonPieces = cartonInput.closest('tr').find("input[name='carton_piece[]']").val();
        var qtyInput = cartonInput.closest('tr').find("input[name='qty[]']");
        var qtyValue = (carton * cartonPieces).toFixed(0);
        qtyInput.val(qtyValue);
        checkAvailableQuantityAndFetchCost(qtyInput);
        Calculate();
    });

    function checkAvailableQuantityAndFetchCost(input) {
    var qty = input.val();

    var productId = input
        .closest('tr')
        .find("input[name='products[]']")
        .val();

    $.ajax({
        url: 'fetch_cost_price.php',
        type: 'POST',
        dataType: 'json',
        data: {
            qty: qty,
            productId: productId
        },
        success: function (response) {
            input
                .closest('tr')
                .find("input[name='unitcost[]']")
                .val(response.cost_price);

            Calculate();
        },
        error: function (xhr, status, error) {
            console.log(
                'Error fetching product cost price:',
                error
            );
        }
    });
}

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

    <?php if (PROJECT_DISCOUNT == 1 || !empty($discount)) { ?>
        $('#discount').attr('required', true);
        $(document).on('keyup', "input[name='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>"
                }
            });
        });
    <?php } ?>

    function Calculate() {
        var ptotal = 0;
        var count = 0;
        var totalCartons = 0;
      	var totalPieces = 0; // ✅ NEW
        $("input[name='qty[]']").each(function (index, value) {
            if (isNaN(parseFloat($(this).val())) || parseFloat($(this).val()) == '') {
                $(this).val('0');
            } else {
                var qty = parseFloat($(this).val());
              	totalPieces += qty; // ✅ accumulate total pieces
                var unitsale = parseFloat($("input[name='unitsale[]']").eq(index).val());
                if (isNaN(unitsale) || unitsale == '') {
                    unitsale = 0;
                }
                var subtotal = qty * unitsale;
                ptotal += subtotal;
                $(this).closest('tr').find('td[id="subTotal"]').text(subtotal.toFixed(2));
                var cartonPieces = parseFloat($(this).closest('tr').find("input[name='carton_piece[]']").val());
                var cartonValue = (qty / cartonPieces).toFixed(0);

                if (cartonValue == "Infinity" || isNaN(cartonValue)) {
                    $(this).closest('tr').find("input[name='totcarton[]']").val(0);
                } else {
                    $(this).closest('tr').find("input[name='totcarton[]']").val(cartonValue);
                    totalCartons += parseFloat(cartonValue);
                }
            }
            count++;
        });

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

        <?php if (PROJECT_DISCOUNT == 1 || !empty($discount)) { ?>
            $('#subAmount').text(parseFloat(ptotal).toFixed());
            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;
        <?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;
        return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
    }

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

    </section>
    </section>
</body>

</html>