@extends('layouts.master')
@section('styles')
    <style>
        .search-box {
            position: relative;
            display: flex;
        }

        #clear-search {
            position: absolute;
            right: 0;
            top: 0;
            border: none;
            background: none;
            cursor: pointer;
            font-size: 19px;
            color: #6c757d;
        }

        #clear-search:hover {
            color: #dc3545; /* Change color on hover */
        }
    </style>
@endsection
@section('content')
    <div class="card">
        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between border-bottom mb-3">
            <h6 class="m-0 table__top__txt">Create Sale</h6>
            <div class="m-0 float-right">
                @can('inventory.sales.view')
                    <a href="{{ route('sales.index') }}" class="btn btn-sm btn-light-blue">View All</a>
                @endcan
            </div>
        </div>
        <div class="card-body">
            @if ($errors->any())
                <div class="alert alert-danger m-3">
                    <ul class="m-0">
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <div class="row">
                <div class="col-md-12">
                    <form action="{{ route('sales.store') }}" method="POST">
                        @csrf

                        <div class="row mb-3">
                            <div class="col-md-4">
                                <div class="form-group mb-0">
                                    @component('components.search_student', [
                                        'student_name' => $student_name ?? '',
                                        'student_id_no' => request()->student_id_no ?? '',
                                        'required' => 'required',
                                    ])
                                    @endcomponent
                                </div>
                            </div>

                            <div class="col-md-4">
                                <div class="form-group mb-0 float-left d-block" style="width: 80%;margin-right: 5px;">

                                    <div class="search-box">
                                        <select id="product-search" class="form-control form-control-sm ">
                                            <option value="">-Select Product--</option>
                                            @foreach($products as $product)
                                                <option value="{{$product->name}}">{{$product->name}}</option>
                                            @endforeach
                                        </select>
                                    </div>

                                    {{--<div class="search-box">
                                        <input type="text" id="product-search" class="form-control form-control-sm" placeholder="Search for a product..." autocomplete="off">
                                        <button type="button" id="clear-search"  style="display: none;"><i class="fas fa-times"></i></button>
                                    </div>--}}

                                    <input type="hidden" id="product-search-value" value="">
                                </div>
                                <button type="button" id="add-more" class="btn btn-sm btn-light-blue float-left"
                                        style="padding-top: 5px;"><i class="fas fa-plus"></i></button>
                            </div>
                        </div>

                        <div class="table-responsive mb-3">
                            <div id="sales-details">
                                <table class="table">
                                    <thead class="thead-light">
                                    <tr>
                                        <th>Action</th>
                                        <th>Product</th>
                                        <th>Quantity</th>
                                        <th>Price</th>
                                        <th>Discount Amt.</th>
                                        <th>Discount %</th>
                                        <th>Total</th>
                                    </tr>
                                    </thead>
                                    <tbody>

                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="text-right mt-3">
                            <div class="sale__summary">
                                <div class="my-4 d-flex flex-column align-items-end">
                                    <div class="d-flex justify-content-between w-25 sum__line">
                                        <span class="w-50">Total Amount:</span>
                                        <span id="total-amount">0.00</span>
                                        <input type="hidden" name="total_amount" id="total-amount-input" value="">
                                    </div>
                                    <div class="d-flex justify-content-between w-25 sum__line">
                                        <span class="w-50">Total Discount:</span>
                                        <span id="total-discount">0.00</span>
                                        <input type="hidden" name="total_discount" id="total-discount-input" value="">
                                    </div>
                                    <div class="d-flex justify-content-between w-25 sum__line">
                                        <span class="w-50">Grand Total:</span>
                                        <span id="grand-total">0.00</span>
                                        <input type="hidden" name="grand_total" id="grand-total-input" value="">
                                    </div>
                                </div>
                            </div>
                            <button type="submit" class="btn btn-submit">Submit & Print</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

@endsection

@section('scripts')
    <script>
        $(document).ready(function () {

            const $searchInput = $('#product-search');
            const $clearButton = $('#clear-search');

            // Show/hide clear button based on input value
            $searchInput.on('input', function () {
                if ($(this).val().length > 0) {
                    $clearButton.show();
                } else {
                    $clearButton.hide();
                }
            });

            // Clear the input when the button is clicked
            $clearButton.on('click', function () {
                $searchInput.val('');
                $clearButton.hide();
                $searchInput.focus(); // Optionally refocus on the input
            });


            const $salesDetails = $('#sales-details');
            const $totalAmountEl = $('#total-amount');
            const $totalDiscountEl = $('#total-discount');
            const $grandTotalEl = $('#grand-total');

            const $totalAmountInput = $('#total-amount-input');
            const $totalDiscountInput = $('#total-discount-input');
            const $grandTotalInput = $('#grand-total-input');

            // Add new row for product details
            $('#add-more').on('click', function () {


                const query = $("#product-search").val();

                // Check if the item already exists in the table (based on product name)
                const tableBody = document.querySelector("#sales-details tbody");
                const rows = tableBody.getElementsByTagName("tr");
                for (let i = 0; i < rows.length; i++) {
                    const rowItemName = rows[i].querySelector('input[name="product_name[]"]').value;
                    if (rowItemName.toLowerCase() === query.toLowerCase()) {
                        alert("This item has already been added.");
                        return;  // Prevent adding the item
                    }
                }

                if (query.length > 0) {
                    let button = $(this);
                    button.prop('disabled', true); // Disable button
                    $.ajax({
                        url: "{{ route('product.search') }}",
                        method: 'GET',
                        data: {query: query},
                        success: function (data) {
                            let product_id = data.id;
                            let product_name = data.name;
                            let sale_price = data.sale_price;
                            // Create a new row with product details

                            if (product_id != null) {
                                const newRow = `
                            <tr>
                                <td>
                                    <button type="button" class="remove-row btn btn-sm btn-danger"><i class="fa fa-trash"></i></button>
                                </td>
                                <td>
                                    <input type="text" readonly id="product-name" data-item-name="${product_name}" value="${product_name}" name="product_name[]" class="form-control form-control-sm" placeholder="Product Name" autocomplete="off">
                                    <input type="hidden" name="product_id[]" value="${product_id}" >
                                </td>
                                <td>
                                    <input type="number" name="quantity[]" class="quantity form-control form-control-sm" placeholder="Qty" min="1" required>
                                </td>
                                <td>
                                    <input type="number" name="price[]" value="${sale_price}" class="price form-control form-control-sm" placeholder="Price" step="0.01">
                                </td>
                                <td>
                                    <input type="number" name="discount_amount[]" class="discount_amount form-control form-control-sm" placeholder="Disc Amt" value="0" step="0.01">
                                </td>
                                <td>
                                    <input type="number" name="discount_percentage[]" class="discount_percentage form-control form-control-sm" placeholder="Disc %" value="0" step="0.01">
                                </td>
                                <td>
                                    <input type="text" class="total form-control form-control-sm" name="total[]" placeholder="Total" readonly>
                                </td>
                            </tr>
                        `;
                                $salesDetails.find('tbody').append(newRow);
                                updateEventListeners();
                                $("#product-search").val('');
                            } else {
                                alert("Select valid product")
                            }
                        },
                        complete: function () {
                            button.prop('disabled', false); // Re-enable button after request completes
                        },
                        error: function () {
                            console.error('Error fetching search results.');
                        }
                    });
                }
            });

            // Update total and grand total calculations
            function updateTotal($row) {
                const quantity = parseFloat($row.find('.quantity').val()) || 0;
                const price = parseFloat($row.find('.price').val()) || 0;
                const discountAmount = parseFloat($row.find('.discount_amount').val()) || 0;
                const discountPercentage = parseFloat($row.find('.discount_percentage').val()) || 0;

                let totalAmount = quantity * price; // Total before discounts
                let discountValue = 0;
                let total = totalAmount; // Initialize total as totalAmount

                if (discountPercentage > 0) {
                    discountValue = totalAmount * (discountPercentage / 100); // Calculate percentage-based discount
                    total -= discountValue;
                } else {
                    discountValue = discountAmount; // Fixed discount
                    total -= discountAmount;
                }

                // Update total and discount fields
                $row.find('.total').val(total.toFixed(2));
                $row.find('.discount_value').val(discountValue.toFixed(2)); // Add this if you want to show the discount in the row

                // Call to update the grand totals
                updateGrandTotal();
            }

            function updateGrandTotal() {
                let grandTotal = 0;      // After discounts
                let totalDiscount = 0;   // Total discounts
                let totalAmount = 0;     // Total amount before discounts

                $('#sales-details tbody tr').each(function () {
                    const quantity = parseFloat($(this).find('.quantity').val()) || 0;
                    const price = parseFloat($(this).find('.price').val()) || 0;
                    const discountAmount = parseFloat($(this).find('.discount_amount').val()) || 0;
                    const discountPercentage = parseFloat($(this).find('.discount_percentage').val()) || 0;

                    let rowTotalAmount = quantity * price; // Amount before discounts
                    let rowDiscount = 0;

                    if (discountPercentage > 0) {
                        rowDiscount = rowTotalAmount * (discountPercentage / 100);
                    } else {
                        rowDiscount = discountAmount;
                    }

                    totalAmount += rowTotalAmount; // Accumulate total amount before discounts
                    totalDiscount += rowDiscount; // Accumulate total discount
                    grandTotal += rowTotalAmount - rowDiscount; // Calculate grand total
                });

                // Update the respective elements
                $totalAmountEl.text(totalAmount.toFixed(2)); // Update total amount
                $totalDiscountEl.text(totalDiscount.toFixed(2)); // Update total discount
                $grandTotalEl.text(grandTotal.toFixed(2)); // Update grand total

                $totalAmountInput.val(totalAmount.toFixed(2)); // Update total amount in input
                $totalDiscountInput.val(totalDiscount.toFixed(2)); // Update total discount in input
                $grandTotalInput.val(grandTotal.toFixed(2)); // Update grand total in input

            }

            // Remove row
            function removeRow() {
                $(this).closest('tr').remove();
                updateGrandTotal();
            }

            // Attach event listeners to elements
            function updateEventListeners() {
                $('.quantity, .discount_amount, .discount_percentage').off('input').on('input', function () {
                    const $row = $(this).closest('tr');
                    updateTotal($row);
                });
                $('.remove-row').off('click').on('click', removeRow);
            }

            // Initialize listeners for existing elements
            updateEventListeners();
        });
    </script>
    <script>
        $(document).ready(function () {
            $("#product-search").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "{{ route('products.search') }}", // Adjust this route as necessary
                        data: {
                            query: request.term
                        },
                        success: function (data) {
                            response($.map(data, function (product) {
                                return {
                                    label: product.name, // Assuming 'name' is a field in your product model
                                    value: product.id // Assuming 'id' is the product identifier
                                };
                            }));
                        }
                    });
                },
                minLength: 3,
                select: function (event, ui) {
                    $('#product-search').val(ui.item.label);
                    $('#product-search-value').val(ui.item.value);
                    return false; // Prevent default select behavior
                },
                focus: function (event, ui) {
                    $('#product-search').val(ui.item.label);
                    return false;
                }
            });

            $("#product-search").on('input', function () {
                if ($(this).val() === '') {
                    $('#product-search-value').val('');
                }
            });
        });
    </script>
@endsection
