@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 Edit</h3>
                </div>
                <div class="card-body">

                    <form id="orderForm" action="{{ route('quick.sales.update', $order->id) }}" method="POST">
                        @csrf
                        @method('PUT')
                        @php
                            // Fetch necessary data for dropdowns
                            $ledgers = App\Models\ChartOfAccount::whereIn('id', [
                                getAccountByUniqueID(5)->id,
                                getAccountByUniqueID(16)->id,
                            ])->get();

                            $customerGroup = App\Models\CustomerGroup::all();
                            $branches = App\Models\Branch::all(); // Fetch branches for dropdown
                        @endphp

                        <div class="row">
                            <div class="form-group col-md-6">
                                <label for="date">Date:</label>
                                <input type="date" name="date" id="date" class="form-control"
                                    value="{{ old('date', $order->date) }}" required>
                                @error('date')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>

                            <div class="form-group col-md-6">
                                <label for="ledger_id">Customer *:</label>
                                <select class="form-control select2" name="ledger_id" id="ledger_id">
                                    <option selected disabled value="">--Select Ledger--</option>
                                    <x-account :setAccounts="$ledgers" :selectVal="$order->ledger_id" />
                                </select>
                                @error('ledger_id')
                                    <span class="error text-danger font-weight-bold">{{ $message }}</span>
                                @enderror

                            </div>

                            <div class="form-group col-md-6">
                                <label for="branch_id">Branch:</label>
                                <select name="branch_id" id="branch_id" class="form-control">
                                    <option value="">--Select Branch--</option>
                                    @foreach ($branches as $branch)
                                        <option value="{{ $branch->id }}"
                                            {{ old('branch_id', $order->branch_id) == $branch->id ? 'selected' : '' }}>
                                            {{ $branch->name }}
                                        </option>
                                    @endforeach
                                </select>
                                @error('branch_id')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </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>
                                <div class="form-group col-md-2">
                                    <label>&nbsp;</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>Price</th>
                                        <th>Quantity</th>
                                        <th>Total Price</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody id="productList">
                                    @if (!empty($order->products) && count($order->products) > 0)
                                        @foreach ($order->products as $key => $product)
                                        <input type="text" name="delete" hidden value={{$product->id}}>
                                            <tr>
                                                <td>{{ $key + 1 }}</td>
                                                <td>{{ $product->product_name }}</td>
                                                <td>{{ $product->productSpecification }}</td>
                                                <td>{{ $product->fabricSpecification }}</td>
                                                <td>{{ $product->price, 2 }}</td>
                                                <td>{{ $product->quantity }}</td>
                                                <td>{{ $product->price * $product->quantity, 2 }}</td>
                                                <td>
                                                    <button type="button"
                                                        class="btn btn-danger btn-sm remove-product">Remove</button>
                                                </td>

                                                <input type="hidden" name="productid[]" value="{{ $product->id }}">
                                                <input type="hidden" name="productName[]" value="{{ $product->product_name }}">
                                                <input type="hidden" name="existingProducts[]" value="{{ $product->id }}">
                                                <input type="hidden" name="fabricSpecification[]" value="{{ $product->fabricSpecification }}">
                                                <input type="hidden" name="productSpecification[]" value="{{ $product->productSpecification }}">
                                                <input type="hidden" name="price[]" value="{{ $product->price }}">
                                                <input type="hidden" name="quantity[]" value="{{ $product->quantity }}">
                                                <input type="hidden" name="totalPrice[]" value="{{ $product->price * $product->quantity }}">
                                            </tr>
                                        @endforeach
                                    @else
                                        <tr>
                                            <td colspan="8" class="text-center">No products added yet.</td>
                                        </tr>
                                    @endif
                                </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="{{ (int) $order->shipping_charge }}">
                                        </td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td colspan="6" class="text-right font-weight-bold">Grand Total:</td>
                                        <td id="grandTotal" class="font-weight-bold">{{ $order->total_amount }}</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="{{ (int) $order->discount }}">
                                        </td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td colspan="6" class="text-right font-weight-bold">Total Bill:</td>
                                        <td id="discountedTotal" class="font-weight-bold">{{ $order->discounted_total }}
                                        </td>
                                        <td></td>
                                    </tr>
                                    {{-- <tr>
                                <td>
                                    <select id="paymentMethod" name="payment_method" class="form-control" required>
                                        <option value="Hand Cash" {{ $order->payment_method == 'Hand Cash' ? 'selected' : '' }}>Hand Cash</option>
                                        <option value="Bkash" {{ $order->payment_method == 'Bkash' ? 'selected' : '' }}>Bkash</option>
                                        <option value="Nagod" {{ $order->payment_method == 'Nagod' ? 'selected' : '' }}>Nagod</option>
                                    </select>
                                </td>
                            </tr> --}}
                                    <tr>
                                        <td colspan="6" class="text-right font-weight-bold">Due Balance:</td>
                                        <td class="remainingBalance" class="font-weight-bold">
                                            {{ $order->remaining_balance }}</td>

                                        <input type="text" name="reaminign" hidden class="remainingBalance2">
                                    </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="date">Payment Status :</label>
                                    <select id="payment_status" name="payment_status" class="form-control" required>
                                        <option value="due" {{ $order->payment_status == 'due' ? 'selected' : '' }}>Due
                                        </option>
                                        <option value="partial"
                                            {{ $order->payment_status == 'partial' ? 'selected' : '' }}>Partial</option>
                                        <option value="paid" {{ $order->payment_status == 'paid' ? 'selected' : '' }}>
                                            Paid</option>
                                    </select>
                                </div> --}}
                                <div class="form-group col-md-6">
                                    <label for="biller">Delivery Status:</label>
                                    <select id="delivery_status" name="delivery_status" class="form-control" required>
                                        <option value="pending"
                                            {{ $order->delivery_status == 'pending' ? 'selected' : '' }}>Pending</option>
                                        <option value="Confrim"
                                            {{ $order->delivery_status == 'Confrim' ? 'selected' : '' }}>Confrim
                                        </option>
                                        <option value="Pik-up"
                                            {{ $order->delivery_status == 'Pik-up' ? 'selected' : '' }}>Pik-up
                                        </option>
                                        <option value="On The Way"
                                            {{ $order->delivery_status == 'On The Way' ? 'selected' : '' }}>On The Way
                                        </option>
                                        <option value="delivered"
                                            {{ $order->delivery_status == 'delivered' ? 'selected' : '' }}>Delivered
                                        </option>
                                        <option value="Cancel"
                                            {{ $order->delivery_status == 'Cancel' ? 'selected' : '' }}>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>
    </div>
    </div>
    <!-- /.col-->
    </div>

   
    <script>
        $(document).ready(function() {
            let productCounter = 1; // Initialize counter for serial number

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

                // Sum up total prices from the table rows
                $("#productList tr").each(function() {
                    const rowTotal = parseFloat($(this).find("td:nth-child(7)").text());
                    if (!isNaN(rowTotal)) {
                        grandTotal += rowTotal;
                    }
                });

                // Include shipping charge in the grand total
           
                const shippingCharge = parseFloat($("#shippingCharge").val()) || 0;
                grandTotal += shippingCharge;

                // Update the grand total display
                $("#grandTotal").text(grandTotal.toFixed(2));

                // Update discounted total
                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 productSpecification = $("#productSpecification").val().trim();
                const fabricSpecification = $("#fabricSpecification").val().trim();
                const productPrice = parseFloat($("#productPrice").val());
                const productQty = parseInt($("#productQty").val());
                const productId = $("#productId")
                    .val(); // Assuming you have a hidden field or dropdown for product ID

                if (!productName || !productSpecification || !fabricSpecification || isNaN(productPrice) ||
                    isNaN(productQty) || productQty <= 0 || productPrice <= 0) {
                    alert("Please enter valid product details.");
                    return;
                }

                const totalPrice = productPrice * productQty;

                const row = `
        <tr>
            <td>${productCounter}</td>
            <td>${productName}</td>
            <td>${productSpecification}</td>
            <td>${fabricSpecification}</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="productid[]" value="${productId}">
        <input type="hidden" name="productName[]" value="${productName}">
        <input type="hidden" name="productSpecification[]" value="${productSpecification}">
        <input type="hidden" name="fabricSpecification[]" value="${fabricSpecification}">
        <input type="hidden" name="price[]" value="${productPrice}">
        <input type="hidden" name="quantity[]" value="${productQty}">
        <input type="hidden" name="totalPrice[]" value="${totalPrice}">
    `;

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

                // Reset input fields
                $("#productName, #productSpecification, #fabricSpecification, #productPrice, #productQty, #productId")
                    .val("");

                updateGrandTotal();
            });


            $(document).on("click", ".remove-product", function() {
                $(this).closest("tr").remove(); // Remove row

                // Reset product counter & update serial numbers
                productCounter = 1;
                $("#productList tr").each(function() {
                    $(this).find("td:first").text(productCounter);
                    productCounter++;
                });

                updateGrandTotal();
            });

            // Listen for input changes
            $("#discount, #receivedAmount, #shippingCharge").on("input", function() {
                updateGrandTotal();
            });

            updateGrandTotal(); // Ensure grand total updates on page load
        });
    </script>


@endsection
