@extends('layouts.layoutapp')

@section('content')
    <div class="row">
        <div class="col-12">
            <div class="card me-2">
                <div class="card-header pb-0">
                    <div class="d-flex flex-row justify-content-between">
                        <div>
                            <h5 class="mb-0">Add Quote</h5>
                        </div>
                    </div>
                </div>

                <form action="{{ route('quotes-store') }}" method="POST">
                    @csrf
                    <div class="card-body">
                        <div class="row">
                            <div class="col-lg-3 mb-3">
                                <label for="client_id" class="form-label">Client Name:</label>
                                <input type="text" name="client_name" id="client_id" class="form-control"
                                    value="{{ old('client_id') }}">
                                <span class="text-danger" id="client_name_error"></span>
                                @error('client_id')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>

                            <div class="col-lg-3 mb-3">
                                <label for="client_num" class="form-label">Client Number:</label>
                                <div id="client_select">
                                    <select name="client_num" id="client_num_select" class="select2 form-select" multiple
                                        required>
                                        @forelse ($clients as $data)
                                            <option value="{{ $data->user->phone }}">{{ $data->user->phone }}</option>
                                        @empty
                                            <option>No Client found</option>
                                        @endforelse
                                    </select>
                                </div>
                                @error('client_num')
                                    <span class="text-danger">{{ $message }}</span>
                                @enderror
                            </div>
                            <div class="col-lg-3 mb-3">
                                <label for="quote_id" class="form-label">Quotes Id:</label>
                                <input type="text" id="quote_id" name="quote_id" class="form-control" value="" readonly
                                    required>
                            </div>
                            <div class="col-lg-3 mb-3">
                                <label for="quote_date" class="form-label">Quotes Date:</label>
                                <input type="date" id="quote_date" name="quote_date" class="form-control" required>
                            </div>
                            <div class="col-lg-3 mb-3">
                                <label for="due_date" class="form-label">Due Date:</label>
                                <input type="date" id="due_date" name="due_date" class="form-control" required>
                            </div>
                            <div class="col-lg-3 mb-3">
                                <label for="status" class="form-label">Status</label>
                                <select name="status" id="status" class="form-select" required>
                                    <option value="1" selected>Draft</option>
                                </select>
                            </div>
                        </div>
                        <hr>
                        <div>
                            <h5>Product Details:</h5>
                            <div class="row align-items-center">
                                <div class="col-lg-4">
                                    <button type="button" id="add-row" class="btn btn-primary">
                                        <i class="fas fa-plus"></i> Add Row
                                    </button>
                                </div>
                            </div>

                            <div class="table-responsive">
                                <table class="table table-bordered table-striped text-sm" id="products-table">
                                    <thead class="thead-dark">
                                        <tr>
                                            <th>#</th>
                                            <th>Product</th>
                                            <th>Avl. Qty</th>
                                            <th>Qty</th>
                                            <th>Unit Price</th>
                                            <th>Amount</th>
                                            <th></th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Rows will be added dynamically -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <div class="row mt-5">
                            <div class="col-lg-6 mb-3 d-flex">
                                <div class="col-lg-6">
                                    <label for="discount_type" class="form-label">Discount type:</label>
                                    <select name="discount_type" id="discount_type" class="form-select" disabled>
                                        <option value="">Select discount type</option>
                                        @foreach ($discount_types as $type)
                                            <option value="{{ $type->id }}">{{ $type->type }}</option>
                                        @endforeach
                                    </select>
                                </div>
                                <div class="col-lg-6">
                                    <label for="discount" class="form-label">Discount:</label>
                                    <input type="number" id="discount" name="discount" class="form-control" min="0"
                                        step="0.01" disabled>
                                </div>
                            </div>
                            <div class="col-lg-5 mb-3">
                                <div class="card shadow-lg">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between pl-5">
                                            <span>Sub Total:</span>
                                            <span id="sub-total">0 ₹</span>
                                        </div>
                                        <div class="d-flex justify-content-between pl-5">
                                            <span>Discount:</span>
                                            <span id="discount-amt">0 ₹</span>
                                        </div>
                                        <div class="d-flex justify-content-between pl-5">
                                            <span>Total:</span>
                                            <span id="total-amt">0 ₹</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <hr>
                        <div>
                            <button type="button" id="toggle-notes" class="btn btn-primary">
                                <i class="fas fa-plus"></i> Add Note & Term
                            </button>
                            <div id="notes-terms" style="display: none;">
                                <div class="row mt-3">
                                    <div class="col-lg-6">
                                        <label for="note" class="form-label">Note:</label>
                                        <textarea class="form-control" name="note" id="note"></textarea>
                                    </div>
                                    <div class="col-lg-6">
                                        <label for="term" class="form-label">Term:</label>
                                        <textarea class="form-control" name="term" id="term"></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" id="hidden-sub-total" name="sub_total" value="0">
                        <input type="hidden" id="hidden-discount-amt" name="discount_amount" value="0">
                        <input type="hidden" id="hidden-total-amt" name="total_amount" value="0">
                        <div class="modal-footer mt-4">
                            <button type="submit" id="submit" class="btn btn-primary">Save</button>
                            <a href="{{ route('quotes-index') }}" class="btn btn-secondary">Cancel</a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
@endsection

@push('scripts')
    <script>
        $(document).ready(function () {
            let rowCount = 0;

            // Add row button
            $('#add-row').click(function () {
                rowCount++;
                const row =
                    `
                                                <tr class="product-row">
                                                <td>${rowCount}</td>
                                                <td>
                                                <select name="products[${rowCount}][id]" class="form-select product-select" required>
                                                <option value="">Select Product</option>
                                                @foreach ($products as $product)
                                                    <option value="{{ $product->id }}" 
                                                    data-available="{{ $product->qty }}" 
                                                    data-amount=0 
                                                    data-price="{{ $product->unit_price }}">
                                                    {{ $product->code }}-{{ $product->branch->native_name_flag == 'A' ? ($product->native_name ?? $product->name) : $product->name }}
                                                    </option>
                                                @endforeach
                                                </select>
                                    <div class="duplicate-warning-container"></div>
                                                </td>
                                                <td>
                                                <input type="text" class="form-control available-qty" readonly>
                                                </td>
                                                <td>
                                                <input type="number" name="products[${rowCount}][qty]" 
                                                class="form-control qty" min="1" required>
                                                </td>
                                                <td>
                                                <input type="number" name="products[${rowCount}][unit_price]" 
                                                class="form-control unit-price" min="0" step="0.01" required>
                                                </td>
                                                <td>
                                                <input type="text" class="form-control amount" readonly>
                                                </td>
                                                <td class="text-center align-middle">

                                                  <a href="javascript:void(0);"
                                                                                        class="text-danger fs-5 remove-row" title="Remove Row">
                                                                                        <i class="fas fa-trash"></i>
                                                                                    </a>
                                                </td>
                                                </tr>
                                                `;
                $('#products-table tbody').append(row);
                $('#products-table tbody tr:last .product-select').select2({
                    placeholder: "Select Product",
                    width: '100%'
                });
            });

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

            // Product select change
            // $(document).on('change', '.product-select', function () {
            //     const selectedOption = $(this).find('option:selected');
            //     const availableQty = selectedOption.data('available');
            //     const price = selectedOption.data('price');

            //     const row = $(this).closest('tr');
            //     row.find('.available-qty').val(availableQty);
            //     row.find('.qty').val(1);
            //     row.find('.unit-price').val(price);

            //     calculateRowAmount(row);
            //     calculateTotals();
            // });
            $(document).on('change', '.product-select', function () {
                const selectedOption = $(this).find('option:selected');
                const availableQty = selectedOption.data('available');
                const price = selectedOption.data('price');
                const productId = $(this).val();

                const row = $(this).closest('tr');
                row.find('.available-qty').val(availableQty);
                row.find('.qty').val(1);
                row.find('.unit-price').val(price);

                $('.duplicate-warning').remove();
                $('.duplicate-row').removeClass('duplicate-row');

                if (productId) {
                    let duplicateFound = false;

                    $('.product-select').each(function () {
                        if ($(this).val() === productId && $(this).closest('tr')[0] !== row[0]) {
                            duplicateFound = true;
                            row.addClass('duplicate-row');
                            $(this).closest('tr').addClass('duplicate-row');

                            const warningHTML = `
                                <div class="duplicate-warning text-danger small mt-1">
                                    <i class="fas fa-exclamation-triangle"></i> Duplicate Product
                                </div>
                            `;

                            row.find('.duplicate-warning-container').html(warningHTML);
                            $(this).closest('tr').find('.duplicate-warning-container').html(warningHTML);
                        }
                    });

                    $('#add-row').prop('disabled', duplicateFound);
                    $('#submit').prop('disabled', duplicateFound);
                }

                calculateRowAmount(row);
                calculateTotals();
            });

            // Quantity or unit price change
            $(document).on('change', '.qty, .unit-price', function () {
                const row = $(this).closest('tr');
                calculateRowAmount(row);
                calculateTotals();
            });

            // Discount type or amount change
            $('#discount').prop('disabled', true).val('');
            $(document).on('change', '#discount_type', function () {
                const discountType = $(this).val();
                if (discountType) {
                    $('#discount').prop('disabled', false);
                } else {
                    $('#discount').prop('disabled', true).val('');
                }
                calculateTotals();
            });
            $(document).on('input', '#discount', function () {
                calculateTotals();
            });

            // Toggle notes and terms
            $('#toggle-notes').click(function () {
                $('#notes-terms').toggle();
                $(this).html(function (_, html) {
                    return html.includes('Add') ?
                        '<i class="fas fa-minus"></i> Remove Note & Term' :
                        '<i class="fas fa-plus"></i> Add Note & Term';
                });
            });

            // Calculate row amount
            function calculateRowAmount(row) {
                const qty = parseFloat(row.find('.qty').val()) || 0;
                const unitPrice = parseFloat(row.find('.unit-price').val()) || 0;
                const amount = qty * unitPrice;

                row.find('.amount').val(amount.toFixed(2));

                // Add or update hidden input for the amount
                let amountInput = row.find('input[name^="products"][name$="[amount]"]');
                if (amountInput.length === 0) {
                    const name = row.find('.product-select').attr('name').replace('[id]', '[amount]');
                    amountInput = $('<input>').attr({
                        type: 'hidden',
                        name: name,
                        value: amount.toFixed(2)
                    });
                    row.append(amountInput);
                } else {
                    amountInput.val(amount.toFixed(2));
                }
            }

            // Calculate totals
            function calculateTotals() {
                let subTotal = 0;

                $('.product-row').each(function () {
                    const amount = parseFloat($(this).find('.amount').val()) || 0;
                    if (!isNaN(amount)) {
                        subTotal += amount;
                    }
                });

                const discountType = $('#discount_type').val();
                const discount = parseFloat($('#discount').val()) || 0;
                let discountAmount = 0;
                if (discountType == 2) {

                    if (discount >= 0 && discount <= 100) {
                        discountAmount = (subTotal * discount) / 100;
                    } else {
                        $('#discount').val('');
                        discountAmount = 0;
                    }
                } else if (discountType == 1) {
                    discountAmount = Math.min(discount, subTotal);
                }

                const total = Math.max(0, subTotal - discountAmount);

                // Update totals in the UI
                $('#sub-total').text(subTotal.toFixed(2) + ' ₹');
                $('#discount-amt').text(discountAmount.toFixed(2) + ' ₹');
                $('#total-amt').text(total.toFixed(2) + ' ₹');

                //hidden-input
                $('#hidden-sub-total').val(subTotal.toFixed(2));
                $('#hidden-discount-amt').val(discountAmount.toFixed(2));
                $('#hidden-total-amt').val(total.toFixed(2));
            }
            // Renumber rows
            function renumberRows() {
                let count = 1;
                $('.product-row').each(function () {
                    $(this).find('td:first').text(count);
                    count++;
                });
            }
        });
        $(document).ready(function () {
            let existingClientNumbers = $("#client_num_select option").map(function () {
                return $(this).val();
            }).get();

            $("#client_num_select").on("change", function () {
                let selectedNumbers = $(this).val() || [];

                let hasNewNumber = selectedNumbers.some(num => !existingClientNumbers.includes(num));

                if (hasNewNumber) {
                    $("#client_id").prop("required", true);
                    $("#client_name_error").text("Please enter Client Name");
                } else {
                    $("#client_id").prop("required", false);
                    $("#client_name_error").text("");
                }
            });

            $("#client_id").on("input", function () {
                if ($(this).val().trim() !== "") {
                    $("#client_name_error").text("");
                }
            });
        });
    </script>
    <script>
        $(document).ready(function () {
            $('#client_num_select').select2({
                placeholder: "Search or type a number",
                allowClear: true,
                tags: true,
                tokenSeparators: [',', ' '],
                createTag: function (params) {
                    return {
                        id: params.term,
                        text: params.term
                    };
                }
            });

        });
    </script>
    <script>
        window.onload = function () {
            // Get the current date
            var currentDate = new Date().toISOString().split('T')[0];

            // Set the current date for the quote_date and due_date fields
            document.getElementById('quote_date').value = currentDate;
            document.getElementById('due_date').value = currentDate;
        }
    </script>
@endpush