<?php
include("../../classes/manager.class.php");
$m = new Manager();
if ($_REQUEST['id']) {
    $id = $_REQUEST['id'];
    $customer = $_REQUEST['customer'];
    $customerid = $_REQUEST['customerid'];
    $unitCost = '';
    $unitDistributor = '';
    $unitSale = '';
    if ($customer == 0) {
        $hide = 'style="display:none"';
    }
    if ($customerid != 0 && $customerid != '') {
        $customerDetails = CustomerSetup::GetCustomerSetupById($customerid);
        $customer_cat = $customerDetails->category_id;
        if ($customer_cat) {
            $invoiceRateFilter = " WHERE customer_category_id = '$customer_cat' AND status = 1";
            $invoiceRate = InvoiceRate::GetInvoiceRateList($invoiceRateFilter);
        }
    }
    $qry1 = ProducedProducts::GetTotalAvailableQuantityFIFO($id);
    $qry = ProductSetup::GetProductSetupById($id);
    if ($qry) {
        $unitCost = '';
        $unitDistributor = '';
        $unitSale = '';
        if (!empty($invoiceRate)) {
            $invoiceRateId = $invoiceRate[0]->id;
            $invoiceRateDetailsFilter = " WHERE invoice_rate_id = '$invoiceRateId' AND product_id = '$qry->id'";
            $invoiceRateDetails = InvoiceRate::GetInvoiceRateDetails($invoiceRateDetailsFilter);
            if (!empty($invoiceRateDetails)) {
                $unitCost = $invoiceRateDetails[0]->unit_cost_price;
                $unitDistributor = $invoiceRateDetails[0]->unit_distributor_price;
                $unitSale = $invoiceRateDetails[0]->unit_sale_price;
            }
        }

        echo "<tr id='tr" . $id . "'>";
        echo '<td></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' . $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' . $id . '" value="' . $qry->id . '">';
        echo '</td>';
        echo '<td id="carton">';
        echo '<input '.($qry->carton_pieces==0?'disabled':'').' 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' . $id . '">';
        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);" name="qty[]" id="qty' . $id . '">';
      //  echo '</td>';
      //  echo '<td>';
      //  echo '<input value="' . $qry->carton_pieces . '" name="carton_piece[]" type="hidden" id="cartonval' . $id . '">';
      //  echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $qry->unit . '">';
      //  echo '<input type="hidden" name="units[]" id="unit' . $id . '" value="' . $qry->unit . '">';
      //  echo '</td>';
      //  echo '<td>';
      //  echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" readonly class="form-control" type="text" name="unitcost[]" value="' . $qry->cost_price . '" id="unitcost' . $id . '">';  // Updated ID
      //  echo '</td>';
       // echo '<td id="distributorField" ' . $hide . '>';
       // echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" class="form-control" type="text" name="unitdistributor[]" value="' . $unitDistributor . '" id="unitdistributor' . $id . '">';  // Updated ID
      //  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="' . $unitSale . '" id="unitsale' . $id . '">';  // Updated ID
      //  echo '</td>';
      //  echo '<td id="subTotal">';
      //  echo '</td>';
      //  echo "</tr>";
    }
}
?>
<script>
    // Handle click on delete icon
    $('#trashing<?=$id?>').on('click', function () {
        $(this).parent('td').parent('tr').remove();
        numbering();
        Calculate();
    });

    // Handle quantity change
    function handleChange<?=$id?>(input) {
        var qty = input.value;  // User entered quantity
        var productId = <?=$qry->id?>;  // Product ID
        
        // Ensure quantity is within the available stock
        if (qty < 0) qty = 0;
        if (qty > <?=$qry1?>) {
            qty = <?=$qry1?>;
            swal({
                title: "Stock Availability",
                text: "Stock not available, max quantity is " + <?=$qry1?>,
                type: "error",
                confirmButtonColor: '#DD6B55',
                closeOnConfirm: false
            });
            input.value = <?=$qry1?>; // Reset the value to the max available stock
            Calculate();  // Recalculate totals
            return false;
        }

        // AJAX request to fetch new cost price
        $.ajax({
            url: 'fetch_cost_price.php',  // PHP script to handle the request
            type: 'POST',
            data: {
                qty: qty,  // Send quantity
                productId: productId  // Send product ID
            },
            success: function(response) {
                // Update the cost price in the form with the response
                $('#unitcost' + productId).val(response);  // Update the cost price field with unique ID
                Calculate();  // Recalculate totals
            },
            error: function(error) {
                console.log("Error in AJAX request:", error);
            }
        });
    }

    function handleCh<?=$qry->id?>(val) {
        var qty = val.val();  // User entered quantity
        var productId = <?=$qry->id?>;  // Product ID

        // Ensure quantity is within the available stock
        if (qty < 0) qty = 0;
        if (qty > <?=$qry1?>) {
            qty = <?=$qry1?>;
            swal({
                title: "Stock Availability",
                text: "Stock not available, max quantity is " + <?=$qry1?>,
                type: "error",
                confirmButtonColor: '#DD6B55',
                closeOnConfirm: false
            });
            val.val(<?=$qry1?>); // Reset the value to the max available stock
            return false;
        }

        // AJAX request to fetch new cost price
        $.ajax({
            url: 'fetch_cost_price.php',  // PHP script to handle the request
            type: 'POST',
            data: {
                qty: qty,  // Send quantity
                productId: productId  // Send product ID
            },
            success: function(response) {
                // Update the cost price in the form with the response
                $('#unitcost' + productId).val(response);  // Update the cost price field with unique ID
                Calculate();  // Recalculate totals
            },
            error: function(error) {
                console.log("Error in AJAX request:", error);
            }
        });
    }
</script>
