<?php
include("../../classes/manager.class.php");
$m = new Manager();

// Check if this is an AJAX request to check stock availability
if (isset($_POST['check_stock']) && $_POST['check_stock'] == true) {
    $product_id = $_POST['product_id'];

    // Assuming you have a method to get the total available quantity from the `produced_products` table
    $total_available_qty = ProducedProducts::GetTotalAvailableQuantityFIFO($product_id); 
    echo json_encode(['total' => $total_available_qty]);
    exit; // Stop further processing since this is an AJAX request
}

// The rest of the addItem logic
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);
        }
    }
    $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" 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">';
        //echo '0';
        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">';
        echo '</td>';
        echo '<td>';
        echo '<input value="' . $qry->carton_pieces . '" name="carton_piece[]" type="hidden" id="cartonval">';
        echo '<input class="form-control" style="width:100%!important;" type="text" readonly value="' . $qry->unit . '">';
        echo '<input type="hidden" name="units[]" id="unit" value="' . $qry->unit . '">';
        echo '</td>';
        echo '<td>';
        echo '<input style="width:100%!important;" required maxlength="10" onkeypress="return isDoubleNumberKey(event)" readonly class="form-control" type="text" name="unitcost[]" value="' . $qry->cost_price . '" id="unitcost">';
        echo '</td>';
        echo '<td id="distributorField" ' . $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>";
    }
}
?>
<script>
    $('#trashing<?=$id?>').on('click', function () {
        $(this).parent('td').parent('tr').remove();
        numbering();
        Calculate();
    });

    // Update the handleChange function to use AJAX to check stock within the same file
    function handleChange<?=$id?>(input) {
        var product_id = <?=$qry->id?>;
        $.ajax({
            type: "POST",
            url: "addItem.php",  // Self-reference this file
            data: { product_id: product_id, check_stock: true },  // Include a flag to indicate stock check
            dataType: "json",
            success: function(response) {
                console.log("Stock check response:", response);  // Log the response for debugging
                var total = response.total;  // Available stock quantity based on FIFO
                if (input.value < 0) input.value = 0;
                if (input.value > total) {
                    input.value = total;
                    swal({
                        title: "Stock Availability",
                        text: "Stock not available, max quantity is " + total,
                        type: "error",
                        confirmButtonColor: '#DD6B55',
                        closeOnConfirm: false
                    });
                    Calculate();  // Recalculate totals or any other necessary updates
                    return false;
                }
            }
        });
    }

    function handleCh<?=$qry->id?>(val) {
        if (val.val() < 0) val.val(0);
        if (val.val() > <?=$qry->availability?>) {
            val.val(<?=$qry->availability?>);
            swal({
                title: "Stock Availability",
                text: "Stock not available, max quantity is " + <?=$qry->availability?>,
                type: "error",
                confirmButtonColor: '#DD6B55',
                closeOnConfirm: false
            });
            return false;
        }
    }
</script>
</tr>
