<?php echo $__env->make('admin::layouts.header', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<?php
use App\Models\Supliers;
use App\Models\Products;
use App\Models\Batches;
use App\Models\Stock;
?>
<main id="main-container">
        <!-- Hero -->
        <div class="bg-body-light">
          <div class="content content-full">
            <div class="d-flex flex-column flex-sm-row justify-content-sm-between align-items-sm-center">
              <h1 class="flex-grow-1 fs-3 fw-semibold my-2 my-sm-3">Edit GRN</h1>
              <nav class="flex-shrink-0 my-2 my-sm-0 ms-sm-3" aria-label="breadcrumb">
                <ol class="breadcrumb">
                  <li class="breadcrumb-item">Dashboard</li>
                  <li class="breadcrumb-item">GRN</li>
                  <li class="breadcrumb-item active" aria-current="page">Edit GRN</li>
                </ol>
              </nav>
            </div>
          </div>
        </div>
        <!-- END Hero -->

        <!-- Page Content -->
        <div class="content">
          <!-- Your Block -->
          <div class="block block-rounded">
            <div class="block-header block-header-default">
              <h3 class="block-title">Edit GRN</h3>
            </div>
            <div class="block-content">
            <?php if(Session::has('success')): ?> <div class="alert alert-success mt-2 mb-2"><?php echo e(Session::get('success')); ?></div><?php endif; ?>
            <?php if(Session::has('fail')): ?> <div class="alert alert-danger mt-2 mb-2"><?php echo e(Session::get('fail')); ?></div><?php endif; ?>
            <form class="row" action="" method="POST" >
            <?php echo csrf_field(); ?>
                    <div class="col-md-3 mb-3">
                      <label class="form-label">GRN Number</label>
                      <input type="text" class="form-control" name="grn_number" value="<?php echo e($grn_details->grn_number); ?>" readonly required>
                      <?php if($errors->has("grn_number")): ?> <div class="alert alert-danger mt-2"><?php echo e($errors->first('grn_number')); ?></div><?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                      <label class="form-label">Invoice No</label>
                      <input type="text" class="form-control" name="invoice_no" value="<?php echo e($grn_details->invoice_no); ?>" required>
                      <?php if($errors->has("invoice_no")): ?> <div class="alert alert-danger mt-2"><?php echo e($errors->first('invoice_no')); ?></div><?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                      <label class="form-label">Invoice Value</label>
                      <input type="number" class="form-control" name="invoice_value" value="<?php echo e($grn_details->invoice_value); ?>" required>
                      <?php if($errors->has("invoice_value")): ?> <div class="alert alert-danger mt-2"><?php echo e($errors->first('invoice_value')); ?></div><?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                      <label class="form-label">PO No</label>
                      <input type="text" class="form-control" name="purchase_order_number" value="<?php echo e($grn_details->purchase_order_number); ?>" required>
                      <?php if($errors->has("purchase_order_number")): ?> <div class="alert alert-danger mt-2"><?php echo e($errors->first('purchase_order_number')); ?></div><?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                    <label class="form-label">Suplier</label>
                    <select class="js-select2 form-select" id="suplier" name="suplier" style="width: 100%;" data-placeholder="Select a suplier..">
                    <?php if($grn_details->suplier) { ?> 
                        <option value="<?php echo e($grn_details->suplier); ?>"><?php echo e(Supliers::where('id', $grn_details->suplier)->value('suplier_name')); ?></option>
                    <?php } ?>
                    <?php foreach($supliers as $suplier){ ?> 
                        <option value="<?php echo e($suplier->id); ?>"><?php echo e($suplier->suplier_name); ?></option>
                    <?php } ?>
                    </select>
                      <?php if($errors->has("suplier")): ?> <div class="alert alert-danger mt-2"><?php echo e($errors->first('suplier')); ?></div><?php endif; ?>
                    </div>
                    <!-- <div class="col-md-3 mb-3">
                      <label class="form-label">Purchase Order Number</label>
                      <input type="text" class="form-control" name="purchase_order_number" value="<?php echo e(old('purchase_order_number')); ?>">
                      <?php if($errors->has("purchase_order_number")): ?> <div class="alert alert-danger mt-2"><?php echo e($errors->first('purchase_order_number')); ?></div><?php endif; ?>
                    </div> -->

                    <div class="col-md-3 mb-3">
                      <label class="form-label">Received Date</label>

                      <input type="date" class="form-control" name="received_date" value="<?php echo e($grn_details->received_date); ?>">

                      <?php if($errors->has("received_date")): ?> <div class="alert alert-danger mt-2"><?php echo e($errors->first('received_date')); ?></div><?php endif; ?>
                    </div>
                     <div>
                      <div class="row">
                        <div class="col-md-2 mb-3">
                        <label class="form-label">Select Product</label>
                        <select class="js-select2 form-select" id="product" style="width: 100%;" data-placeholder="Select a product.." >
                            <option></option>
                            <?php foreach($products as $product){ ?> 
                                <option value="<?php echo e($product->id); ?>"><?php echo e($product->product_name); ?></option>
                            <?php } ?>
                        </select>
                        </div>
                        <div class="col-md-2 mb-3">
                        <label class="form-label">Batch</label>
                        <select class="tags-select form-select" id="batch" style="width: 100%;" data-placeholder="Select a batch.." >
                            <option></option>
                           
                        </select>
                        </div>
                        <div class="col-md-2 mb-3">
                        <label class="form-label">Expire Date</label>
                        <input type="date" class="form-control" id="expire_date"  value="" >
                        </div>
                        <div class="col-md-1 mb-3">
                        <label class="form-label">Qty</label>
                        <input type="number" class="form-control" id="qty"  value="" >
                        </div>
                        <div class="col-md-1 mb-3">
                        <label class="form-label">Free Qty</label>
                        <input type="number" class="form-control" id="free_qty"  value="" >
                        </div>
                        <div class="col-md-1 mb-3">
                        <label class="form-label">Cost</label>
                        <input type="number" class="form-control" id="cost"  value="" >
                        </div>
                        <div class="col-md-1 mb-3">
                        <label class="form-label">MRP</label>
                        <input type="number" class="form-control"  id="mrp" value="" >
                        </div>
                        <div class="col-md-1 mb-3">
                        <label class="form-label">Total Cost</label>
                        <input type="number" class="form-control" id="total_cost"  value="" >
                        </div>
                      </div>
                     <button type="button" class="btn btn-success" id="add_batch">+ Add Batch</button>
                    <div class="table-responsive">
                            <table class="table table-bordered table-striped table-vcenter mt-4">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th>Batch</th>
                                        <th>Qty</th>
                                        <th>Free Qty</th> 
                                        <th>Unit Cost</th>
                                        <th>MRP</th>
                                        <th>Total Cost</th>
                                    </tr>
                                </thead>
                                <tbody id="products-tbody">
                                <?php foreach($grn_products as $grn_product){ 
                                $free_quantity = 0;  
                                $free_quantity_data = Stock::where('batch', $grn_product->batch)->where('is_free', 1)->first();
                                if($free_quantity_data){
                                  $free_quantity = $free_quantity_data->initial_stock; 
                                }
                                ?> 
                                <tr>
                                  <td><?php echo e(Products::where('id', $grn_product->product)->value('product_name')); ?></td>
                                  <td><?php echo e(Batches::where('id', $grn_product->batch)->value('batch').' - MRP: '.Batches::where('id', $grn_product->batch)->value('mrp').' - Exp: '.Batches::where('id', $grn_product->batch)->value('expire_date')); ?></td>
                                  <td><?php echo e($grn_product->initial_stock); ?></td>
                                  <td><?php echo e($free_quantity); ?></td>
                                  <td><?php echo e($grn_product->cost); ?></td>
                                  <td><?php echo e(Batches::where('id', $grn_product->batch)->value('mrp')); ?></td>
                                  <td><?php echo e($grn_product->total_cost); ?><input type="hidden" class="batch-total-cost" value="<?php echo e($grn_product->total_cost); ?>"></td>
                                  <td></td>
                                  <!-- <td><button type="button" class="btn btn-info btn-sm ">Edit</button><button type="button" class="btn btn-danger btn-sm ">Remove</button></td> -->
                              </tr>
                              <?php } ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="6" style="text-align:right">Total</th>
                                        <th id="total_grn_cost"><?php echo e($grn_details->total_grn_cost); ?></th>
                                    </tr>
                                 
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    <div>
                    <input type="hidden" id="total_grn_cost_input" name="total_grn_cost_input" value="<?php echo e($grn_details->total_grn_cost); ?>">
                      <button type="submit" class="btn btn-primary">Save</button>

                     
                    </div>
                  </form>
            </div>
          </div>
          <!-- END Your Block -->
        </div>
        <!-- END Page Content -->
</main>
<!-- END Main Container -->
<?php echo $__env->make('admin::layouts.footer', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<script>
$(".tags-select").select2({
    tags: true
});

document.addEventListener("DOMContentLoaded", function () {
    let batchIndex = 0;
    const tbody = document.getElementById("products-tbody");
    const addBatchButton = document.getElementById("add_batch");
    const totalGrnCostElement = document.getElementById("total_grn_cost");
    const totalGrnCostInput = document.getElementById("total_grn_cost_input");

    function calculateTotalCost() {
        let totalCost = 0;
        document.querySelectorAll(".batch-total-cost").forEach((costField) => {
            totalCost += parseFloat(costField.value) || 0;
        });
        totalGrnCostElement.textContent = totalCost.toFixed(2);
        totalGrnCostInput.value = totalCost.toFixed(2);
    }

    function updateTotalCost() {
        const qty = parseFloat(document.getElementById("qty").value) || 0;
        const cost = parseFloat(document.getElementById("cost").value) || 0;
        document.getElementById("total_cost").value = (qty * cost).toFixed(2);
    }

    document.getElementById("qty").addEventListener("input", updateTotalCost);
    document.getElementById("cost").addEventListener("input", updateTotalCost);

    addBatchButton.addEventListener("click", function () {
        const product = document.getElementById("product");
        const batch = document.getElementById("batch");
        const expireDate = document.getElementById("expire_date").value;
        const qty = parseFloat(document.getElementById("qty").value) || 0;
        const freeQty = parseFloat(document.getElementById("free_qty").value) || 0;
        const cost = parseFloat(document.getElementById("cost").value) || 0;
        const mrp = parseFloat(document.getElementById("mrp").value) || 0;
        const total_cost = parseFloat(document.getElementById("total_cost").value) || 0;

        if (!product.value || !batch.value || qty <= 0 || cost <= 0) {
            alert("Please enter valid product, batch, quantity, and cost.");
            return;
        }

        const row = `<tr>
            <td>${product.options[product.selectedIndex].text}<input type="hidden" name="batches[${batchIndex}][product_id]" value="${product.value}"></td>
            <td>${batch.options[batch.selectedIndex].text}<input type="hidden" name="batches[${batchIndex}][batch_id]" value="${batch.value}"></td>
            <td>${qty}<input type="hidden" name="batches[${batchIndex}][qty]" value="${qty}"></td>
            <td>${freeQty}<input type="hidden" name="batches[${batchIndex}][free_qty]" value="${freeQty}"></td>
            <td>${cost}<input type="hidden" name="batches[${batchIndex}][cost]" value="${cost}"></td>
            <td>${mrp}<input type="hidden" name="batches[${batchIndex}][mrp]" value="${mrp}"></td>
            <td>${total_cost.toFixed(2)}<input type="hidden" class="batch-total-cost" name="batches[${batchIndex}][total_cost]" value="${total_cost.toFixed(2)}">
            <input type="hidden" name="batches[${batchIndex}][expire_date]" value="${expireDate}"></td>
            <td><button type="button" class="btn btn-danger btn-sm remove-batch">Remove</button></td>
        </tr>`;

        tbody.insertAdjacentHTML("beforeend", row);
        batchIndex++;
        calculateTotalCost();


        $('#product').val([]).trigger('change');
        $('#batch').val([]).trigger('change');

        document.getElementById("product").value = "";
        document.getElementById("batch").value = "";
        document.getElementById("expire_date").value = "";
        document.getElementById("qty").value = "";
        document.getElementById("free_qty").value = "";
        document.getElementById("cost").value = "";
        document.getElementById("mrp").value = "";
        document.getElementById("total_cost").value = "";
    });

    tbody.addEventListener("click", function (event) {
        if (event.target.classList.contains("remove-batch")) {
            event.target.closest("tr").remove();
            calculateTotalCost();
        }
    });
});
</script>

<script>
   $(document).ready(function () {
    $('#product').change(function () {
        let productId = $(this).val();
        if (productId) {
            $.ajax({
                url: '<?php echo e(url('admin/get-all-batches')); ?>/' + productId,
                type: 'GET',
                success: function (data) {
                    let batchSelect = $('#batch');
                    batchSelect.empty();
                    batchSelect.append('<option></option>');
                    
                    $.each(data, function (index, batch) {
                        let optionText = `${batch.batch_name} - MRP: ${batch.mrp} - Exp: ${batch.expire_date}`;
                        batchSelect.append('<option value="' + batch.batch_id + '" data-expire-date="' + batch.expire_date + '" data-mrp="' + batch.mrp + '">' + optionText + '</option>');
                    });
                }
            });
        }
    });

    $('#batch').change(function () {
        let selectedOption = $(this).find('option:selected');
        let expireDate = selectedOption.data('expire-date');
        let mrp = selectedOption.data('mrp');
        
        $('#expire_date').val(expireDate);
        $('#mrp').val(mrp);
    });
});
</script><?php /**PATH /home/u446954234/domains/orionerp.xyz/public_html/demo/Modules/Admin/resources/views/grn/edit_grn.blade.php ENDPATH**/ ?>