<?php
use Carbon\Carbon;
?>


<?php $__env->startSection('title', 'Farmer Return Invoice Create'); ?>

<?php $__env->startPush('css'); ?>
    <!-- data tables -->
    <link href="<?php echo e(asset('admin/assets/plugins/datatables/plugins/bootstrap/dataTables.bootstrap4.min.css')); ?> "
        rel="stylesheet" type="text/css" />
            <!--select2-->
    <link href="<?php echo e(asset('admin/assets/plugins/select2/css/select2.css')); ?>" rel="stylesheet" type="text/css" />
    <link href="<?php echo e(asset('admin/assets/plugins/select2/css/select2-bootstrap.min.css')); ?>" rel="stylesheet" type="text/css" />
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
    <div class="page-bar">
        <div class="page-title-breadcrumb">

        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <div class="btn-group">
                <a href="<?php echo e(route('admin.farmer-return.create')); ?>" id="addRow1" class="btn btn-primary"
                    style="font-size:14px; padding: 6px 12px;">
                    Add New Return <i style="color:white;" class="fa fa-plus"></i>
                </a>

            </div>
            <div class="card card-topline-red">
                <div class="card-head" style="text-align: center;">
                    <header>Create Farmer Return Invoice </header>
                    <div class="tools">
                        <a class="fa fa-repeat btn-color box-refresh" href="javascript:;"></a>
                        <a class="t-collapse btn-color fa fa-chevron-down" href="javascript:;"></a>
                        <a class="t-close btn-color fa fa-times" href="javascript:;"></a>
                    </div>
                </div>
                <div class="card-body ">
                    <form action="<?php echo e(route('admin.farmer-return.store')); ?>" method="post">
                        <?php echo csrf_field(); ?>
                        <div class="form-row">
                            <div class="col-md-4 col-sm-12 form-group">
                                <label for="invoice">Invoice No</label>
                                <input type="text" name="invoice_no" id="invoice" placeholder="Invoice No"
                                    class="form-control <?php $__errorArgs = ['invoice_no'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" />
                                <?php $__errorArgs = ['invoice_no'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="invalid-feedback"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>
                            <div class="col-md-4 col-sm-12 form-group">
                                <label for="date">Date*</label>
                                <input type="date" name="date" id="date" class="form-control <?php $__errorArgs = ['date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" required />
                                <?php $__errorArgs = ['date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="invalid-feedback"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>

                            <div class="col-md-4 col-sm-12 form-group">
                                <label for="farmer">Farmer*</label>
                                <select name="farmer_id" id="farmer" class="select2 form-control <?php $__errorArgs = ['farmer_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" data-placeholder="Select a Farmer">
                                    <option value="" hidden>Select a Farmer</option>
                                    <?php $__empty_1 = true; $__currentLoopData = $farmers; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $farmer): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                        <option value="<?php echo e($farmer->id); ?>"><?php echo e($farmer->name); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                    <?php endif; ?>
                                </select>
                                <?php $__errorArgs = ['farmer_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                    <div class="invalid-feedback"><?php echo e($message); ?></div>
                                <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="col-md-12 col-sm-12">
                                <table class="table">
                                    <tbody>
                                        <tr>
                                            <td>
                                                <select id="product" class="select2 form-control" data-placeholder="Select a Product">
                                                    <option value="" hidden>Select a Product</option>
                                                    <?php $__empty_1 = true; $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                                        <option data-price="<?php echo e($product->stock() > 0 ? $product->productprices()->latest()->first()->selling_price : 0); ?>" value="<?php echo e($product->id); ?>"><?php echo e($product->product_name); ?> (<?php echo e($product->size); ?>)</option>
                                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>                                                        
                                                    <?php endif; ?>                                                    
                                                </select>
                                            </td>
                                            <td>
                                                <input type="number" class="form-control" id="unit_price" placeholder="Unit Price" />
                                            </td>
                                            <td>
                                                <input type="number" class="form-control" id="quantity" placeholder="Quantity" />
                                            </td>
                                            <td>
                                                <input type="number" class="form-control" id="total" placeholder="Total" readonly />
                                            </td>
                                            <td>
                                                <button type="button" id="addProduct" class="btn btn-primary">Add</button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            <div class="col-md-12 col-sm-12 form-group">
                                <table class="table table-sm" id="selectedProductTable">
                                    <thead>
                                        <tr>
                                            <th>Product</th>
                                            <th>Unit Price</th>
                                            <th>Qty.</th>
                                            <th>Total</th>
                                            <th>&nbsp;</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <td colspan="2">Total</td>
                                            <td id="total_qty"></td>
                                            <td id="total_amount"></td>
                                            <td>&nbsp;</td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="note">Note</label>
                            <textarea name="note" class="form-control" id="" cols="10" rows="3" placeholder="Write Note..."></textarea>
                        </div>
                        
                        <input type="hidden" value="" name="grand_total" />
                        <input type="hidden" value="" name="total_qty" />
                        <div class="form-group">
                            <button class="btn btn-primary" id="submitBtn" type="submit">Save</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('js'); ?>
    <!-- data tables -->
    <script src="<?php echo e(asset('admin/assets/plugins/select2/js/select2.js')); ?>"></script>

    <!-- sweet aleart -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $(".select2").select2({});
            
            // Re-init select2 and trigger change to ensure price loads if page refreshed with value
            // $('#product').trigger('change'); 

            // Product Prices Mapping
            // const productPrices = {
            //     <?php $__currentLoopData = $products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $product): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            //         "<?php echo e($product->id); ?>": <?php echo e($product->stock() > 0 ? (optional($product->productprices()->latest()->first())->selling_price ?? 0) : 0); ?>,
            //     <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            // };

            $('#product').on('change select2:select', function(e) {
                let price = $(this).find(':selected').data('price');
                // let productId = $(this).val();
                // let price = productPrices[productId] || 0;
                $('#unit_price').val(price);
                calculateTotal();
            });

            function calculateTotal() {
                let unitPrice = $("#unit_price").val();
                let quantity = $("#quantity").val();
                $("#total").val(unitPrice * quantity);
            }

            $('#unit_price').on("input", calculateTotal);
            $('#quantity').on("input", calculateTotal);

            $("#addProduct").on("click", function() {
                let product_id = $('#product').val();
                if(!product_id) {
                    Swal.fire('Please Select Product!', '', 'warning');
                    return;
                }
                let selected_id = [];
                $("input[name='product_id[]']").each(function () {
                    selected_id.push($(this).val());
                })

                let check = selected_id.includes(product_id);
                if(check) {
                    Swal.fire('Product Already Exists!', '', 'success');
                    clear();
                    return;
                }
                
                let product_name = $("#product option:selected").text();                
                let unit_price = $("#unit_price").val();
                let quantity = $("#quantity").val();
                let total = $("#total").val();
                let output = '';
                output += `<tr>`;
                output += `<input type="hidden" name="product_id[]" value="${product_id}" />`
                output += `<td><input type="text" name="product_name" class="form-control" value="${product_name}" readonly /></td>`
                output += `<td><input type="number" name="unit_price[]" class="unit_price form-control" value="${unit_price}" placeholder="Unit Price" /></td>`
                output += `<td><input type="number" name="quantity[]" class="quantity form-control" value="${quantity}" placeholder="Quantity" /></td>`
                output += `<td><input type="number" name="total[]" class="total form-control" value="${total}" placeholder="Total" readonly /></td>`
                output += `<td><button class="remove_btn btn btn-outline-danger" type="button" >Remove</button></td>`
                output += `</tr>`;
                $("#selectedProductTable tbody").append(output);
                clear();
                calculateFooterTotal();
            });

            $(document).on("click", ".remove_btn",  function() {
                $(this).closest('tr').remove();
                calculateFooterTotal();
            });

            const calculateFooterTotal = () => {
                let total_amount = 0;
                let total_qty = 0;
                $(document).find('.total').each((index, item) => {
                    total_amount += Number($(item).val());
                });
                $(document).find('.quantity').each((index, item) => {
                    total_qty += Number($(item).val());
                });
                $("#total_amount").text(total_amount);
                $("#total_qty").text(total_qty);
                $("input[name='grand_total']").val(total_amount)
                $("input[name='total_qty']").val(total_qty)
            }

            const calculateEditTotal = (evt) => {
                let tr = $(evt.target).closest('tr');
                let unit_price = $($(tr).find('.unit_price')).val();
                let unit_quantity = $($(tr).find(".quantity")).val();
                $($(tr).find('.total')).val(Number(unit_price * unit_quantity));
                calculateFooterTotal();
            };

            $(document).on("input", ".unit_price", calculateEditTotal);
            $(document).on("input", ".quantity", calculateEditTotal);

            function clear() {
                $('#product').val('');
                $('#unit_price').val('');
                $('#quantity').val('');
                $('#total').val('');
            }

            $("#submitBtn").on("click", function(e) {
                let rowCount = $('#selectedProductTable tbody tr').length;
                if(rowCount === 0) {
                    e.preventDefault();
                    Swal.fire('Please Add at least one Product!', '', 'warning');
                    return false;
                }
                
                if(!confirm('Are you sure?')) {
                    e.preventDefault();
                    return false;
                }
            });

        });
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('template.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\forazi\resources\views/admin/farmerreturn/create.blade.php ENDPATH**/ ?>