<?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;
?>
<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="<?php echo e(Session::get('whatsapp_link')); ?>" target="_blank" class="btn btn-primary mt-2">
                            Send to WhatsApp
                    </a>
                </div>
                <script>
                    window.onload = function() {
                        var whatsappLink = "<?php echo e(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="<?php echo e(Session::get('pdf_url')); ?>" class="btn btn-success mt-2">
                        Click here to view the invoice
                    </a>
                </div>
                <script>
                    window.onload = function() {
                        var pdfUrl = "<?php echo e(Session::get('pdf_url')); ?>";

                            var printWindow = window.open(pdfUrl, '_blank');
                            if (printWindow) {
                                setTimeout(function() {
                                    printWindow.print();
                                }, 1000);
                            }
                    };
                </script> 
            <?php }} ?>
                
                <?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">Invoice 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 data-mobile="<?php echo e(CustomerDetails::where('user_id', old('customer'))->value('phone')); ?>" 
                    value="<?php echo e(old('customer')); ?>" selected>
                <?php echo e(CustomerDetails::where('user_id', old('customer'))->value('customer_name')); ?>

            </option>
        <?php } ?>
        <option data-mobile="-" data-discount="0" value="Cash">Cash</option>
        <?php foreach($customers as $customer) { ?> 
            <option data-mobile="<?php echo e($customer->customerDetails->phone); ?>" data-discount="<?php echo e($customer->customerDetails->discount ?? 0); ?>" 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">Mobile No</label>
    <input type="text" class="form-control" id="mobile_no" name="mobile_no" value="-" required>
    <?php if($errors->has("mobile_no")): ?> 
        <div class="alert alert-danger mt-2"><?php echo e($errors->first('mobile_no')); ?></div>
    <?php 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>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="<?php echo e($product->id); ?>"><?php echo e($product->product_name); ?> (<?php echo e($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.." >
                                                <option></option>
                                            </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>
                                        </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>
                        <!-- <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">
                        <input type="hidden" name="order_total_input" id="order_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">10</span></strong> 
                            </p>
                            <p>
                            <strong>BIll Number : <?php echo e($orderNumber); ?></strong>
                            </p>
                            <ul class="nav nav-tabs nav-tabs-block mt-4 justify-content-center" role="tablist">
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" type="button" id="btabs-animated-slideright-home-tab" data-bs-toggle="tab" data-bs-target="#btabs-animated-slideright-home" role="tab" aria-controls="btabs-animated-slideright-home" aria-selected="true">Cash</button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" type="button" id="btabs-animated-slideright-profile-tab" data-bs-toggle="tab" data-bs-target="#btabs-animated-slideright-profile" role="tab" aria-controls="btabs-animated-slideright-profile" aria-selected="false" tabindex="-1">Card</button>
                            </li>
    
                            </ul>
                            <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">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">Paying Amount</label>
                                    <input type="number" class="form-control" name="paying_amount" id="paying_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">
                                    <label class="form-label">Remaining Amount</label>
                                    <input type="number" class="form-control" name="remaining_amount" id="remaining_amount" readonly>
                                </div>
                            </div>
                            <div class="tab-pane fade fade-right" id="btabs-animated-slideright-profile" role="tabpanel" aria-labelledby="btabs-animated-slideright-profile-tab" tabindex="0">
                            <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">
                                    <label class="form-label">Paying 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">Remaining</label>
                                    <input type="number" class="form-control" name="card_balance" id="card_balance" 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>
                        <button class="btn btn-success mt-4" type="submit" name="submit_button" disabled id="print-button" value="print_submit">Print Bill
                        </button>
                        <button class="btn btn-success mt-4" type="submit" name="submit_button" disabled id="whatsapp-button" value="whatsapp_submit">Send Bill via Whatsapp
                        </button>
                        
                    <script>
    document.getElementById('offcanvasRight').addEventListener('shown.bs.offcanvas', function () {
        document.getElementById('cash_amount').focus();
    });

    document.addEventListener("DOMContentLoaded", function () {
    const cashAmount = document.getElementById("cash_amount");
    const payingAmount = document.getElementById("paying_amount");
    const balance = document.getElementById("balance");
    const remainingAmount = document.getElementById("remaining_amount");
    const orderTotalInput = document.getElementById("order_total_input");
    const cardPayingAmount = document.getElementById("card_paying_amount");
    const cardBalance = document.getElementById("card_balance");
    const printButton = document.getElementById("print-button");
    const whatsappButton = document.getElementById("whatsapp-button");
    
    let activeInput = null;
    
    // Initialize payingAmount with order total
    payingAmount.value = orderTotalInput.value;
    
    document.querySelectorAll("input").forEach(input => {
        input.addEventListener("focus", function () {
            activeInput = this;
        });
    });
    
    function updateBalance() {
        const cash = parseFloat(cashAmount.value) || 0;
        const paying = parseFloat(payingAmount.value) || 0;
        const orderTotal = parseFloat(orderTotalInput.value) || 0;
        
        // Calculate balance to return to the customer
        const calculatedBalance = cash - paying;
        balance.value = calculatedBalance >= 0 ? calculatedBalance.toFixed(2) : "0.00";
        
        // Calculate remaining amount
        const calculatedRemaining = orderTotal - paying;
        remainingAmount.value = calculatedRemaining > 0 ? calculatedRemaining.toFixed(2) : "0.00";
        
        // Assign remaining amount to card balance
        cardBalance.value = remainingAmount.value;
        
        // Enable/Disable buttons
        if (remainingAmount.value == 0) {
            printButton.disabled = false;
            whatsappButton.disabled = false;
        } else {
            printButton.disabled = true;
            whatsappButton.disabled = true;
        }
    }
    
    document.querySelectorAll("input").forEach(input => {
        input.addEventListener("input", function (event) {
            updateBalance();
        });
    });
    
    cardPayingAmount.addEventListener("input", function () {
        const cardPaying = parseFloat(cardPayingAmount.value) || 0;
        const cardBal = parseFloat(cardBalance.value) || 0;
        
        if (cardPaying === cardBal) {
            cardBalance.value = "0.00";
            remainingAmount.value = "0.00";
            printButton.disabled = false;
            whatsappButton.disabled = false;
        } else {
            printButton.disabled = true;
            whatsappButton.disabled = true;
        }
    });
    
    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 -->
<?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.." >
                    <option></option>
                    <?php foreach($products as $product){ ?> 
                        <option value="<?php echo e($product->id); ?>"><?php echo e($product->product_name); ?> (<?php echo e($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.." >
                    <option></option>
                </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>
        </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', onPriceOrQuantityChange);
        $('.quantity-input').last().on('input', onPriceOrQuantityChange);
    }

    function onProductChange() {
        var row = $(this).closest('tr');
        var productId = $(this).val();
        var quantityInput = row.find('.quantity-input');
        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);

                    $.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>');
                    });
                    batchSelect.val(data[0].grn_id).trigger('change');
                    quantityInput.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 onPriceOrQuantityChange() {
        var row = $(this).closest('tr');
        calculateTotal(row);
        calculateOrderSubTotal(); 
        updateTotal(); 

        $('.product-select').last().select2('open');
    }

    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);
        // $('#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);
        $('.price-input').on('input', onPriceOrQuantityChange);
        $('.quantity-input').on('input', onPriceOrQuantityChange);
        $('#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(); 
    });
});
</script>
<?php /**PATH D:\Part Time Work\shoes\Modules/Admin\resources/views/sales/add_order.blade.php ENDPATH**/ ?>