
@extends($master)

@section('title', 'Create Invoice')

@section('body')
    <!-- PAGE-HEADER -->
    <div class="page-header">
        <div>
            <h1 class="page-title">Create Invoice</h1>
        </div>
        <div class="ms-auto pageheader-btn">
            <ol class="breadcrumb">
                <li class="breadcrumb-item">Apps</li>
                <li class="breadcrumb-item"><a href="javascript:void(0);">Invoices</a></li>
                <li class="breadcrumb-item active" aria-current="page">Create Invoice</li>
            </ol>
        </div>
    </div>
    <!-- PAGE-HEADER END -->

    <!--ROW OPENED-->
    <div class="row">
        <div class="col-lg-12 col-md-12">
            <div class="card">
                <div class="card-header border-bottom">
                    <h4 class="mb-0">Invoice</h4>
                </div>
                <form action="{{ route('invoices.store') }}" method="post">
                    @csrf
{{--                    <div class="row p-5 border-bottom">--}}
{{--                        <div class="col-sm-12 col-md col-xl">--}}
{{--                            <div class="form-group">--}}
{{--                                <label class="form-label text-muted">Name</label>--}}
{{--                                <input type="text" class="form-control" id="clientName" name="name" value="">--}}
{{--                            </div>--}}
{{--                        </div>--}}
{{--                        <div class="col-sm-12 col-md col-xl">--}}
{{--                            <div class="form-group">--}}
{{--                                <label class="form-label text-muted">Mobile: +880</label>--}}
{{--                                <input type="number" class="form-control" id="clientMobile" name="mobile" value="">--}}
{{--                            </div>--}}
{{--                        </div>--}}
{{--                    </div>--}}

                    <div class="row p-5 border-bottom">
                        <div class="col-sm-12 col-md col-xl">
                            <div class="form-group">
                                <label class="form-label text-muted">Name</label>
                                <ul>
                                    <li class="select-client">
                                        <input type="text" class="form-control" id="clientName" name="name" value="">
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="col-sm-12 col-md col-xl">
                            <div class="form-group">
                                <label class="form-label text-muted">Mobile</label>
                                <ul>
                                    <li class="select-client">
                                        <input type="number" class="form-control" id="clientMobile" name="mobile" value="">
                                        <div id="mobileSuggestions" class="list-group"></div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="col-sm-12 col-md col-xl">
                            <div class="form-group">
                                <label class="form-label text-muted">Gender</label>
                                <ul>
                                    <li class="select-client">
                                        <select id="" class="form-control select2-client-search" name="sex" required>
                                            <option>---Select Gender---</option>
                                            <option value="Male">Male</option>
                                            <option value="Female">Female</option>
                                            <option value="Others">Others</option>
                                        </select>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="col-sm-12 col-md col-xl">
                            <div class="form-group">
                                <label class="form-label text-muted">Ref. Doctor</label>
                                <ul>
                                    <li class="select-client">
                                        <input type="text" class="form-control" id="" name="dr" value="">
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <div class="col-sm-12 col-md col-xl">
                            <div class="form-group">
                                <label class="form-label text-muted">Age</label>
                                <ul>
                                    <li class="select-client">
                                        <input type="text" class="form-control" id="" name="age" value="">
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
                    <script>
                        // Listen for input in the mobile field
                        $('#clientMobile').on('input', function() {
                            let mobile = $(this).val();
                            if (mobile.length >= 3) {
                                // Perform AJAX request to fetch suggestions
                                $.ajax({
                                    url: '{{ route("client.search") }}', // Search route
                                    method: 'GET',
                                    data: { mobile: mobile },
                                    success: function(data) {
                                        console.log(data); // Check if data is returned
                                        let suggestions = '';
                                        if (data.length > 0) {
                                            data.forEach(client => {
                                                suggestions += `<a href="#" class="list-group-item list-group-item-action" onclick="selectClient(${client.id}, '${client.name}', '${client.mobile}')">${client.mobile} - ${client.name}</a>`;
                                            });
                                            $('#mobileSuggestions').html(suggestions).show();
                                        } else {
                                            $('#mobileSuggestions').html('<p class="text-muted">No results found</p>').show();
                                        }
                                    },
                                    error: function(xhr, status, error) {
                                        console.log(xhr.responseText); // Log any errors from the server
                                    }
                                });
                            } else {
                                $('#mobileSuggestions').hide();
                            }
                        });

                        // Function to select client and populate the fields
                        function selectClient(id, name, mobile) {
                            $('#clientName').val(name);
                            $('#clientMobile').val(mobile);
                            $('#mobileSuggestions').hide();
                        }
                    </script>



                    <div class="row px-5 border-bottom">
                        <div class="col-xl-12">
                            <div class="form-group">
                                <label class="form-label text-muted">Tests:</label>
                                <select id="testSelect" class="form-control select2-client-search" name="test_id">
                                    <option value="">--Select Test Name--</option>
                                    @foreach($tests as $test)
                                        <option value="{{ $test->id }}" data-amount="{{ $test->price }}">{{ $test->name }}</option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="table-responsive product-description-each mb-3">
                                <table class="invoice-product-table">
                                    <thead>
                                    <tr>
                                        <th>SL</th>
                                        <th>Test Name</th>
                                        <th>Amount</th>
                                        <th>Actions</th>
                                    </tr>
                                    </thead>
                                    <tbody id="testTableBody" class="border">
                                    <!-- Rows will be appended here -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div class="row pt-0 pb-5 px-5 border-bottom">
                        <div class="col-xl-12">
                            <div class="table-responsive invoice-bottom-table-container">
                                <table class="table ms-auto invoice-table-bottom w-50 text-end">
                                    <tbody>
                                    <tr>
                                        <td colspan="3" class="border-top-0">Sub Total</td>
                                        <td class="border-top-0" id="subTotal">0.00</td>
                                    </tr>
                                    <tr>
                                        <td>Discount</td>
                                        <td class="w-30">
                                            <input type="number" class="form-control text-end" name="discount" id="discount" value="" min="0">
                                        </td>
                                        <td id="discountAmount">0.00</td>
                                    </tr>
                                    <tr class="bg-primary-transparent text-primary-dark fw-bold fs-15">
                                        <td colspan="3">Total</td>
                                        <td id="totalAmount">0.00</td>
                                    </tr>
                                    <tr>
                                        <td>Amount Received</td>
                                        <td class="w-30">
                                            <input type="number" class="form-control text-end" name="received" id="received" value="0" min="0">
                                        </td>
                                        <td id="receivedAmount">0.00</td> <!-- Updated ID to track the received amount -->
                                    </tr>
                                    <tr class="bg-primary-transparent text-primary-dark fw-bold fs-15">
                                        <td colspan="3">Amount Due</td>
                                        <td id="amountDue">0.00</td> <!-- Updated ID for Amount Due -->
                                    </tr>

                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                    <div class="row p-5">
                        <div class="btn-list text-end">
                            <button class="btn btn-primary me-sm-0 me-2" onclick="saveInvoice()">Save</button>
                        </div>
                    </div>

                    <!-- Hidden Fields for Subtotal, Discount, and Total -->
                    <input type="hidden" name="subtotal" id="hiddenSubTotal">
                    <input type="hidden" name="discount" id="hiddenDiscount">
                    <input type="hidden" name="total" id="hiddenTotal">
                </form>
            </div>
        </div>
    </div>
    <!--ROW CLOSED-->

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <script>
        $(document).ready(function() {
            let testCount = 0;

            $('#testSelect').on('change', function() {
                const selectedOption = $(this).find('option:selected');
                const testId = selectedOption.val();
                const testName = selectedOption.text();
                const testAmount = selectedOption.data('amount');

                if (testId) {
                    testCount++;
                    const newRow = `
                <tr class="dashed-border-bottom" data-id="${testId}">
                    <td>${testCount}</td>
                    <td>
                        <input type="text" class="form-control" name="test_names[]" value="${testName}" readonly>
                        <input type="hidden" name="test_ids[]" value="${testId}">
                    </td>
                    <td>
                        <input type="text" class="form-control" name="test_amounts[]" value="${testAmount}" readonly>
                    </td>
                    <td>
                        <button type="button" class="btn btn-danger remove-row-btn">Remove</button>
                    </td>
                </tr>
            `;
                    $('#testTableBody').append(newRow);
                    calculateTotals();
                }
            });

            $(document).on('click', '.remove-row-btn', function() {
                $(this).closest('tr').remove();
                calculateTotals();
            });

            $('#discount, #received').on('input', calculateTotals);

            function calculateTotals() {
                let subTotal = 0;
                const discount = parseFloat($('#discount').val()) || 0;
                const received = parseFloat($('#received').val()) || 0;

                $('#testTableBody tr').each(function() {
                    const amount = parseFloat($(this).find('input[name="test_amounts[]"]').val()) || 0;
                    subTotal += amount;
                });

                const discountAmount = (subTotal * discount) / 100;
                const totalAmount = subTotal - discountAmount;
                const amountDue = totalAmount - received;

                $('#subTotal').text(subTotal.toFixed(2));
                $('#discountAmount').text(discountAmount.toFixed(2));
                $('#totalAmount').text(totalAmount.toFixed(2));
                $('#receivedAmount').text(received.toFixed(2));
                $('#amountDue').text(amountDue.toFixed(2));
            }

            $('form').on('submit', function() {
                $('#hiddenSubTotal').val($('#subTotal').text());
                $('#hiddenDiscount').val($('#discount').val());
                $('#hiddenTotal').val($('#totalAmount').text());
            });
        });

    </script>
{{--    <script>--}}
{{--        let testCount = 0;--}}

{{--        document.getElementById('testSelect').addEventListener('change', function() {--}}
{{--            let selectedOption = this.options[this.selectedIndex];--}}
{{--            let testId = selectedOption.value;--}}
{{--            let testName = selectedOption.text;--}}
{{--            let testAmount = selectedOption.getAttribute('data-amount');--}}

{{--            if (testId) {--}}
{{--                testCount++;--}}
{{--                let newRow = `--}}
{{--                <tr class="dashed-border-bottom" data-id="${testId}">--}}
{{--                    <td>${testCount}</td>--}}
{{--                    <td>--}}
{{--                        <input type="text" class="form-control" name="test_names[]" value="${testName}" readonly>--}}
{{--                        <input type="hidden" name="test_ids[]" value="${testId}">--}}
{{--                    </td>--}}
{{--                    <td>--}}
{{--                        <input type="text" class="form-control" name="test_amounts[]" value="${testAmount}" readonly>--}}
{{--                    </td>--}}
{{--                    <td>--}}
{{--                        <button type="button" class="btn btn-danger remove-row-btn">Remove</button>--}}
{{--                    </td>--}}
{{--                </tr>--}}
{{--            `;--}}
{{--                document.getElementById('testTableBody').insertAdjacentHTML('beforeend', newRow);--}}
{{--                calculateTotals(); // Trigger total calculation when adding a new test--}}
{{--            }--}}
{{--        });--}}

{{--        document.addEventListener('click', function(e) {--}}
{{--            if (e.target.classList.contains('remove-row-btn')) {--}}
{{--                e.target.closest('tr').remove();--}}
{{--                calculateTotals(); // Update total after removing a test--}}
{{--            }--}}
{{--        });--}}

{{--        function calculateTotals() {--}}
{{--            let subTotal = 0;--}}
{{--            let discount = parseFloat(document.getElementById('discount').value) || 0;--}}
{{--            let received = parseFloat(document.querySelector('input[name="received"]').value) || 0;--}}

{{--            // Loop through the table rows to calculate the subtotal--}}
{{--            document.querySelectorAll('#testTableBody tr').forEach(row => {--}}
{{--                let amount = parseFloat(row.querySelector('input[name="test_amounts[]"]').value) || 0;--}}
{{--                subTotal += amount;--}}
{{--            });--}}

{{--            // Calculate discount amount and total--}}
{{--            let discountAmount = (subTotal * discount) / 100;--}}
{{--            let totalAmount = subTotal - discountAmount;--}}

{{--            // Calculate the amount due (Total - Received)--}}
{{--            let amountDue = totalAmount - received;--}}

{{--            // Update the displayed values--}}
{{--            document.getElementById('subTotal').textContent = subTotal.toFixed(2);--}}
{{--            document.getElementById('discountAmount').textContent = discountAmount.toFixed(2);--}}
{{--            document.getElementById('totalAmount').textContent = totalAmount.toFixed(2);--}}
{{--            document.querySelector('input[name="received"]').nextElementSibling.textContent = received.toFixed(2); // Updates the "Amount Received" display next to the input field--}}
{{--            document.querySelector('td.bg-primary-transparent').nextElementSibling.textContent = amountDue.toFixed(2); // Updates "Amount Due" display--}}
{{--        }--}}

{{--        // Trigger calculation on discount and received change--}}
{{--        document.getElementById('discount').addEventListener('input', calculateTotals);--}}
{{--        document.querySelector('input[name="received"]').addEventListener('input', calculateTotals);--}}

{{--        // Trigger calculation when a new test is added or removed--}}
{{--        document.addEventListener('change', function(e) {--}}
{{--            if (e.target.closest('select') || e.target.classList.contains('remove-row-btn')) {--}}
{{--                calculateTotals();--}}
{{--            }--}}
{{--        });--}}


{{--        // function calculateTotals() {--}}
{{--        //     let subTotal = 0;--}}
{{--        //     let discount = parseFloat(document.getElementById('discount').value) || 0;--}}
{{--        //--}}
{{--        //     // Loop through the table rows to calculate the subtotal--}}
{{--        //     document.querySelectorAll('#testTableBody tr').forEach(row => {--}}
{{--        //         let amount = parseFloat(row.querySelector('input[name="test_amounts[]"]').value) || 0;--}}
{{--        //         subTotal += amount;--}}
{{--        //     });--}}
{{--        //--}}
{{--        //     // Calculate discount amount and total--}}
{{--        //     let discountAmount = (subTotal * discount) / 100;--}}
{{--        //     let totalAmount = subTotal - discountAmount;--}}
{{--        //--}}
{{--        //     // Update the displayed values--}}
{{--        //     document.getElementById('subTotal').textContent = subTotal.toFixed(2);--}}
{{--        //     document.getElementById('discountAmount').textContent = discountAmount.toFixed(2);--}}
{{--        //     document.getElementById('totalAmount').textContent = totalAmount.toFixed(2);--}}
{{--        // }--}}

{{--        // Trigger calculation on discount change--}}
{{--        document.getElementById('discount').addEventListener('input', calculateTotals);--}}

{{--        function saveInvoice() {--}}
{{--            document.getElementById('hiddenSubTotal').value = document.getElementById('subTotal').textContent;--}}
{{--            document.getElementById('hiddenDiscount').value = document.getElementById('discount').value;--}}
{{--            document.getElementById('hiddenTotal').value = document.getElementById('totalAmount').textContent;--}}
{{--        }--}}
{{--    </script>--}}

@endsection
