<?php
include("../classes/manager.class.php");


$m = new Manager();
$output = '';

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

$adjustment_date = date('d-m-Y');
$reason = '';
$ingredient_id = '';
$purchase_id = '';
$deduct_qty = '';

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
    <script>
        $(function () {
            $('#datepicker_adj').pickadate({
                format: 'dd-mm-yyyy',
                selectMonths: true,
                selectYears: 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>Ingredient Stock Adjustment</h3>
            </div>
            <hr>

            <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;" href="ingredient_stock_adjustment_view.php">
                View <i class="mdi-action-visibility"></i>
            </a>
            <div class="clearfix"></div>

            <br/>

            <?php echo $output; ?>

            <form action="ingredient_stock_adjustment_submit.php" method="post" id="ingredient_stock_adjustment_form" novalidate="novalidate">
                <div class="row">
                    <div class="col m3 s12">
                        <div class="row margin">
                            <div class="input-field col s12">
                                <input class="form-control" required type="text" id="datepicker_adj"
                                       name="adjustment_date"
                                       value="<?php echo $adjustment_date; ?>"/><br/>
                                <label for="adjustment_date" class="control-label">Adjustment Date *</label>
                            </div>
                        </div>
                    </div>

                    <div class="col m9 s12">
                        <div class="row margin">
                            <div class="input-field col s12">
                                <input class="form-control" required type="text" id="reason"
                                       name="reason" maxlength="255"
                                       value="<?php echo $reason; ?>"/><br/>
                                <label for="reason" class="control-label">Reason *</label>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">

                    <div class="col m4 s12">
                        <div class="row margin">
                            <div class="input-field col s12">
                                <?php
                                // Ingredient dropdown like your purchase page pattern
                                $filter = " where status = 'active' ORDER BY name";
                                $qryIng = IngSetup::GetIngSetupList($filter, $pageno = "null", $pagesize = "null");
                                ?>
                                <select class="form-control" required id="ingredient_id" name="ingredient_id">
                                    <option></option>
                                    <?php
                                    if ($qryIng) {
                                        foreach ($qryIng as $ingRow) {
                                            echo '<option value="' . $ingRow->id . '">' . $ingRow->name . ' - ' . $ingRow->description . '</option>';
                                        }
                                    }
                                    ?>
                                </select>
                                <label for="ingredient_id" class="control-label">Ingredient *</label>
                            </div>
                        </div>
                    </div>

                    <div class="col m5 s12">
                        <div class="row margin">
                            <div class="input-field col s12">
                                <select class="form-control" required id="purchase_id" name="purchase_id" disabled>
                                    <option></option>
                                </select>
                                <label for="purchase_id" class="control-label">Purchase (Remaining &gt; 0) *</label>
                            </div>
                        </div>
                    </div>

                    <div class="col m3 s12">
                        <div class="row margin">
                            <div class="input-field col s12">
                                <input class="form-control" required type="text" id="deduct_qty"
                                       name="deduct_qty" maxlength="20"
                                       onkeypress="return isDoubleNumberKey(event)"
                                       disabled
                                       value="<?php echo $deduct_qty; ?>"/><br/>
                                <label for="deduct_qty" class="control-label">Deduct Qty *</label>
                                <small id="maxDeductHint" style="color:#777;"></small>
                            </div>
                        </div>
                    </div>

                </div>

                <!-- Detail panel (auto-filled) -->
                <div class="row">
                    <div class="col s12">
                        <div class="card-panel grey lighten-4">
                            <div class="row" style="margin-bottom:0;">
                                <div class="col m3 s12"><b>Purchase Date:</b> <span id="d_purchase_date">-</span></div>
                                <div class="col m3 s12"><b>Supplier:</b> <span id="d_supplier">-</span></div>
                                <div class="col m3 s12"><b>Purchase Code:</b> <span id="d_purchase_code">-</span></div>
                                <div class="col m3 s12"><b>Invoice No:</b> <span id="d_invoice_no">-</span></div>
                            </div>
                            <div class="row" style="margin-bottom:0;margin-top:10px;">
                                <div class="col m3 s12"><b>Purchased Qty:</b> <span id="d_purchased">0</span></div>
                                <div class="col m3 s12"><b>Used Qty:</b> <span id="d_used">0</span></div>
                                <div class="col m3 s12"><b>Remaining Qty:</b> <span id="d_remaining">0</span></div>
                                <div class="col m3 s12"><b>Consumed Qty:</b> <span id="d_consumed">0</span></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="clearfix"></div>
                <button id="btnsubmit" type="submit" class="btn waves-effect waves-light" disabled>Submit</button>
                <button type="button" class="btn waves-effect waves-light" onclick="location.href='ingredient_stock_adjustment_view.php'">
                    Cancel
                </button>

            </form>
        </div>
    </div>

</div>

<?php include('includes/inc_footer.php'); ?>
<?php include('includes/inc_js.php'); ?>

<script type="application/javascript">
    function toastMsg(msg){
        if (window.M && M.toast) {
            M.toast({html: msg});
        } else if (window.Materialize && Materialize.toast) {
            Materialize.toast(msg, 3000);
        } else {
            alert(msg);
        }
    }

    function refreshSelects(){
        try {
            if ($.fn.formSelect) { $('select').formSelect(); }
            if ($.fn.material_select) { $('select').material_select(); }
        } catch(e){}
    }

    function resetDetail(){
        $('#d_purchase_date').text('-');
        $('#d_supplier').text('-');
        $('#d_purchase_code').text('-');
        $('#d_invoice_no').text('-');

        $('#d_purchased').text('0');
        $('#d_used').text('0');
        $('#d_remaining').text('0');
        $('#d_consumed').text('0');

        $('#deduct_qty').val('').prop('disabled', true);
        $('#purchase_id').prop('disabled', true).html('<option></option>');
        $('#btnsubmit').prop('disabled', true);
        $('#maxDeductHint').text('');
        refreshSelects();
    }

    $(document).ready(function () {
        refreshSelects();
        resetDetail();
    });

    // Ingredient change -> load purchase list (same ajax style you use for addPurItem) :contentReference[oaicite:2]{index=2}
    $('#ingredient_id').on('change', function () {
        resetDetail();

        var ingId = $('#ingredient_id').val();
        if (!ingId) return;

        $('body #container').block({message: 'Loading...'});
        $.get('getIngredientPurchasesForAdjustment.php?id=' + ingId, function (data) {
            $('#purchase_id').html('<option></option>' + data);
            $('#purchase_id').prop('disabled', false);
            refreshSelects();
            $('body #container').unblock();
        }).fail(function () {
            $('body #container').unblock();
            toastMsg('Failed to load purchase list.');
        });
    });

    // Purchase change -> load purchase detail panel
    $('#purchase_id').on('change', function () {
        var ingId = $('#ingredient_id').val();
        var purId = $('#purchase_id').val();

        if (!ingId || !purId) {
            resetDetail();
            return;
        }

        $('body #container').block({message: 'Loading...'});
        $.get('getIngredientPurchaseDetailForAdjustment.php?ingredient_id=' + ingId + '&purchase_id=' + purId, function (resp) {
            $('body #container').unblock();

            var data = {};
            try { data = JSON.parse(resp); } catch(e){}

            if (!data || data.status !== true) {
                toastMsg((data && data.msg) ? data.msg : 'No detail found.');
                return;
            }

            $('#d_purchase_date').text(data.purchase_date);
            $('#d_supplier').text(data.supplier_name);
            $('#d_purchase_code').text(data.purchase_code);
            $('#d_invoice_no').text(data.purchase_invoice_no);

            $('#d_purchased').text(data.purchased_qty);
            $('#d_used').text(data.used_qty);
            $('#d_remaining').text(data.remaining_qty);
            $('#d_consumed').text(data.consumed_qty);

            $('#deduct_qty').prop('disabled', false);
            $('#btnsubmit').prop('disabled', false);

            $('#deduct_qty').attr('max', data.remaining_qty_raw);
            $('#maxDeductHint').text('Max deduct: ' + data.remaining_qty);

        }).fail(function () {
            $('body #container').unblock();
            toastMsg('Failed to load purchase details.');
        });
    });

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

</body>
</html>
