@include('admin::layouts.header')
<?php
use App\Models\CustomerDetails;
use App\Models\Products;
use App\Models\GRNS;
?>
<style>
    .big-text{
        font-size: 32px;
    }
    .block-content .block, .block-content .items-push>div, .block-content .push, .block-content p {
    margin-bottom: 0px;
}
.nav-tabs-block {
    background-color: #fff;
    border-bottom: none;
}
.nav-tabs-block .nav-item.show .nav-link, .nav-tabs-block .nav-link.active {
    color: #fff;
    background-color: #2E5FCF;
    border-color: #2E5FCF;
    border-radius: 6px;
}
.nav-tabs-block .nav-item.show .nav-link, .nav-tabs-block .nav-link {
    color: #2E5FCF;
    background-color: #A2BCFA;
    border-color: #A2BCFA;
    border-radius: 6px;
    margin-left:10px;
    margin-right:10px;
}
.keypad {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 5px;
        width: 100%;
        margin-top: 10px;
    }
    .key {
        padding: 10px;
        font-size: 18px;
        cursor: pointer;
        border: 1px solid #ccc;
        background: #f8f9fa;
    }
    .key:hover {
        background: #dcdcdc;
    }
    .key:active {
        background: #a9a9a9;
    }
</style>
<main id="main-container">

    <!-- <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> -->

    <div class="content">

        <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')){
                if(Session::get('bill_receive_method') == 'whatsapp'){ ?>
                <!-- <div class="alert alert-success mt-2 mb-2">
                    <a id="whatsapp-link" href="{{ Session::get('whatsapp_link') }}" target="_blank" class="btn btn-primary mt-2">
                           WhatsApp
                    </a>
                </div> -->
                <script>
                    window.onload = function() {
                        var whatsappLink = "{{ Session::get('whatsapp_link') }}";

                        setTimeout(function() {
                            window.open(whatsappLink, '_blank');
                        }, 1000); 
                        
                    };
                </script>
            <?php }
                else{ ?>
                <!-- <div class="alert alert-success mt-2 mb-2">
                    <a target="_blank" id="pdf-link" href="{{ Session::get('pdf_url') }}" class="btn btn-success mt-2">
                        Click here to view the invoice
                    </a>
                </div> -->
                <script>
                    // window.onload = function() {
                    //     var pdfUrl = "{{ Session::get('pdf_url') }}";

                    //         var printWindow = window.open(pdfUrl, '_blank');
                    //         if (printWindow) {
                    //             setTimeout(function() {
                    //                 printWindow.print();
                    //             }, 1000);
                    //         }
                    // };
                    window.onload = function() {
                        var invoice = "{{ Session::get('pdf_url') }}";

                        setTimeout(function() {
                            window.open(invoice, '_blank');
                        }, 1000); 
                        
                    };
                </script> 
            <?php } ?>
        
            <div class="alert alert-success mt-2 mb-2">
                    <a target="_blank" id="pdf-link" href="{{ Session::get('pdf_url') }}" class="btn btn-success mt-2">
                           Print Bill
                    </a>
                    <a id="whatsapp-link" href="{{ Session::get('whatsapp_link') }}" target="_blank" class="btn btn-success mt-2">
                           WhatsApp
                    </a>
                    <a href="{{url('admin/premium')}}"><button class="btn btn-success mt-2" type="button" >Email <span class="nav-main-link-badge badge rounded-pill bg-danger">Premium</span>
                        </button></a>
                    <a href="{{url('admin/premium')}}"><button class="btn btn-success mt-2" type="button">SMS <span class="nav-main-link-badge badge rounded-pill bg-danger">Premium</span>
                    </button></a>
            </div> 
           <?php } ?>
                
                @if(Session::has('fail')) 
                    <div class="alert alert-danger mt-2 mb-2">{{ Session::get('fail') }}</div>
                @endif
                <form class="row" action="" method="POST" id="bill-form" >
                    @csrf
                    

                    <div class="col-md-3 mb-3">
    <label class="form-label">Customer <button class="btn btn-success btn-sm" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasAddCustomer" aria-controls="offcanvasAddCustomer">+
    </button></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 data-mobile="{{ CustomerDetails::where('user_id', old('customer'))->value('phone') }}" 
                    value="{{ old('customer') }}" selected>
                {{ CustomerDetails::where('user_id', old('customer'))->value('customer_name').' ('.CustomerDetails::where('user_id', old('customer'))->value('phone').')' }}
            </option>
        <?php } ?>
        <option data-mobile="-" data-discount="0" value="Cash">Cash</option>
        <?php foreach($customers as $customer) { ?> 
            <option data-mobile="{{ $customer->customerDetails->phone }}" data-discount="{{ $customer->customerDetails->discount ?? 0 }}" value="{{ $customer->id }}">
                {{ $customer->customerDetails->customer_name.' ('.$customer->customerDetails->phone.')' }}
            </option>
        <?php } ?>
    </select>
    @if($errors->has("customer")) 
        <div class="alert alert-danger mt-2">{{ $errors->first('customer') }}</div>
    @endif
</div>

<div class="col-md-3 mb-3">
    <label class="form-label">Mobile No</label>
    <input type="text" class="form-control" id="mobile_no" name="mobile_no" value="-" required>
    @if($errors->has("mobile_no")) 
        <div class="alert alert-danger mt-2">{{ $errors->first('mobile_no') }}</div>
    @endif
</div>
                  
                    <div>
                        <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>Discount (%) </th>
                                        <th>Total</th>
                                    </tr>
                                </thead>
                                <tbody id="products-tbody">
                                    <tr>
                                        <td style="width:350px;"> 
              
                                            <select class="js-select2 form-select product-select" name="product[]" style="width: 100%;" data-placeholder="Select a product.." >
                                                <option></option>
                                                <?php foreach($products as $product){ ?> 
                                                    <option value="{{$product->id}}">Product - {{$product->product_name}} ({{$product->barcode}})</option>
                                                <?php } ?>
                                            </select>
                                        </td>
                                        <td>
                                            <select class="js-select2 form-select batch-select" name="batch[]" style="width: 100%;" data-placeholder="Select a batch.." >
                            
                                            </select>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control price-input" name="price[]" >
                                        </td>
                                      
                                        <td>
                                        <div class="input-group">
                                            <button type="button" class="btn btn-outline-warning btn-decrement">-</button>
                                            <input type="number" class="form-control quantity-input text-center" name="quantity[]" value="1" min="1">
                                            <button type="button" class="btn btn-outline-info btn-increment">+</button>
                                        </div>
                                        <p style="color:red;font-weight:600;" class="qty-error"></p>
                                        </td>
                                        <td>
                                            <input type="number" class="form-control discount-input" name="discounts[]" value="0">
                                        </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">Service Charges (%) +</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>
                        <!-- <div id="keypad2" class="keypad">
                                <button type="button" class="key" data-value="1">1</button>
                                <button type="button" class="key" data-value="2">2</button>
                                <button type="button" class="key" data-value="3">3</button>
                                <button type="button" class="key" data-value="4">4</button>
                                <button type="button" class="key" data-value="5">5</button>
                                <button type="button" class="key" data-value="6">6</button>
                                <button type="button" class="key" data-value="7">7</button>
                                <button type="button" class="key" data-value="8">8</button>
                                <button type="button" class="key" data-value="9">9</button>
                                <button type="button" class="key" data-value="0">0</button>
                                <button type="button" class="key" data-action="clear">C</button>
                                <button type="button" class="key" data-action="backspace">←</button>
                            </div> -->
                        <input type="hidden" name="sub_total_input" id="sub_total_input" value="0">
                       
                        <!-- <button type="button" class="btn btn-primary">Proceed</button> -->
                        <button class="btn btn-primary mt-4" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasRight" aria-controls="offcanvasRight">Proceed
                        </button>
                        <div class="offcanvas offcanvas-end bg-body-extra-light" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel">
                    <div class="offcanvas-header bg-body-light">
                      <h5 class="offcanvas-title" id="offcanvasRightLabel">Confirm Order</h5>
                      <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                    </div>
                    <div class="offcanvas-body">
                      <p>
                      <div class="block-content">
                        <div class="py-2">
                            <p>
                            <strong>Total : <span class="big-text" id="total-span" style="color:#0665d0;">0</span></strong> 
                            </p>
                            <p>
                           
                            </p>

                            <div class=" tab-content overflow-hidden mt-4">
                            <div class="tab-pane fade fade-right active show" id="btabs-animated-slideright-home" role="tabpanel" aria-labelledby="btabs-animated-slideright-home-tab" tabindex="0">
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Bill Amount</label>
                                    <input type="number" class="form-control" name="order_total_input" id="order_total_input" value="0" readonly>
                                </div>
                                <div class="col-md-12 mb-3">
                                <p class="mt-4 mb-1" style="color:#0665d0;"><strong>Cash Payments</strong> </p>
                                    <label class="form-label">Cash Amount</label>
                                    <input type="number" class="form-control" name="cash_amount" id="cash_amount">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Received Amount</label>
                                    <input type="number" class="form-control" name="received_amount" id="received_amount">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Balance</label>
                                    <input type="number" class="form-control" name="balance" id="balance" readonly>
                                </div>
                                <div class="col-md-12 mb-3">
                                <p class="mt-4 mb-1" style="color:#0665d0;"><strong>Card Payments</strong> </p>
                                    <label class="form-label">Card Amount</label>
                                    <input type="number" class="form-control" name="card_paying_amount" id="card_paying_amount">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Card Ref No</label>
                                    <input type="text" class="form-control" name="card_ref_no" id="card_ref_no">
                                </div>
                                <div class="col-md-12 mb-3">
                                <p class="mt-4 mb-1" style="color:#0665d0;"><strong>Online Payments</strong> </p>
                                    <label class="form-label">Online Amount</label>
                                    <input type="number" class="form-control" name="online_amount" id="online_amount">
                                </div>

                                <div class="col-md-12 mb-3">
                                <p class="mt-4 mb-1" style="color:#0665d0;"><strong>Summery</strong> </p>
                                    <label class="form-label">Paid Amount</label>
                                    <input type="number" class="form-control" name="paid_amount" id="paid_amount" readonly>
                                </div>

                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Remaining Amount</label>
                                    <input type="number" class="form-control" name="remaining_amount" id="remaining_amount" readonly>
                                </div>
                            </div>
                            
                            </div>
                            <!-- <div id="keypad" class="keypad">
                                <button type="button" class="key" data-value="1">1</button>
                                <button type="button" class="key" data-value="2">2</button>
                                <button type="button" class="key" data-value="3">3</button>
                                <button type="button" class="key" data-value="4">4</button>
                                <button type="button" class="key" data-value="5">5</button>
                                <button type="button" class="key" data-value="6">6</button>
                                <button type="button" class="key" data-value="7">7</button>
                                <button type="button" class="key" data-value="8">8</button>
                                <button type="button" class="key" data-value="9">9</button>
                                <button type="button" class="key" data-value="0">0</button>
                                <button type="button" class="key" data-action="clear">C</button>
                                <button type="button" class="key" data-action="backspace">←</button>
                            </div> -->
                        <p class="mb-0 mt-2"  id="bill-error" style="color:red;font-weight:600"></p>
                        <button class="btn btn-success mt-4" type="submit" name="submit_button" disabled id="print-button" value="print_submit">Print Bill
                        </button>
                        <p class="mb-0 mt-4" >
                            <strong>Send VIA</strong> 
                        </p>
                        <button class="btn btn-success mt-2" type="submit" name="submit_button" disabled id="whatsapp-button" value="whatsapp_submit">Whatsapp
                        </button>
                        <a href="{{url('admin/premium')}}"><button class="btn btn-success mt-2" type="button" name="submit_button" disabled id="email-button" value="whatsapp_email">Email <span class="nav-main-link-badge badge rounded-pill bg-danger">Premium</span>
                        </button></a>
                        <a href="{{url('admin/premium')}}"><button class="btn btn-success mt-2" type="button" name="submit_button" disabled id="sms-button" value="whatsapp_sms">SMS <span class="nav-main-link-badge badge rounded-pill bg-danger">Premium</span>
                        </button></a>
                        
                    <script>
    document.getElementById('offcanvasRight').addEventListener('shown.bs.offcanvas', function () {
        document.getElementById('cash_amount').focus();
    });

    document.addEventListener("DOMContentLoaded", function () {
        const orderTotalInput = document.getElementById("order_total_input");
        const cashAmount = document.getElementById("cash_amount");
        const receivedAmount = document.getElementById("received_amount");
        const balance = document.getElementById("balance");
        const cardPayingAmount = document.getElementById("card_paying_amount");
        const cardRef = document.getElementById("card_ref_no");
        const onlineAmount = document.getElementById("online_amount");
        const paidAmount = document.getElementById("paid_amount");
        const remainingAmount = document.getElementById("remaining_amount");

        const printButton = document.getElementById("print-button");
        const whatsappButton = document.getElementById("whatsapp-button");
        const billError = document.getElementById("bill-error");

        function updatePaymentDetails() {
            const billAmount = parseFloat(orderTotalInput.value) || 0;
            const cash = parseFloat(cashAmount.value) || 0;
            const received = parseFloat(receivedAmount.value) || 0;
            const card = parseFloat(cardPayingAmount.value) || 0;
            const online = parseFloat(onlineAmount.value) || 0;

            const totalPaid = cash + card + online;
            const remaining = billAmount - totalPaid;
            const cashBalance = received - cash;

            // Set calculated values
            paidAmount.value = totalPaid.toFixed(2);
            remainingAmount.value = remaining > 0 ? remaining.toFixed(2) : "0.00";
            balance.value = cashBalance >= 0 ? cashBalance.toFixed(2) : "0.00";

            // Enable/disable submit buttons
            if (remaining <= 0 && totalPaid >= billAmount) {
                printButton.disabled = false;
                whatsappButton.disabled = false;
                billError.innerHTML = "";
            } else {
                printButton.disabled = true;
                whatsappButton.disabled = true;
                billError.innerHTML = "Please complete the full payment. Remaining amount must be 0.";
            }
        }
        cashAmount.addEventListener("keydown", function (e) {
            if (e.key === "Enter") {
                e.preventDefault();
                receivedAmount.focus();
            }
        });

        receivedAmount.addEventListener("keydown", function (e) {
            if (e.key === "Enter") {
                e.preventDefault();
                cardPayingAmount.focus();
            }
        });

        cardPayingAmount.addEventListener("keydown", function (e) {
            if (e.key === "Enter") {
                e.preventDefault();
                cardRef.focus();
            }
        });

        cardRef.addEventListener("keydown", function (e) {
            if (e.key === "Enter") {
                e.preventDefault();
                onlineAmount.focus();
            }
        });

        onlineAmount.addEventListener("keydown", function (e) {
            if (e.key === "Enter") {
                e.preventDefault();
                onlineAmount.blur(); 
            }
        });
        // Attach event listeners
        document.querySelectorAll("#cash_amount, #received_amount, #card_paying_amount, #online_amount").forEach(input => {
            input.addEventListener("input", updatePaymentDetails);
        });

    
    document.querySelectorAll(".key").forEach(key => {
        key.addEventListener("click", function () {
            if (!activeInput) return;
            const value = this.getAttribute("data-value");
            const action = this.getAttribute("data-action");
            
            if (value) {
                activeInput.value += value;
            } else if (action === "clear") {
                activeInput.value = "";
            } else if (action === "backspace") {
                activeInput.value = activeInput.value.slice(0, -1);
            }
            updateBalance();
        });
    });
});


</script>
                        </div>
                        </div>
                      </p>
                    </div>
                  </div>
                    </div>
                </form>
            </div>
        </div>
        <!-- END Your Block -->
    </div>
    <!-- END Page Content -->
</main>
<!-- END Main Container -->
@include('admin::layouts.footer')

<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.." >
                    <option></option>
                    <?php foreach($products as $product){ ?> 
                        <option value="{{$product->id}}">Product - {{$product->product_name}} ({{$product->barcode}})</option>
                    <?php } ?>
                </select>
            </td>
            <td>
                <select class="js-select2 form-select batch-select" name="batch[]" style="width: 100%;" data-placeholder="Select a batch.." >
                   
                </select>
            </td>
            <td>
                <input type="number" class="form-control price-input" name="price[]" value="0">
            </td>
            
            <td>
            <div class="input-group">
                <button type="button" class="btn btn-outline-warning btn-decrement">-</button>
                <input type="number" class="form-control quantity-input text-center" name="quantity[]" value="1" min="1">
                <button type="button" class="btn btn-outline-info btn-increment">+</button>
            </div>
            <p style="color:red;font-weight:600;" class="qty-error"></p>
        </td>
         <td>
            <input type="number" class="form-control discount-input" name="discounts[]" value="0">
        </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);

        $('.js-select2').select2();
        addEventListeners();
    }

    function addEventListeners() {
        $('.product-select').last().change(onProductChange);
        $('.batch-select').last().change(onBatchChange);
        $('.price-input').last().on('input', onPriceChange);
        $('.price-input').last().on('keypress', function(event) {
            if (event.which === 13) {
                openNextQuantity($(this));
            }
        });
        $('.quantity-input').last().on('input', onPriceOrQuantityChange);
        $('.quantity-input').last().on('keypress', function(event) {
            if (event.which === 13) {
                openNextDiscount($(this));
            }
        });
        $('.discount-input').last().on('input', onDiscountChange);
        $('.discount-input').last().on('keypress', function(event) {
            if (event.which === 13) {
                openNextSelect();
            }
        });
    }

    function onProductChange() {
        var row = $(this).closest('tr');
        var productId = $(this).val();
        // var productId = productValue.split('||')[1];
        var priceInput = row.find('.price-input');
        var batchSelect = row.find('.batch-select');
        batchSelect.empty();
        if (productId) {
            $.ajax({
                url: '{{ url('admin/get-batches') }}/' + productId,
                type: 'GET',
                dataType: 'json',
                success: function(data) {
                    console.log(data);

                    $.each(data, function(key, value) {
                        batchSelect.append('<option value="'+ value.batch_id +'" data-retail="' + value.mrp + '" data-wholesale="' + value.mrp + '" data-avilable-qty="' + value.stock + '">'+ value.batch_name +'</option>');
                    });
                    batchSelect.val(data[0].batch_id).trigger('change');
                    priceInput.focus().select();
                    AddMoreProducts();
                }
            });
        } 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');
        priceInput.val(retailPrice);
        calculateTotal(row);
        calculateOrderSubTotal();
        updateTotal(); 
    }
    function onDiscountChange() {
        console.log($(this).val());
        var row = $(this).closest('tr');
        calculateTotal(row);
        calculateOrderSubTotal();
        updateTotal(); 
    }
    function onPriceChange() {
        var row = $(this).closest('tr');
        // var quantityInput = row.find('.quantity-input');
        // quantityInput.focus().select();
        calculateTotal(row);
        calculateOrderSubTotal(); 
        updateTotal(); 

    }
    function onPriceOrQuantityChange() {
        var row = $(this).closest('tr');
        var priceInput = row.find('.price-input');
        var batchSelect = row.find('.batch-select');
        var selectedOption = batchSelect.find(':selected');
        var qty = selectedOption.data('avilable-qty');
        var qtyError =  row.find('.qty-error');
        console.log('qty',qty);
        console.log('entered qty',$(this).val());
        calculateTotal(row);
        calculateOrderSubTotal(); 
        updateTotal(); 
        // $('.product-select').last().select2('open');
        if( parseFloat(qty ) <  parseFloat($(this).val())){
            alert("Entered quantity exceeds available stock (" + qty + ")");
            qtyError.text("Entered quantity exceeds available stock (" + qty + ")");
        }
        else{
            qtyError.text(""); 
        }
    }
    function openNextSelect() {
        $('.product-select').last().select2('open');
    }
    function openNextQuantity(inputElement) {
    var row = inputElement.closest('tr');
    var quantityInput = row.find('.quantity-input');

    quantityInput.focus().select();
    }
    function openNextDiscount(inputElement) {
    var row = inputElement.closest('tr');
    var discountInput = row.find('.discount-input');

    discountInput.focus().select();
    }
    function calculateTotal(row) {
        var price = parseFloat(row.find('.price-input').val()) || 0;
        var quantity = parseFloat(row.find('.quantity-input').val()) || 0;
        var discount = parseFloat(row.find('.discount-input').val()) || 0;
        
        var lineDiscountAmount = (price * quantity * discount) / 100;
        var total = (price * quantity) - lineDiscountAmount;
        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);
        // $('#card_paying_amount').val(orderTotal);
        // $('#cash_amount').val(orderTotal);
        $('#paying_amount').val(orderTotal);
        $('#total-span').text('Rs.'+orderTotal.toFixed(2));
    }
    document.getElementById('products-tbody').addEventListener('click', function(event) {
        if (event.target.matches('.btn-remove, .btn-remove *')) {
            removeRow(event);
        }
    });

    $(document).on("click", ".btn-increment", function() {
      
        var input = $(this).siblings(".quantity-input");
        var value = parseInt(input.val(), 10);
        input.val(value + 1).trigger("input");

    });


    $(document).on("click", ".btn-decrement", function() {
        var input = $(this).siblings(".quantity-input");
        var value = parseInt(input.val(), 10);
        if (value > 1) {
            input.val(value - 1).trigger("input");
        }

    });
    function removeRow(event) {
        const button = event.target;
        const row = button.closest('tr');
        row.remove();
        calculateOrderSubTotal();
        updateTotal();
    }
    $(document).ready(function() {
        $('.product-select').change(onProductChange);
        $('.batch-select').change(onBatchChange);
        $('.discount-input').on('input', onPriceOrQuantityChange);
        $('.discount-input').last().on('keypress', function(event) {
            if (event.which === 13) {
                openNextSelect();
            }
        });
        $('.price-input').on('input', onPriceChange);
        $('.price-input').last().on('keypress', function(event) {
            if (event.which === 13) {
                openNextQuantity($(this));
            }
        });
        $('.quantity-input').on('input', onPriceOrQuantityChange);
        $('.quantity-input').last().on('keypress', function(event) {
            if (event.which === 13) {
                openNextDiscount($(this));
            }
        });
        $('#tax').on('input', updateTotal);
        $('#discount').on('input', updateTotal);
        calculateOrderSubTotal();
        updateTotal();
    });

</script><script>
$(document).ready(function() {
    $('#customer').select2();
    $('.product-select').select2('open');
    $('#customer').on('change', function() {
        var mobileNumber = $(this).find(':selected').data('mobile');
        var discount = $(this).find(':selected').data('discount');
        $('#mobile_no').val(mobileNumber || '');
        $('#discount').val(discount || 0);
        calculateOrderSubTotal(); 
        updateTotal(); 
    });
});
$(document).ready(function() {
    $('.toggle-nav-bar').click();
});

</script>

<div class="offcanvas offcanvas-end bg-body-extra-light" tabindex="-1" id="offcanvasAddCustomer" aria-labelledby="offcanvasAddCustomerLabel">
<div class="offcanvas-header bg-body-light">
    <h5 class="offcanvas-title" id="offcanvasAddCustomerLabel">Add Customer</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
</div>
<div class="offcanvas-body">
<div class="col-md-12 mb-3">
<label class="form-label">Customer Name</label>
<input type="text" class="form-control" name="customer_name" value="" id="customer_name">
</div>
<div class="col-md-12 mb-3">
    <label class="form-label">Phone No</label>
    <input type="text" class="form-control" name="phone"  value="" id="customer_phone">
</div>
<div class="col-md-12 mb-3">
    <label class="form-label">Email</label>
    <input type="email" class="form-control" name="email" value="" id="customer_email">
</div>
<div class="col-md-12 mb-3">
    <label class="form-label">Discount</label>
    <input type="number" class="form-control" name="discount" value="" id="customer_discount">
</div>

<button class="btn btn-success mt-2 add-customer-btn" type="button" >Add Customer</button>
</div>
</div>

<script>
    $(document).ready(function () {
        $(".add-customer-btn").click(function () {
            let customer_name = $("#customer_name").val().trim();
            let customer_phone = $("#customer_phone").val().trim();
            let customer_email = $("#customer_email").val().trim();
            let customer_discount = $("#customer_discount").val().trim();

            $.ajax({
                url: "{{ url('admin/add-customer-ajax') }}", 
                type: "POST",
                data: {
                    _token: "{{ csrf_token() }}",
                    customer_name: customer_name,
                    phone: customer_phone,
                    email: customer_email,
                    discount: customer_discount
                },
                success: function (response) {
                    alert(response.message);
                    $("#customer_name, #customer_phone, #customer_email, #customer_discount").val("");
                    refreshCustomers();
                },
                error: function (xhr) {
                    let errors = xhr.responseJSON.errors;
                    if (errors) {
                        let errorMessages = "";
                        $.each(errors, function (key, value) {
                            errorMessages += value[0] + "\n";
                        });
                        alert(errorMessages);
                    }
                }
            });
        });

        function refreshCustomers() {
            $.ajax({
                url: "{{ url('admin/refresh-customers-ajax') }}", 
                type: "GET",
                success: function (data) {
                    let customerSelect = $("#customer");
                    customerSelect.empty();

                    customerSelect.append('<option data-mobile="-" data-discount="0" value="Cash">Cash</option>');

                    $.each(data, function (key, customer) {
                        customerSelect.append(
                            `<option data-mobile="${customer.phone}" data-discount="${customer.discount}" value="${customer.id}">
                                ${customer.customer_name} (${customer.phone})
                            </option>`
                        );
                    });

                    customerSelect.select2();
                }
            });
        }
    });
</script>
<script>
    document.getElementById('bill-form').addEventListener('submit', function (e) {

        document.getElementById('print-button').disabled = true;
        document.getElementById('whatsapp-button').disabled = true;

        document.getElementById('print-button').innerText = 'Processing...';
        document.getElementById('whatsapp-button').innerText = 'Processing...';
    });
</script>