<?php
include("../../classes/manager.class.php");
$m = new Manager();
if ($_REQUEST['id']) {
    $id = $_REQUEST['id'];
    $customerDetails = CustomerSetup::GetCustomerSetupById($id);
    $customer_cat = $customerDetails->category_id;
    if ($customer_cat) {
        $invoiceRateFilter = " WHERE customer_category_id = '$customer_cat' AND status = 1";
        $invoiceRate = InvoiceRate::GetInvoiceRateList($invoiceRateFilter);
    }
//print_r($invoiceRate);
    //exit;
    $customer = $_REQUEST['customer'];
    if ($customer == 0) {
        $hide = 'style="display:none"';
    }
    $filterProduct = " WHERE status = 'active' ORDER BY product_order";
    $qry = ProductSetup::GetProductSetupList($filterProduct);
  
  

    if ($qry) {
        foreach ($qry AS $qryRow) {
            $unitCost = '';
            $unitDistributor = '';
            $unitSale = '';
            if (!empty($invoiceRate)) {
                $invoiceRateId = $invoiceRate[0]->id;
                $invoiceRateDetailsFilter = " WHERE invoice_rate_id = '$invoiceRateId' AND product_id = '$qryRow->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;
                }
            }
            if ($unitCost != 0) {
                echo "<tr id='tr" . $qryRow->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' . $qryRow->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="' . $qryRow->name . '">';
                echo '<input type="hidden" name="products[]" id="product" value="' . $qryRow->id . '">';
                echo '</td>';
                echo '<td id="carton">';
                echo '<input '.($qryRow->carton_pieces==0?'disabled':'').' style="width:100%!important;" required maxlength="10" onkeypress="return isNumberKey(event)" class="form-control" type="text" name="totcarton'.($qryRow->carton_pieces==0?'1':'').'[]" id="totcarton">';
                //echo '0';
                echo '</td>';
                echo '<td>';
                echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isNumberKey(event)" class="form-control" onchange="handleChange' . $qryRow->id . '(this);" type="text" name="qty[]" id="qty">';
                echo '</td>';
                echo '<td>';
                echo '<input value="' . $qryRow->carton_pieces . '" name="carton_piece[]" type="hidden" id="cartonval">';
                echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $qryRow->unit . '">';
                echo '<input type="hidden" name="units[]" id="unit" value="' . $qryRow->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="' . $qryRow->cost_price . '" id="unitcost">';
                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">';
                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">';
                echo '</td>';
                echo '<td id="subTotal">';
                echo '';
                echo '</td>';
                //echo "</tr>";
                 $qry1 =ProducedProducts::GetTotalAvailableQuantityFIFO($qryRow->id);
                ?>
                <script>
    // Handle click on delete icon
    $('#trashing<?=$qryRow->id?>').on('click', function () {
        $(this).parent('td').parent('tr').remove();
        numbering();
        Calculate();
		
		
    });

    // Handle quantity change
    function handleChange<?=$qryRow->id?>(input) {
        var qty = input.value;  // User entered quantity
        var productId = <?=$qryRow->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').val(response);  // Update the cost price field
                Calculate();  // Recalculate totals
            },
            error: function(error) {
                console.log("Error in AJAX request:", error);
            }
        });
    }

    function handleCh<?=$qryRow->id?>(val) {
        var qty = val.val();  // User entered quantity
        var productId = <?=$qryRow->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').val(response);  // Update the cost price field
                Calculate();  // Recalculate totals
            },
            error: function(error) {
                console.log("Error in AJAX request:", error);
            }
        });
    }
</script>
                <?php
                echo '</tr>';
            }
        }
    }
}

?>