<?php echo $__env->make('admin::layouts.header', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<?php
use App\Models\CustomerDetails;
use App\Models\Products;
use App\Models\GRNS;
?>
<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">Add Order</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">Sales</li>
                        <li class="breadcrumb-item active" aria-current="page">Add Order</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">Add Order</h3>
            </div>
            <div class="block-content">
                <?php if(Session::has('success')): ?> 
                    <div class="alert alert-success mt-2 mb-2"><?php echo 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">Sales Order Number</label>
                        <input type="text" class="form-control" name="sales_order_number" value="<?php echo e($orderNumber); ?>" readonly>
                        <?php if($errors->has("sales_order_number")): ?> 
                            <div class="alert alert-danger mt-2"><?php echo e($errors->first('sales_order_number')); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Customer</label>
                        <select class="js-select2 form-select" id="customer" name="customer" style="width: 100%;" data-placeholder="Select a customer.." required>
                            <?php if(old('customer')) { ?> 
                                <option value="<?php echo e(old('customer')); ?>"><?php echo e(CustomerDetails::where('user_id', old('customer'))->value('customer_name')); ?></option>
                            <?php } ?>
                            <option></option>
                            <?php foreach($customers as $customer){ ?> 
                                <option value="<?php echo e($customer->id); ?>"><?php echo e($customer->customerDetails->customer_name); ?></option>
                            <?php } ?>
                        </select>
                        <?php if($errors->has("customer")): ?> 
                            <div class="alert alert-danger mt-2"><?php echo e($errors->first('customer')); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Order Date</label>
                        <input type="date" class="form-control" name="order_date" value="<?php echo e(old('order_date')); ?>" required>
                        <?php if($errors->has("order_date")): ?> 
                            <div class="alert alert-danger mt-2"><?php echo e($errors->first('order_date')); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Delivery Date</label>
                        <input type="date" class="form-control" name="delivery_date" value="<?php echo e(old('delivery_date')); ?>" required>
                        <?php if($errors->has("delivery_date")): ?> 
                            <div class="alert alert-danger mt-2"><?php echo e($errors->first('delivery_date')); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Shipping Address</label>
                        <input type="text" class="form-control" name="shipping_address" value="<?php echo e(old('shipping_address')); ?>" required>
                        <?php if($errors->has("shipping_address")): ?> 
                            <div class="alert alert-danger mt-2"><?php echo e($errors->first('shipping_address')); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Order Status</label>
                        <select class="js-select2 form-select" id="order_status" name="order_status" style="width: 100%;" data-placeholder="Select .." required>
                            <?php if(old('order_status')) { ?> 
                                <option value="<?php echo e(old('order_status')); ?>"><?php echo e(old('order_status')); ?></option>
                            <?php } ?>
                            <option></option>
                            <option value="Pending">Pending</option>
                            <option value="Processed">Processed</option>
                            <option value="Shipped">Shipped</option>
                            <option value="Delivered">Delivered</option>
                            <option value="Canceled">Canceled</option>
                        </select>
                        <?php if($errors->has("order_status")): ?> 
                            <div class="alert alert-danger mt-2"><?php echo e($errors->first('order_status')); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Sales Person</label>
                        <input type="text" class="form-control" name="sales_person" value="<?php echo e(old('sales_person')); ?>" required>
                        <?php if($errors->has("sales_person")): ?> 
                            <div class="alert alert-danger mt-2"><?php echo e($errors->first('sales_person')); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Price Method</label>
                        <select class="js-select2 form-select" id="price_method" name="price_method" style="width: 100%;" data-placeholder="Select .." required>
                            <?php if(old('price_method')) { ?> 
                                <option value="<?php echo e(old('price_method')); ?>"><?php echo e(old('price_method')); ?></option>
                            <?php } ?>
                            <option></option>
                            <option value="retail">Retail</option>
                            <option value="wholesale">Wholesale</option>
                        </select>
                        <?php if($errors->has("price_method")): ?> 
                            <div class="alert alert-danger mt-2"><?php echo e($errors->first('price_method')); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Due Date</label>
                        <input type="date" class="form-control" name="due_date" value="<?php echo e(old('due_date')); ?>" required>
                        <?php if($errors->has("due_date")): ?> 
                            <div class="alert alert-danger mt-2"><?php echo e($errors->first('due_date')); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Notes</label>
                        <textarea class="form-control" name="notes" rows="3"><?php echo e(old('notes')); ?></textarea>
                        <?php if($errors->has("notes")): ?> 
                            <div class="alert alert-danger mt-2"><?php echo e($errors->first('notes')); ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Payment Terms</label>
                        <textarea class="form-control" name="payment_terms" rows="3"><?php echo e(old('payment_terms')); ?></textarea>
                        <?php if($errors->has("payment_terms")): ?> 
                            <div class="alert alert-danger mt-2"><?php echo e($errors->first('payment_terms')); ?></div>
                        <?php endif; ?>
                    </div>
                    <div>
                        <button type="button" class="btn btn-success me-1 mt-1" onclick="AddMoreProducts()">
                            <i class="fa fa-fw fa-plus me-1"></i> Add More Products
                        </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>Price</th>
                                        <th>Quantity</th>
                                        <th>Total</th>
                                    </tr>
                                </thead>
                                <tbody id="products-tbody">
                                    <tr>
                                        <td>
              
                                            <select class="js-select2 form-select product-select" name="product[]" style="width: 100%;" data-placeholder="Select a product.." required>
                                                <option></option>
                                                <?php foreach($products as $product){ ?> 
                                                    <option value="<?php echo e($product->id); ?>"><?php echo e($product->product_name); ?></option>
                                                <?php } ?>
                                            </select>
                                        </td>
                                        <td>
                                            <select class="js-select2 form-select batch-select" name="batch[]" style="width: 100%;" data-placeholder="Select a batch.." required>
                                                <option></option>
                                            </select>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control price-input" name="price[]" required>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control quantity-input" name="quantity[]"  value="1" required>
                                        </td>
                                       
                                        <td class="total-cell"></td>
                                        <td >   <button type="button" class="btn btn-danger btn-xs btn-remove">
                                               X
                                            </button></td>
                                    </tr>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="4" style="text-align:right">Sub Total</th>
                                        <th id="sub-total"></th>
                                    </tr>
                                    <tr>
                                        <th colspan="4" style="text-align:right">Tax (%) +</th>
                                        <th><input type="number" class="form-control" name="tax" id="tax"  value="0" onkeyup="updateTotal()"></th>
                                    </tr>
                                    <tr>
                                        <th colspan="4" style="text-align:right">Discount (%) -</th>
                                        <th><input type="number" class="form-control" name="discount" id="discount" onkeyup="updateTotal()"  value="0"></th>
                                    </tr>
                                    <tr>
                                        <th colspan="4" style="text-align:right">Total</th>
                                        <th  id="order-total"></th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                        <input type="hidden" name="sub_total_input" id="sub_total_input" value="0">
                        <input type="hidden" name="order_total_input" id="order_total_input" value="0">
                        <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>
    function AddMoreProducts() {
        var newRow = `<tr>
            <td>
                <select class="js-select2 form-select product-select" name="product[]" style="width: 100%;" data-placeholder="Select a product.." required>
                    <option></option>
                    <?php foreach($products as $product){ ?> 
                        <option value="<?php echo e($product->id); ?>"><?php echo e($product->product_name); ?></option>
                    <?php } ?>
                </select>
            </td>
            <td>
                <select class="js-select2 form-select batch-select" name="batch[]" style="width: 100%;" data-placeholder="Select a batch.." required>
                    <option></option>
                </select>
            </td>
            <td>
                <input type="number" class="form-control price-input" name="price[]" required>
            </td>
            <td>
                <input type="number" class="form-control quantity-input" name="quantity[]" value="1" required>
            </td>
            <td class="total-cell"></td>
            <td >   <button type="button" class="btn btn-danger btn-xs btn-remove">
                                               X
                                            </button></td>
        </tr>`;
        $('#products-tbody').append(newRow);

        // Initialize select2 for new elements
        $('.js-select2').select2();

        // Add event listeners for new elements
        addEventListeners();
    }

    function addEventListeners() {
        $('.product-select').last().change(onProductChange);
        $('.batch-select').last().change(onBatchChange);
        $('.price-input').last().on('input', onPriceOrQuantityChange);
        $('.quantity-input').last().on('input', onPriceOrQuantityChange);
    }

    function onProductChange() {
        var row = $(this).closest('tr');
        var productId = $(this).val();
        var batchSelect = row.find('.batch-select');
        batchSelect.empty();
        if (productId) {
            $.ajax({
                url: '<?php echo e(url('admin/get-batches')); ?>/' + productId,
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    console.log(data);
                    batchSelect.append('<option></option>');
                    $.each(data, function(key, value) {
                        batchSelect.append('<option value="'+ value.grn_id +'" data-retail="' + value.retail_selling_price + '" data-wholesale="' + value.wholesale_selling_price + '">'+ value.g_r_n.grn_number +'</option>');
                    });
                }
            });
        } else {
            batchSelect.append('<option value="">Select a batch..</option>');
        }
    }

    function onBatchChange() {
        var row = $(this).closest('tr');
        var priceMethod = $('#price_method').val();
        var priceInput = row.find('.price-input');
        var selectedOption = $(this).find(':selected');
        var retailPrice = selectedOption.data('retail');
        var wholesalePrice = selectedOption.data('wholesale');

        if (priceMethod === 'retail') {
            priceInput.val(retailPrice);
        } else {
            priceInput.val(wholesalePrice);
        }

        calculateTotal(row);
        calculateOrderSubTotal(); // Update the order subtotal
        updateTotal(); // Update the order total
    }

    function onPriceOrQuantityChange() {
        var row = $(this).closest('tr');
        calculateTotal(row);
        calculateOrderSubTotal(); // Update the order subtotal
        updateTotal(); // Update the order total
    }

    function calculateTotal(row) {
        var price = parseFloat(row.find('.price-input').val()) || 0;
        var quantity = parseFloat(row.find('.quantity-input').val()) || 0;
        var total = price * quantity;
        row.find('.total-cell').text(total.toFixed(2));
    }

    function calculateOrderSubTotal() {
        var orderSubTotal = 0;
        $('#products-tbody tr').each(function() {
            var total = parseFloat($(this).find('.total-cell').text()) || 0;
            orderSubTotal += total;
        });
        $('#sub-total').text(orderSubTotal.toFixed(2));
        $('#sub_total_input').val(orderSubTotal);
    }

    function updateTotal() {
        var subTotal = parseFloat($('#sub-total').text()) || 0;
        var tax = parseFloat($('#tax').val()) || 0;
        var discount = parseFloat($('#discount').val()) || 0;

        var taxAmount = (subTotal * tax) / 100;
        var discountAmount = (subTotal * discount) / 100;
        var orderTotal = subTotal + taxAmount - discountAmount;

        $('#order-total').text(orderTotal.toFixed(2));
        $('#order_total_input').val(orderTotal);
    }
    document.getElementById('products-tbody').addEventListener('click', function(event) {
        if (event.target.matches('.btn-remove, .btn-remove *')) {
            removeRow(event);
        }
    });
    function removeRow(event) {
        const button = event.target;
        const row = button.closest('tr');
        row.remove();
        calculateOrderSubTotal();
        updateTotal();
    }
    // Initial event listeners
    $(document).ready(function() {
        $('.product-select').change(onProductChange);
        $('.batch-select').change(onBatchChange);
        $('.price-input').on('input', onPriceOrQuantityChange);
        $('.quantity-input').on('input', onPriceOrQuantityChange);
        $('#tax').on('input', updateTotal);
        $('#discount').on('input', updateTotal);

        // Initial calculation of the order total
        calculateOrderSubTotal();
        updateTotal();
    });

</script>
<?php /**PATH /home/dilsnoon/orionuxerp.store/Modules/Admin/resources/views/sales/add_order.blade.php ENDPATH**/ ?>