@extends('backend.layouts.master')
@section('title')
    inventory - {{ 'Quick Salse Create' }}
@endsection

@section('styles')
    <style>
        .bootstrap-switch-large {
            width: 200px;
        }
    </style>
@endsection

@section('navbar-content')
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h5 class="m-0">
                        Quick Sales </h5>
                </div><!-- /.col -->
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="{{ route('home') }}">Dashboard</a></li>
                        @if (helper::roleAccess('sale.sale.index'))
                            <li class="breadcrumb-item"><a href="{{ route('sale.sale.index') }}">Sale</a></li>
                        @endif
                        <li class="breadcrumb-item active"><span>Sale List</span></li>
                    </ol>
                </div><!-- /.col -->
            </div><!-- /.row -->
        </div><!-- /.container-fluid -->
    </div>
@endsection

@section('admin-content')
    <div class="row">
        <div class="col-md-12">
            <div class="card card-default">
                <div class="card-header">
                    <h3 class="card-title">Quick Salse Create</h3>
                </div>
                <div class="card-body">


                    <form id="orderForm" action="{{ route('quick.salse.store') }}" method="POST">
                        @csrf
                        @php
                            $ledgers = App\Models\ChartOfAccount::whereIn('id', [
                                getAccountByUniqueID(5)->id,
                                getAccountByUniqueID(16)->id,
                            ])->get();
                            $customerGroup = App\Models\CustomerGroup::all();

                        @endphp
                        <div class="form-section row">
                            <div class="form-row w-100" style="gap:2">
                                <div class="form-group col-md-6">
                                    <label for="date">Date:</label>
                                    <input type="date" id="date" name="date" class="form-control" required>
                                </div>
                                <div class="form-group col-md-6 mb-2">
                                    <label for="ledger_id">Customer *:
                                        <button type="button" class="btn btn-sm btn-primary ml-2" data-toggle="modal"
                                            data-target="#addCustomerModel">
                                            +
                                        </button>
                                    </label>
                                    <select class="form-control select2" name="ledger_id" id="ledger_id">
                                        <option selected disabled value="">--Select Ledger--</option>
                                        <x-account :setAccounts="$ledgers" />
                                    </select>
                                    @error('ledger_id')
                                        <span class="error text-danger font-weight-bold">{{ $message }}</span>
                                    @enderror
                                </div>
                                <div class="form-group col-md-6 mb-2">
                                    <label for="">Branch</label>
                                    @php
                                        $ledgers = App\Models\Branch::all(); // Fetch the ledgers from the database
                                    @endphp
                                    <select class="form-control select2" name="branch_id" id="branch_id">
                                        <option selected disabled value="">--Select Branch--</option>
                                        @foreach ($ledgers as $ledger)
                                            <option value="{{ $ledger->id }}">{{ $ledger->name }}</option>
                                        @endforeach
                                    </select>
                                    @error('branch_id')
                                        <span class="error text-danger font-weight-bold">{{ $message }}</span>
                                    @enderror
                                </div>

                            </div>
                        </div>

                        <div class="form-section">
                            <h4>Product Details</h4>
                            <div class="form-row align-items-center mb-2">
                                <div class="form-group col-md-4">
                                    <label for="productName">Product Name:</label>
                                    <input type="text" id="productName" class="form-control"
                                        placeholder="Enter Product Name">
                                </div>
                                <div class="form-group col-md-4">
                                    <label for="fabricSpecification">Fabric Specification:</label>
                                    <input type="text" id="fabricSpecification" class="form-control"
                                        placeholder="Enter Fabric Specification">
                                </div>

                                <div class="form-group col-md-4">
                                    <label for="productSpecification">Product Specification:</label>
                                    <input type="text" id="productSpecification" class="form-control"
                                        placeholder="Enter Product Specification">
                                </div>

                                <div class="form-group col-md-4">
                                    <label for="productPrice">Price:</label>
                                    <input type="number" id="productPrice" class="form-control" placeholder="Enter Price">
                                </div>
                                <div class="form-group col-md-2">
                                    <label for="productQty">Quantity:</label>
                                    <input type="number" id="productQty" class="form-control" placeholder="Enter Quantity">
                                </div>
                                @php
                                    $fabrics = App\Models\Fabric::select('name', 'id')->get();
                                @endphp

                                <div class="form-group col-md-2">
                                    <label for="SelectFabric">Select Fabric:</label>
                                    <select name="fabric" id="fabric" class="form-control select2">
                                        <option value="">Select Fabrics</option>
                                        @foreach ($fabrics as $fabric)
                                            <option value="{{ $fabric->id }}" data-name='{{ $fabric->name }}'>
                                                {{ $fabric->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="form-group col-md-2">
                                    <label for=""></label>
                                    <button type="button" class="btn btn-primary btn-block" id="addProduct">Add
                                        Product</button>
                                </div>
                            </div>
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th>SL</th>
                                        <th>Product Name</th>
                                        <th>Product Specification</th>
                                        <th>Fabric Specification</th>
                                        <th>Fabric</th>
                                        <th>Price</th>
                                        <th>Quantity</th>
                                        <th>Total Price</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody id="productList">
                                    <!-- Dynamically added rows will appear here -->
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="6" class="text-right font-weight-bold">Shipping Charge:</td>
                                        <td>
                                            <input type="number" id="shippingCharge" name="shipping_charge"
                                                class="form-control" placeholder="Enter Shipping Charge" min="0"
                                                value="0">
                                        </td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td colspan="6" class="text-right font-weight-bold">Grand Total:</td>
                                        <td id="grandTotal" class="font-weight-bold">0.00</td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td colspan="6" class="text-right font-weight-bold">Discount:</td>
                                        <td>
                                            <input type="number" name="discount" id="discount" class="form-control"
                                                placeholder="Enter Discount" min="0" value="0">
                                        </td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td colspan="6" class="text-right font-weight-bold">Due Balance:</td>
                                        <td id="discountedTotal" class="font-weight-bold">0.00</td>
                                        <td></td>
                                        <input type="text" hidden id="remainingBalance2" name='reaminign'>
                                    </tr>
                                    {{-- <tr>
                                        <td colspan="6" class="text-right font-weight-bold">Received Amount:</td>
                                        <td>
                                            <input type="number" id="receivedAmount" name="received_amount"
                                                class="form-control" placeholder="Enter Received Amount" min="0"
                                                value="0">
                                        </td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td colspan="6" class="text-right font-weight-bold">Payment Method:</td>
                                        <td>
                                            <select id="paymantMethord" name="payment_mathord" class="form-control"
                                                required>
                                                <option value="Hand Cash">Hand Cash</option>
                                                <option value="Bkash">Bkash</option>
                                                <option value="Nagod">Nagod</option>
                                            </select>
                                        </td>
                                        <td></td>
                                    </tr> --}}
                                    {{-- <tr>
                                        <td colspan="6" class="text-right font-weight-bold">Due Balance:</td>
                                        <td id="remainingBalance" class="font-weight-bold">0.00</td>
                                        <td></td>
                                    </tr> --}}
                                </tfoot>
                            </table>


                        </div>



                        <div class="form-section ">
                            <h4>Payment & Delivery Status :</h4>
                            <div class="form-row mt-3">

                                <div class="form-group col-md-6">
                                    <label for="biller">Delivery Status:</label>
                                    <select id="deliveryStatus" name="delivery_status" class="form-control" required>
                                        <option value="Pending">Pending</option>
                                        <option value="Confrim">Confrim</option>
                                        <option value="Pik-up">Pik-up</option>
                                        <option value="On The Way">On The Way</option>
                                        <option value="Delivered">Delivered</option>
                                        <option value="Cancel">Cancel</option>
                                    </select>
                                </div>
                            </div>
                        </div>


                        <button type="submit" class="btn btn-success btn-block">Submit Order</button>
                    </form>

                </div>

            </div>

            </td>
            </tr>

            </table>



        </div>

        </form>
        <div class="modal fade" id="addCustomerModel" tabindex="-1" role="dialog"
            aria-labelledby="addCustomerModelLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addCustomerModelLabel">Add Customer</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <form method="POST" id="addCustomerFOrm" action="{{ route('sale.sale.quiceAddCustomer') }}">
                        @csrf
                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="validationCustom01">Company Name *:</label>
                                        <input type="text" name="co_name" class="form-control"
                                            id="validationCustom01" placeholder="Company Name"
                                            value="{{ old('co_name') }}">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="validationCustom01">Customer Group Name *:</label>
                                        <select name="customergroup_id" class="form-control select2">
                                            <option value="0">Not Applicable</option>
                                            @foreach ($customerGroup as $data)
                                                <option value="{{ $data->id }}">{{ $data->name }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="validationCustom01">Contact Person:</label>
                                        <input type="text" name="name" class="form-control"
                                            id="validationCustom01" placeholder="Contact Person"
                                            value="{{ old('name') }}">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="validationCustom02">E-mail:</label>
                                        <input type="text" name="email" class="form-control"
                                            id="validationCustom02" placeholder="E-mail" value="{{ old('email') }}"
                                            required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="validationCustom01">Phone:</label>
                                        <input type="text" name="phone" class="form-control"
                                            id="validationCustom01" placeholder="Phone" value="{{ old('phone') }}"
                                            required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="validationCustom02">Address:</label>
                                        <input name="address" class="form-control" id="validationCustom02"
                                            placeholder="Address" value="{{ old('address') }}" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="validationCustom07">Bin:</label>
                                        <input name="bin" class="form-control" id="validationCustom07"
                                            placeholder="Bin" value="{{ old('bin') }}">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                            <button type="submit" class="btn btn-primary">Save Customer</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    </div>
    </div>
    <!-- /.col-->
    </div>

    <script>
        $(document).ready(function() {
            let productCounter = 1;

            const updateGrandTotal = () => {
                let grandTotal = 0;

                $("#productList tr").each(function() {
                    const rowTotal = parseFloat($(this).find("td:nth-child(7)")
                .text()); // Correct column index
                    if (!isNaN(rowTotal)) {
                        grandTotal += rowTotal;
                    }
                });

                const shippingCharge = parseFloat($("#shippingCharge").val()) || 0;
                grandTotal += shippingCharge;

                $("#grandTotal").text(grandTotal.toFixed(2));
                updateDiscountedTotal();
            };

            const updateDiscountedTotal = () => {
                const grandTotal = parseFloat($("#grandTotal").text());
                const discount = parseFloat($("#discount").val()) || 0;
                const discountedTotal = grandTotal - discount;

                $("#discountedTotal").text(discountedTotal > 0 ? discountedTotal.toFixed(2) : "0.00");
                updateRemainingBalance();
            };

            const updateRemainingBalance = () => {
                const discountedTotal = parseFloat($("#discountedTotal").text());
                const receivedAmount = parseFloat($("#receivedAmount").val()) || 0;
                const remainingBalance = discountedTotal - receivedAmount;

                $("#remainingBalance").text(remainingBalance.toFixed(2));
                $("#remainingBalance2").val(remainingBalance.toFixed(2));
            };

            $("#addProduct").click(function() {
                const productName = $("#productName").val().trim();
                const fabricSpecification = $("#fabricSpecification").val().trim();
                const productSpecification = $("#productSpecification").val().trim();
                const productPrice = parseFloat($("#productPrice").val());
                const productQty = parseInt($("#productQty").val());
                const fabric = $("#fabric option:selected").val();
                const fabricName = $("#fabric option:selected").data('name');

                if (!productName || isNaN(productPrice) || isNaN(productQty) || productQty <= 0 ||
                    productPrice <= 0) {
                    alert("Please enter valid product name, price, and quantity.");
                    return;
                }

                const totalPrice = productPrice * productQty;

                const row = `
            <tr data-product-id="${productCounter}">
                <td>${productCounter}</td>
                <td>${productName}</td>
                <td>${productSpecification}</td>
                <td>${fabricSpecification}</td>
                <td>${fabricName}</td>                
                <td>${productPrice.toFixed(2)}</td>
                <td>${productQty}</td>
                <td>${totalPrice.toFixed(2)}</td>
                <td>
                    <button type="button" class="btn btn-danger btn-sm remove-product">Remove</button>
                </td>
            </tr>
            <input type="hidden" name="products[${productCounter}][productName]" value="${productName}">
            <input type="hidden" name="products[${productCounter}][fabricSpecification]" value="${fabricSpecification}">
            <input type="hidden" name="products[${productCounter}][productSpecification]" value="${productSpecification}">
            <input type="hidden" name="products[${productCounter}][fabric]" value="${fabric}">
            <input type="hidden" name="products[${productCounter}][price]" value="${productPrice}">
            <input type="hidden" name="products[${productCounter}][quantity]" value="${productQty}">
            <input type="hidden" name="products[${productCounter}][totalPrice]" value="${totalPrice}">
        `;

                $("#productList").append(row);
                productCounter++;

                $("#productName, #fabricSpecification, #productSpecification, #productPrice, #productQty")
                    .val("");

                updateGrandTotal();
            });

            $(document).on("click", ".remove-product", function() {
                const row = $(this).closest("tr");
                const productId = row.data("product-id");

                row.remove();
                $(`input[name^="products[${productId}]"]`).remove(); // Remove hidden inputs

                productCounter = 1;
                $("#productList tr").each(function() {
                    $(this).find("td:first").text(productCounter);
                    productCounter++;
                });

                updateGrandTotal();
            });

            $("#discount, #receivedAmount, #shippingCharge").on("input", function() {
                updateGrandTotal();
            });
        });
    </script>

    <script type="text/javascript">
        $(document).ready(function() {
            // Supplier  Create 
            $('#addCustomerFOrm').on('submit', function(e) {
                e.preventDefault();
                const formData = $(this).serialize();
                $.ajax({
                    url: $(this).attr('action'),
                    method: 'POST',
                    data: formData,
                    success: function(response) {
                        if (response.success) {
                            $('#addCustomerModel').modal('hide');
                            $('select[name="ledger_id"]').append(
                                `<option value="${response.accounts.id}" selected>${response.accounts.account_name}</option>`
                            );
                        } else {
                            alert('Error adding Unit');
                        }
                    },
                    error: function(error) {
                        alert('An error occurred');
                    }
                });
                $("button[type='submit']").prop('disabled', false);
            });
        });

        $(document).ready(function() {
            $('#cty_size, #qty').on('input', function() {
                let ctyval = $('#cty_size').val();
                let qty = $('#qty').val();
                let gas_qty = ctyval * qty;
                $('#gas_qty').val(gas_qty);
            })

            var findqtyamount = function() {
                var ttlqty = 0;
                $.each($('.ttlqty'), function() {
                    qty = $(this).val();
                    qty = Number(qty);
                    ttlqty += qty;
                });
                $('.ttlqty').text(parseFloat(ttlqty).toFixed(2));
            };

            var findunitamount = function() {
                var ttlunitprice = 0;
                $.each($('.ttlunitprice'), function() {
                    unitprice = $(this).val();
                    unitprice = Number(unitprice);
                    ttlunitprice += unitprice;
                });
                $('.ttlunitprice').text(parseFloat(ttlunitprice).toFixed(2));
            };

            var findgrandtottal = function() {
                var grandtotal = 0;
                $.each($('.grandtotal'), function() {
                    total = $(this).val();
                    total = Number(total);
                    grandtotal += total;
                });
                $('.grandtotal').text(parseFloat(grandtotal).toFixed(2));
                var paymentType = $('input[name="payment_type"]:checked').val();
                if (paymentType == "Cash") {
                    $('#payment').val(parseFloat(grandtotal).toFixed(2));
                    paymentCalculation(parseFloat(grandtotal));
                }
            };


            $("#add_item").click(function() {

                // start check duplicate product  
                let seaschproduct = $('#productID option:selected')[0].getAttribute("value");
                let tbody = $('tbody').find(".new_item" + seaschproduct).length;
                let tbody2 = $('tbody').find("new_item" + seaschproduct);
                console.log(tbody);

                var purchasetypeval = $('.purchasetype').find('option:selected').val();
                var purchasetypetext = $('.purchasetype').find('option:selected').text();

                if (purchasetypeval == '' || purchasetypeval == null) {
                    alertMessage.error("Please Select Type.");
                    return false;
                }

                if (tbody > 0) {
                    alertMessage.error('This product already exist');
                    return;
                }
                // end check duplicate product

                // var supid = $('.supid').val();
                var catId = $('.catName').val();
                var catName = $(".catName").find('option:selected').attr('catName');


                var proId = $('.proName').val();
                var proName = $(".proName").find('option:selected').attr('proName');

                //            var unit_id = $('.unitName').val();
                //            var unitName = $(".unitName").find('option:selected').attr('unitName');

                var unit = $('.unit').val();
                var qty = $('.qty').val();
                var vat = parseFloat($('#vat').val()) || 0;

                var patmentType = $('input[name="payment_type"]:checked').val();
                // alert(patmentType);
                var customer_id = $('#customer_id').val();

                var unitprice = $('.unitprice').val();

                var total = $('.total').val();

                if (catId == '' || catId == null) {
                    alertMessage.error("Category can't be empty.");
                    return false;
                }
                if (proId == '' || proId == null) {
                    alertMessage.error("Product can't be empty.");

                    return false;
                }


                if (qty == '' || qty == null || qty == 0) {
                    alertMessage.error("Quantity can't be empty or zero.");

                    return false;
                } else {

                    if (customer_id === null) {
                        alertMessage.error("Please select a Customer.");
                        return false;
                    }

                    if (patmentType === undefined) {
                        alertMessage.error("Please select Payment Type.");
                        return false;
                    }


                    $("#show_item tbody").append('<tr class="new_item' + proId +
                        '">\n\
                                                                                                                                                                                                                                                                                            <td style="padding-left:15px;">' +
                        catName +
                        '<input type="hidden" name="catName[]" value="' +
                        catId +
                        '"></td>\n\
                                                                                                                                                                                                                                                                                            <td align="right">' +
                        proName +
                        '<input type="hidden" class="add_quantity" name="proName[]" value="' +
                        proId +
                        '"></td>\n\
                                                                                                                                                                                                                                                                                            <td align="right">' +
                        purchasetypetext +
                        '<input type="hidden" class="add_quantity" name="purchasetype[]" value="' +
                        purchasetypeval +
                        '"></td>\n\\n\<td align="right">' + qty +
                        '<input type="hidden" class="ttlqty" name="qty[]" value="' + qty +
                        '">                               </td>\n\\n\  <td align="right">' + vat +
                        '<input type="hidden" class="ttlqty" name="vat[]" value="' + vat +
                        '"></td>\n\\n\                                                                                                                                                          <td align="right">' +
                        unitprice +
                        '<input type="hidden" class="ttlunitprice unitparice" name="unitprice[]" value="' +
                        unitprice +
                        '"></td>\n\
                                                                                                                                                                                                                                                                                            <td align="right">' +
                        total +
                        '<input type="hidden" class="grandtotal" name="total[]" value="' +
                        total +
                        '"></td>\n\
                                                                                                                                                                                                                                                                                            \n\
                                                                                                                                                                                                                                                                                            \n\
                                                                                                                                                                                                                                                                                            <td><a del_id="' +
                        proId +
                        '" class="delete_item btn form-control btn-danger" href="javascript:;" title=""><i class="fa fa-times"></i></a></td></tr>'
                    );
                }

                $(".catName").val(null).trigger("change");
                $(".proName").val(null).trigger("change");
                $("#currentStock").val("");
                $("#qty").val("");
                $("#cty_size").val("");
                $("#gas_qty").val("");
                $(".unitprice").val("");
                $(".ttlamount").val("");


                findqtyamount();
                findunitamount();
                findgrandtottal();
                checkDepositAndCreditBalance();
            });

            $('#branch_id').on('change', function() {
                $(".catName").val(null).trigger("change");
                $(".proName").val(null).trigger("change");
            })

            $(document).on('click', '.delete_item', function() {
                // if (confirm("Are you sure?")) {
                //     var id = $(this).attr("del_id");
                //     $('.new_item' + id).remove();
                //     findqtyamount();
                //     findunitamount();
                //     findgrandtottal();
                //     checkDepositAndCreditBalance();
                // }

                let deleteitem = () => {
                    var id = $(this).attr("del_id");
                    $('.new_item' + id).remove();
                    findqtyamount();
                    findunitamount();
                    findgrandtottal();
                    checkDepositAndCreditBalance();
                }

                alertMessage.confirm('You want to remove this', deleteitem);

            });
        });



        function checkDepositAndCreditBalance() {

            var paymentType = $("#paymentType").val();

            if (paymentType == '') {
                paymentType = 'Cash';
            }

            console.log(paymentType);
            var customer_currentBalance = $("#customer_currentBalance").val();
            // var totalDue = document.getElementById("totalDue").innerText;

            var totalDue = $("#totalDue").text();
            var expireDatas = $("#expireData").val();


            var todaysDate = new Date().toISOString().slice(0, 10);

            if (expireDatas == '') {
                expireDatas = todaysDate;
            }
            var btn = document.getElementById('subMitButton');
            if ((paymentType == 'Deposit') && (parseFloat(customer_currentBalance) < parseFloat(totalDue))) {
                console.log('1');
                btn.disabled = true;
                // } else if (((paymentType == 'Credit') && (parseFloat(customer_currentBalance) < parseFloat(totalDue))) || (
                //     expireDatas < todaysDate)) {
                //     console.log('2');
                //     btn.disabled = true;
            } else if (paymentType == 'Cash') {
                console.log('3');
                btn.disabled = false;
            } else {
                console.log('4');
                btn.disabled = false;
            }

        }
    </script>
@endsection
