@php
    $company_settings = getCompanyAllSetting();
@endphp
<h5 class="h4 d-inline-block font-weight-400 mb-4">{{ __('Parts Summary') }}</h5>
<div class="card repeater" @if ($acction == 'edit') data-value='{!! json_encode($invoice->items) !!}' @endif>
    <div class="item-section p-3 pb-0">
        <div class="row justify-content-between align-items-center">
            <div class="col-md-12 d-flex align-items-center justify-content-md-end px-4">
                <a href="#" data-repeater-create="" class="btn btn-primary mr-2" data-toggle="modal"
                    data-target="#add-bank">
                    <i class="ti ti-plus"></i> {{ __('Add Item') }}
                </a>
            </div>
        </div>
    </div>
    <div class="card-body table-border-style">
        <div class="table-responsive">
            <table class="table  mb-0 table-custom-style" data-repeater-list="items" id="sortable-table">
                <thead>
                    <tr>
                        <th>{{ __('Items') }}</th>
                        <th>{{ __('Quantity') }}</th>
                        <th>{{ __('Price') }} </th>
                        <th>{{ __('Discount') }}</th>
                        <th>{{ __('Tax') }} (%)</th>
                        <th class="text-end">
                            {{ __('Amount') }}<br><small class="text-danger font-weight-bold">{{ __('After discount & tax') }}</small>
                        </th>
                        <th></th>
                    </tr>
                </thead>

                <tbody class="ui-sortable" data-repeater-item>
                    <tr>
                        {{ Form::hidden('id', null, ['class' => 'form-control id']) }}
                        <td width="30%" class="form-group pt-0 product_div">
                            <select name="product_id" class="form-control product_id item parts_type js-searchBox"
                                data-url="{{ route('mobileservice.parts.details') }}" required>
                                <option value="0">{{ __('Select parts') }}</option>
                                @foreach ($getAllParts as $key => $parts)
                                    <option value="{{ $parts->id }}">{{ $parts->name }}</option>
                                @endforeach
                            </select>
                            @if (empty($getAllParts))
                                <div class=" text-xs">
                                    {{ __('Please create Product first.') }}<a href="{{ route('product-service.index') }}"><b>{{ __('Add Product') }}</b></a>
                                </div>
                            @endif
                        </td>
                        <td>
                            <div class="form-group price-input input-group search-form mb-0" style="width: 160px">
                                {{ Form::text('quantity', '', ['class' => 'form-control quantity', 'required' => 'required', 'placeholder' => __('Qty'), 'required' => 'required']) }}
                                <span class="unit input-group-text bg-transparent"></span>
                            </div>
                        </td>
                        <td>
                            <div class="form-group price-input input-group search-form mb-0" style="width: 160px">
                                {{ Form::text('price', '', ['class' => 'form-control price', 'required' => 'required', 'placeholder' => __('Price'), 'required' => 'required']) }}
                                <span class="input-group-text bg-transparent">{{ isset($company_settings['defult_currancy_symbol']) ? $company_settings['defult_currancy_symbol'] : '' }}</span>
                            </div>
                        </td>
                        <td>
                            <div class="form-group price-input input-group search-form mb-0" style="width: 160px">
                                {{ Form::text('discount', '', ['class' => 'form-control discount', 'required' => 'required', 'placeholder' => __('Discount')]) }}
                                <span class="input-group-text bg-transparent">{{ isset($company_settings['defult_currancy_symbol']) ? $company_settings['defult_currancy_symbol'] : '' }}</span>
                            </div>
                        </td>
                        <td>
                            <div class="form-group mb-0">
                                <div class="input-group colorpickerinput">
                                    <div class="taxes"></div>
                                    {{ Form::hidden('tax', '', ['class' => 'form-control tax text-dark']) }}
                                    {{ Form::hidden('itemTaxPrice', '', ['class' => 'form-control itemTaxPrice']) }}
                                    {{ Form::hidden('itemTaxRate', '', ['class' => 'form-control itemTaxRate']) }}
                                </div>
                            </div>
                        </td>
                        <td class="text-end amount">0.00</td>
                        <td>
                            <div class="action-btn ms-2 float-end" data-repeater-delete>
                                <a href="#!" class="mx-3 btn btn-sm d-inline-flex align-items-center m-2 p-2 bg-danger">
                                    <i class="ti ti-trash text-white" data-bs-toggle="tooltip" data-bs-original-title="{{ __('Delete') }}"></i>
                                </a>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <div class="form-group mb-0">
                                {{ Form::textarea('description', null, ['class' => 'form-control pro_description', 'rows' => '2', 'placeholder' => __('Description')]) }}
                            </div>
                        </td>
                        <td colspan="5"></td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td></td>
                        <td>
                            <strong>{{ __('Sub Total') }} ({{ isset($company_settings['defult_currancy_symbol']) ? $company_settings['defult_currancy_symbol'] : '' }})</strong>
                        </td>
                        <td class="text-end subTotal">0.00</td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td></td>
                        <td>
                            <strong>{{ __('Discount') }} ({{ isset($company_settings['defult_currancy_symbol']) ? $company_settings['defult_currancy_symbol'] : '' }})</strong>
                        </td>
                        <td class="text-end totalDiscount">0.00</td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td></td>
                        <td>
                            <strong>{{ __('Tax') }} ({{ isset($company_settings['defult_currancy_symbol']) ? $company_settings['defult_currancy_symbol'] : '' }})</strong>
                        </td>
                        <td class="text-end totalTax">0.00</td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td></td>
                        <td>
                            <strong>{{ __('Repair Charge') }} ({{ isset($company_settings['defult_currancy_symbol']) ? $company_settings['defult_currancy_symbol'] : '' }})</strong>
                        </td>
                        <td class="text-end totalServiceCharge">0.00</td>
                    </tr>
                    <tr>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td>&nbsp;</td>
                        <td></td>
                        <td class="blue-text">
                            <strong>{{ __('Total Amount') }} ({{ isset($company_settings['defult_currancy_symbol']) ? $company_settings['defult_currancy_symbol'] : '' }})</strong>
                        </td>
                        <td class="text-end totalAmount blue-text">0.00</td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>
<script src="{{ asset('js/jquery.repeater.min.js') }}"></script>
<script src="{{ asset('js/jquery-searchbox.js') }}"></script>

{{-- repeater js --}}
<script>
    var allParts = @json($getAllParts);

    function refreshPartSelectOptions() {
        // Get all selected part IDs except 0
        const selectedPartIds = $('.product_id').map(function() {
            return $(this).val();
        }).get().filter(val => val && val !== "0");

        $('.product_id').each(function() {
            const $select = $(this);
            const currentValue = $select.val();

            $select.empty().append(`<option value="0">{{ __('Select parts') }}</option>`);

            allParts.forEach(part => {
                const isSelectedInOther = selectedPartIds.includes(part.id.toString()) && currentValue !== part.id.toString();
                if (!isSelectedInOther) {
                    $select.append(`<option value="${part.id}" ${currentValue == part.id ? 'selected' : ''}>${part.name}</option>`);
                }
            });
        });
    }

    var selector = "body";
    if ($(selector + " .repeater").length) {
        var $dragAndDrop = $("body .repeater tbody").sortable({
            handle: '.sort-handler'
        });
        var $repeater = $(selector + ' .repeater').repeater({
            initEmpty: false,
            defaultValues: {
                'status': 1
            },
            show: function() {
                $(this).slideDown();
                var file_uploads = $(this).find('input.multi');
                if (file_uploads.length) {
                    $(this).find('input.multi').MultiFile({
                        max: 3,
                        accept: 'png|jpg|jpeg',
                        max_size: 2048
                    });
                }
                refreshPartSelectOptions();
                JsSearchBox();
            },
            hide: function(deleteElement) {
                var $row = $(this); // The current row
                var id = $row.find('.id').val(); // Get the item ID

                // Call the global delete function
                deleteInvoiceItem($row, id, function() {
                    var totalItemTaxPrice = 0;
                    var itemTaxPriceInput = $('.itemTaxPrice');
                    for (var j = 0; j < itemTaxPriceInput.length; j++) {
                        totalItemTaxPrice += parseFloat(itemTaxPriceInput[j].value);
                    }

                    var subTotal = 0;
                    var inputs = $(".price");
                    var quantity = $(".quantity");
                    for (var i = 0; i < inputs.length; i++) {
                        subTotal += parseFloat($(inputs[i]).val() * $(quantity[i]).val());
                    }

                    var total = 0;
                    var inputs = $(".amount");
                    for (var i = 0; i < inputs.length; i++) {
                        total = parseFloat(total) + parseFloat($(inputs[i]).html());
                    }

                    var service_charge = $('.service_charge').val();
                    var service = parseFloat(service_charge);
                    totalAmount = parseFloat(total) + service;

                    var totalItemDiscountPrice = 0;
                    var itemDiscountPriceInput = $('.discount');
                    for (var k = 0; k < itemDiscountPriceInput.length; k++) {
                        if (itemDiscountPriceInput[k].value == '') {
                            itemDiscountPriceInput[k].value = parseFloat(0);
                        }
                        totalItemDiscountPrice += parseFloat(itemDiscountPriceInput[k].value);
                    }

                    $('.subTotal').html(subTotal.toFixed(2));
                    $('.totalTax').html(totalItemTaxPrice.toFixed(2));
                    $('.totalAmount').html(totalAmount.toFixed(2));
                    $('.totalDiscount').html(totalItemDiscountPrice.toFixed(2));
                });
            },
            ready: function(setIndexes) {
                $dragAndDrop.on('drop', setIndexes);
            },
            isFirstItemUndeletable: true
        });
    }
</script>

{{-- Ajax call for get the parts details  --}}
<script>
    $(document).on('change', '.parts_type', function() {
        var iteams_id = $(this).val();
        var url = $(this).data('url');
        var el = $(this);
        $.ajax({
            url: url,
            type: 'POST',
            data: {
                _token: "{{ csrf_token() }}",
                'product_id': iteams_id
            },
            cache: false,
            success: function(data) {
                var item = JSON.parse(data);
                $(el.parent().parent().find('.quantity')).val(1);
                if (item.product != null) {
                    $(el.parent().parent().find('.price')).val(item.product.sale_price);
                    $(el.parent().parent().parent().find('.pro_description')).val(item.product.description);
                } else {
                    $(el.parent().parent().find('.price')).val(0);
                    $(el.parent().parent().parent().find('.pro_description')).val('');
                }

                var taxes = '';
                var tax = [];
                var totalItemTaxRate = 0;
                if (item.taxes == 0) {
                    taxes += '-';
                } else {
                    for (var i = 0; i < item.taxes.length; i++) {
                        taxes += '<span class="badge bg-primary p-2 px-3 me-1">' +
                            item.taxes[i].name + ' ' + '(' + item.taxes[i].rate + '%)' +
                            '</span>';
                        tax.push(item.taxes[i].id);
                        totalItemTaxRate += parseFloat(item.taxes[i].rate);
                    }
                }

                var itemTaxPrice = 0;
                if (item.product != null) {
                    var itemTaxPrice = parseFloat((totalItemTaxRate / 100) * (item.product.sale_price * 1));
                }

                $(el.parent().parent().find('.itemTaxPrice')).val(itemTaxPrice.toFixed(2));
                $(el.parent().parent().find('.itemTaxRate')).val(totalItemTaxRate.toFixed(2));
                $(el.parent().parent().find('.taxes')).html(taxes);
                $(el.parent().parent().find('.tax')).val(tax);
                $(el.parent().parent().find('.unit')).html(item.unit);
                $(el.parent().parent().find('.discount')).val(0);
                $(el.parent().parent().find('.amount')).html(item.totalAmount);

                var inputs = $(".amount");
                var subTotal = 0;
                for (var i = 0; i < inputs.length; i++) {
                    subTotal = parseFloat(subTotal) + parseFloat($(inputs[i]).html());
                }

                var totalItemPrice = 0;
                var priceInput = $('.price');
                var quantity = $('.quantity');
                for (var j = 0; j < priceInput.length; j++) {
                    totalItemPrice += parseFloat(priceInput[j].value * quantity[j].value);
                }

                var totalItemTaxPrice = 0;
                var itemTaxPriceInput = $('.itemTaxPrice');
                for (var j = 0; j < itemTaxPriceInput.length; j++) {
                    totalItemTaxPrice += parseFloat(itemTaxPriceInput[j].value);
                    if (item.product != null) {
                        $(el.parent().parent().find('.amount')).html(parseFloat(item.totalAmount) + parseFloat(itemTaxPriceInput[j].value));
                    }
                }

                var totalItemDiscountPrice = 0;
                var itemDiscountPriceInput = $('.discount');
                for (var k = 0; k < itemDiscountPriceInput.length; k++) {
                    totalItemDiscountPrice += parseFloat(itemDiscountPriceInput[k].value);
                }

                var totalServiceCharge = $('.service_charge').val();
                $('.subTotal').html(totalItemPrice.toFixed(2));
                $('.totalTax').html(totalItemTaxPrice.toFixed(2));
                $('.totalAmount').html((parseFloat(totalItemPrice) - parseFloat(totalItemDiscountPrice) + parseFloat(totalItemTaxPrice) + parseFloat(totalServiceCharge)).toFixed(2));
            },
        });
    });
</script>

{{-- qty update --}}
<script>
    $(document).on('keyup', '.quantity', function() {
        var el = $(this).parent().parent().parent().parent();

        var quantity = $(this).val();
        var price = $(el.find('.price')).val();
        var discount = $(el.find('.discount')).val();
        if (discount.length <= 0) {
            discount = 0;
        }

        var totalItemPrice = (quantity * price) - discount;
        var amount = (totalItemPrice);
        var totalItemTaxRate = $(el.find('.itemTaxRate')).val();
        var itemTaxPrice = parseFloat((totalItemTaxRate / 100) * (totalItemPrice));

        $(el.find('.itemTaxPrice')).val(itemTaxPrice.toFixed(2));
        $(el.find('.amount')).html(parseFloat(itemTaxPrice) + parseFloat(amount));

        var totalItemTaxPrice = 0;
        var itemTaxPriceInput = $('.itemTaxPrice');
        for (var j = 0; j < itemTaxPriceInput.length; j++) {
            totalItemTaxPrice += parseFloat(itemTaxPriceInput[j].value);
        }

        var totalItemPrice = 0;
        var inputs_quantity = $(".quantity");
        var priceInput = $('.price');
        for (var j = 0; j < priceInput.length; j++) {
            totalItemPrice += (parseFloat(priceInput[j].value) * parseFloat(inputs_quantity[j].value));
        }

        var inputs = $(".amount");
        var subTotal = 0;
        for (var i = 0; i < inputs.length; i++) {
            subTotal = parseFloat(subTotal) + parseFloat($(inputs[i]).html());
        }

        var totalServiceCharge = $('.service_charge').val();
        $('.subTotal').html(totalItemPrice.toFixed(2));
        $('.totalTax').html(totalItemTaxPrice.toFixed(2));
        $('.totalAmount').html((parseFloat(subTotal) + parseFloat(totalServiceCharge)).toFixed(2));
    })
</script>

{{-- price update--}}
<script>
    $(document).on('keyup change', '.price', function() {
        var el = $(this).parent().parent().parent().parent();

        var price = $(this).val();
        var quantity = $(el.find('.quantity')).val();
        if (quantity.length <= 0) {
            quantity = 1;
        }

        var discount = $(el.find('.discount')).val();
        if (discount.length <= 0) {
            discount = 0;
        }

        var totalItemPrice = (quantity * price) - discount;
        var amount = (totalItemPrice);
        var totalItemTaxRate = $(el.find('.itemTaxRate')).val();
        var itemTaxPrice = parseFloat((totalItemTaxRate / 100) * (totalItemPrice));

        $(el.find('.itemTaxPrice')).val(itemTaxPrice.toFixed(2));
        $(el.find('.amount')).html(parseFloat(itemTaxPrice) + parseFloat(amount));

        var totalItemTaxPrice = 0;
        var itemTaxPriceInput = $('.itemTaxPrice');
        for (var j = 0; j < itemTaxPriceInput.length; j++) {
            totalItemTaxPrice += parseFloat(itemTaxPriceInput[j].value);
        }

        var totalItemPrice = 0;
        var inputs_quantity = $(".quantity");
        var priceInput = $('.price');
        for (var j = 0; j < priceInput.length; j++) {
            if (inputs_quantity[j].value <= 0) {
                inputs_quantity[j].value = 1;
            }
            totalItemPrice += (parseFloat(priceInput[j].value) * parseFloat(inputs_quantity[j].value));
        }

        var inputs = $(".amount");
        var subTotal = 0;
        for (var i = 0; i < inputs.length; i++) {
            subTotal = parseFloat(subTotal) + parseFloat($(inputs[i]).html());
        }

        var totalServiceCharge = $('.service_charge').val();
        $('.subTotal').html(totalItemPrice.toFixed(2));
        $('.totalTax').html(totalItemTaxPrice.toFixed(2));
        $('.totalAmount').html((parseFloat(subTotal) + parseFloat(totalServiceCharge)).toFixed(2));
    })
</script>

{{-- discount update--}}
<script>
    $(document).on('keyup change', '.discount', function() {
        var el = $(this).parent().parent().parent();

        var discount = $(this).val();
        if (discount.length <= 0) {
            discount = 0;
        }

        var price = $(el.find('.price')).val();
        var quantity = $(el.find('.quantity')).val();
        var totalItemPrice = (quantity * price) - discount;
        var amount = (totalItemPrice);
        var totalItemTaxRate = $(el.find('.itemTaxRate')).val();
        var itemTaxPrice = parseFloat((totalItemTaxRate / 100) * (totalItemPrice));

        $(el.find('.itemTaxPrice')).val(itemTaxPrice.toFixed(2));
        $(el.find('.amount')).html(parseFloat(itemTaxPrice) + parseFloat(amount));

        var totalItemTaxPrice = 0;
        var itemTaxPriceInput = $('.itemTaxPrice');
        for (var j = 0; j < itemTaxPriceInput.length; j++) {
            totalItemTaxPrice += parseFloat(itemTaxPriceInput[j].value);
        }

        var totalItemPrice = 0;
        var inputs_quantity = $(".quantity");
        var priceInput = $('.price');
        for (var j = 0; j < priceInput.length; j++) {
            totalItemPrice += (parseFloat(priceInput[j].value) * parseFloat(inputs_quantity[j].value));
        }

        var inputs = $(".amount");
        var subTotal = 0;
        for (var i = 0; i < inputs.length; i++) {
            subTotal = parseFloat(subTotal) + parseFloat($(inputs[i]).html());
        }

        var totalItemDiscountPrice = 0;
        var itemDiscountPriceInput = $('.discount');
        for (var k = 0; k < itemDiscountPriceInput.length; k++) {
            if (itemDiscountPriceInput[k].value == '') {
                itemDiscountPriceInput[k].value = parseFloat(0);
            }
            totalItemDiscountPrice += parseFloat(itemDiscountPriceInput[k].value);
        }

        var totalServiceCharge = $('.service_charge').val();
        $('.subTotal').html(totalItemPrice.toFixed(2));
        $('.totalTax').html(totalItemTaxPrice.toFixed(2));
        $('.totalAmount').html((parseFloat(subTotal) + parseFloat(totalServiceCharge)).toFixed(2));
        $('.totalDiscount').html(totalItemDiscountPrice.toFixed(2));
    })
</Script>

@if ($acction == 'edit')
    <script>
        $(document).ready(function() {
            var value = $(selector + " .repeater").attr('data-value');
            if (typeof value != 'undefined' && value.length != 0) {
                value = JSON.parse(value);
                $repeater.setList(value);

                // Remove delete button for first row
                $('.repeater [data-repeater-item]').first().find('[data-repeater-delete]').remove();

                for (var i = 0; i < value.length; i++) {
                    var tr = $('#sortable-table .id[value="' + value[i].id + '"]').parent();
                    tr.find('.item').val(value[i].product_id);
                    var element = tr.find('.parts_type');
                    var product_id = value[i].product_id;
                    changeItem(tr.find('.item'));
                }
            }
            const elementsToRemove = document.querySelectorAll('.bs-pass-para.repeater-action-btn');
            if (elementsToRemove.length > 0) {
                elementsToRemove[0].remove();
            }
        });

        var repair_id = '{{ $invoice->id }}';

        function changeItem(element) {
            var iteams_id = element.val();
            var url = element.data('url');
            var el = element;

            $.ajax({
                url: '{{ route('mobileservice.parts.details') }}',
                type: 'GET',
                headers: {
                    'X-CSRF-TOKEN': jQuery('#token').val()
                },
                data: {
                    'repair_id': repair_id,
                    'product_id': iteams_id,
                },
                cache: false,
                success: function(data) {
                    var item = JSON.parse(data);
                    var invoiceItems = item.parts;
                    var taxes = '';
                    var tax = [];

                    var totalItemTaxRate = 0;
                    for (var i = 0; i < item.taxes.length; i++) {
                        taxes +=
                            '<span class="badge bg-primary p-2 px-3 me-1">' +
                            item.taxes[i].name + ' ' + '(' + item.taxes[i].rate + '%)' +
                            '</span>';
                        tax.push(item.taxes[i].id);
                        totalItemTaxRate += parseFloat(item.taxes[i].rate);
                    }

                    if (invoiceItems != null) {
                        var itemTaxPrice = parseFloat((totalItemTaxRate / 100) * (invoiceItems.price * invoiceItems.quantity));
                    } else {
                        var itemTaxPrice = parseFloat((totalItemTaxRate / 100) * (item.product.sale_price * 1));
                    }

                    $(el.parent().parent().find('.itemTaxPrice')).val(itemTaxPrice.toFixed(2));
                    $(el.parent().parent().find('.itemTaxRate')).val(totalItemTaxRate.toFixed(2));
                    $(el.parent().parent().find('.taxes')).html(taxes);
                    $(el.parent().parent().find('.tax')).val(tax);
                    $(el.parent().parent().find('.unit')).html(item.unit);

                    $(".discount").trigger('change');
                }
            });
        }
    </script>
@endif
