@extends('admin.layouts.app')

@section('title', 'Edit LON')

@section('content')
    <div class="page-header">
        <div class="row">
            <div class="col-sm-12">
                <h3 class="page-title">Edit Left Over Note</h3>
                <ul class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('left-over-notes.index') }}">Left Over Notes</a></li>
                    <li class="breadcrumb-item active">Edit Left Over Note</li>
                </ul>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-body">
                    <form action="{{ route('left-over-notes.update', $leftOverNote) }}" method="PUT"
                        class="needs-validation" novalidate>
                        @csrf
                        @method('PUT')

                        <div class="form-row row">

                            {{-- ✅ Company --}}
                            @role('Superadmin')
                                <div class="mb-3 col-md-12 d-none">
                                    <label for="company_id">Company</label>
                                    <select name="company" id="company_id" class="js-example-basic-single select2" required
                                        onchange="selectProducts(this.value); selectDepartments(this.value); createLeftOverNoteCode(this.value);">
                                        <option value="">Select Company</option>
                                        @foreach ($companies as $company)
                                            <option value="{{ $company->id }}"
                                                {{ $leftOverNote->company_id == $company->id ? 'selected' : '' }}>
                                                {{ $company->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </div>
                            @else
                                <input type="hidden" name="company" id="company_id" value="{{ $leftOverNote->company_id }}">
                            @endrole

                            {{-- ✅ Code --}}
                            <div class="mb-3 col-md-4">
                                <label for="code">Code <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" name="code" id="code"
                                    value="{{ $leftOverNote->code }}" readonly>
                            </div>

                            {{-- ✅ Product --}}
                            <div class="mb-3 col-md-4">
                                <label for="product_id">Product <span class="text-danger">*</span></label>
                                <select class="js-example-basic-single select2" name="product" id="product_id" required
                                    onchange="selectBatches(this.value); showHideRepeater();">
                                    <option value="">Select Product</option>
                                    @foreach ($products->where('company_id', $leftOverNote->company_id) as $product)
                                        <option value="{{ $product->id }}" @selected($leftOverNote->product_id == $product->id)>
                                            {{ $product->brand_name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            {{-- ✅ Batch --}}
                            <div class="mb-3 col-md-4">
                                <label for="batch_id">Batch <span class="text-danger">*</span></label>
                                <select class="js-example-basic-single select2" name="batch" id="batch_id" required>
                                    <option value="">Select Batch</option>
                                    @foreach ($batches->where('product_id', $leftOverNote->product_id) as $batch)
                                        <option value="{{ $batch->id }}"
                                            {{ $leftOverNote->batch_id == $batch->id ? 'selected' : '' }}>
                                            {{ $batch->batch_no }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            {{-- ✅ Department --}}
                            <div class="mb-3 col-md-4 d-none">
                                <label for="department_id">Department</label>
                                <select name="department" id="department_id" class="form-control" required>
                                    <option value="">Select Department</option>
                                    @foreach ($departments->where('company_id', $leftOverNote->company_id) as $department)
                                        <option value="{{ $department->id }}"
                                            {{ $leftOverNote->department_id == $department->id ? 'selected' : '' }}>
                                            {{ $department->name }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            {{-- ✅ Repeater Items --}}
                            <div class="col-md-12" id="repeater_col">
                                <div class="card border-0 mb-0" id="item-group">

                                    @foreach ($leftOverNote->items as $i => $item)
                                    <input type="hidden" name="items[{{ $i }}][lon_item_id]" value="{{ $item->id }}">
                                        {{-- @dd($item->rawMaterialItem->toArray()) --}}
                                        <div class="item-set">
                                            <div
                                                class="card-header bg-white py-2 d-flex justify-content-between align-items-center">
                                                <h4 class="card-title mb-0">Item {{ $i + 1 }}</h4>
                                                @if ($i > 0)
                                                    <button type="button" onclick="removeLastItem()"
                                                        class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></button>
                                                @endif
                                            </div>

                                            <div class="card-body px-0 pb-0">
                                                <div class="row">

                                                    <div class="mb-3 col-md-4">
                                                        <label for="">Code</label>
                                                        <input type="text" name="items[{{ $i }}][code]"
                                                            class="form-control code"
                                                            value="{{ ($item->rawMaterialItem && $item->rawMaterialItem->category ? $item->rawMaterialItem->category->prefix . '-' : '') . ($item?->rawMaterialItem?->code ?? '') }}"
                                                            readonly>
                                                    </div>

                                                    <div class="mb-3 col-md-4">
                                                        <label for="">Raw Material Items <span
                                                                class="text-danger">*</span></label>
                                                        <select required
                                                            name="items[{{ $i }}][raw_material_item]"
                                                            class="js-example-basic-single select2 raw_material_items_dropdown"
                                                            onchange="selectRmiDetailsT(this.value, this); getSirs(this.value, this);">
                                                            <option value="">Select Raw Material</option>
                                                            @foreach ($rawMaterialItems as $rmi)
                                                                <option value="{{ $rmi->id }}"
                                                                    {{ $item->raw_material_item_id == $rmi->id ? 'selected' : '' }}>
                                                                    {{ $rmi->name }}
                                                                </option>
                                                            @endforeach
                                                        </select>
                                                        <input type="hidden" class="rmi_title"
                                                            name="items[{{ $i }}][title]"
                                                            value="{{ $item->title }}">
                                                    </div>

                                                    <div class="mb-3 col-md-4">
                                                        <label for="">Store Issue Requisition <span
                                                                class="text-danger">*</span></label>
                                                        <select name="items[{{ $i }}][sir_item_id]"
                                                            class="js-example-basic-single select2 sir_id" required>
                                                            <option value="">Select SIR</option>
                                                            @if ($item->sirItem)
                                                                <option value="{{ $item->sir_item_id }}"
                                                                    data-qty="{{ $item->sirItem?->quantity - $item->sirItem?->lonQty() + $item->quantity }}"
                                                                    {{-- data-qty="{{ $item->sir_item_qty }}" --}} data-unit={{ $item->unit }}
                                                                    data-unit_price={{ $item->unit_price }} selected>
                                                                    {{ $item->sirItem->store_issue_requisition->code ?? 'N/A' }}
                                                                    — Qty:
                                                                    {{ $item->sirItem?->quantity - $item->sirItem?->lonQty() + $item->quantity ?? 'N/A' }}
                                                                </option>
                                                            @endif
                                                        </select>
                                                    </div>

                                                    <div class="mb-3 col-md-4">
                                                        <label for="">SIR Quantity</label>
                                                        <input type="text" name="items[{{ $i }}][sir_qty]"
                                                            class="form-control sir_qty" readonly {{-- value="{{ $item->sir_item_qty ?? '' }}" --}}
                                                            value="{{ $item->sirItem?->quantity - $item->sirItem?->lonQty() + $item->quantity ?? 0 }}">
                                                    </div>

                                                    <div class="mb-3 col-md-2">
                                                        <label>Quantity Left Over <span
                                                                class="text-danger">*</span></label>
                                                        <input type="number" min="0.01"
                                                            name="items[{{ $i }}][quantity]"
                                                            class="form-control product_quantity"
                                                            value="{{ $item->quantity }}" required>
                                                    </div>

                                                    <div class="mb-3 col-md-3">
                                                        <label>Unit Price <span class="text-danger">*</span></label>
                                                        <div class="input-group">
                                                            <input type="number" class="form-control w-25 unit_price"
                                                                name="items[{{ $i }}][unit_price]"
                                                                value="{{ $item->unit_price }}" readonly>
                                                            <input type="text" class="form-control unit"
                                                                name="items[{{ $i }}][unit]"
                                                                value="{{ $item->unit }}" readonly>
                                                        </div>
                                                    </div>

                                                    <div class="mb-3 col-md-3">
                                                        <label>Total</label>
                                                        <input type="number" class="form-control total_item_amount"
                                                            name="items[{{ $i }}][total_amount]"
                                                            value="{{ $item->total ?? '' }}" readonly>
                                                    </div>

                                                    <div class="mb-3 col-md-12">
                                                        <label>Description</label>
                                                        <textarea name="items[{{ $i }}][description]" class="form-control description">{{ $item->remarks ?? '' }}</textarea>
                                                    </div>

                                                </div>
                                            </div>
                                        </div>
                                    @endforeach

                                </div>

                                <div class="mb-3">
                                    <button type="button" onclick="addItem()" class="btn btn-primary">Add Item</button>
                                </div>
                            </div>

                        </div>

                        {{-- ✅ Buttons --}}
                        <a class="btn btn-secondary" href="{{ route('left-over-notes.index') }}">Cancel</a>
                        <input type="hidden" name="is_approved" id="is_approved" value="0">

                        <button type="submit" class="btn btn-primary"
                            onclick="document.getElementById('is_approved').value = 0;">Save</button>

                        @if (auth()->user()->hasPermission('Document Approval Edit'))
                            <button type="submit" class="btn btn-success"
                                onclick="document.getElementById('is_approved').value = 1;">Approve</button>
                        @endif

                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        // window.onload = async function() {
        //     showHideRepeater()
        //     $('#company_id').trigger('change');
        // }

        $('#batch_id').on('change', async function() {
            try {
                showHideRepeater()
                // const batchId = $(this).val(),
                //     productId = $('#product_id').val();
                // $('#store_issue_requisition_id').empty();
                // $('#store_issue_requisition_id').append(
                //     '<option value="" selected>Select Store Issue Requisition</option>');
                // const url = "{{ route('left-over-notes.get-batch-sir') }}";
                // if (batchId) {
                //     const res = await sendPostRequest(url, {
                //         batch_id: batchId,
                //         product_id: productId,
                //         _token: "{{ csrf_token() }}"
                //     });
                //     if (res.success) {
                //         $.each(res.sirs, function(i, sir) {
                //             let option = $('<option></option>').attr('value', sir.id).text(sir.code);
                //             $('#store_issue_requisition_id').append(option);
                //         });
                //     } else {
                //         toastr.error(res.message ??
                //             'Failed to Fetch Store Issue Requisitions For This Batch !');
                //     }
                // }
            } catch (error) {
                console.error(error);
            }
        });

        async function getSirs(id, el) {
            let product_id = $('#product_id').val(),
                batch_id = $('#batch_id').val(),
                main_row = $(el).closest('.item-set'),
                sirEl = $(main_row).find('.sir_id');

            $(sirEl).empty();
            $(sirEl).append('<option value="" selected>Select Store Issue Requisition</option>');
            let url = "{{ route('left-over-notes.get-batch-sir') }}";
            if (id) {
                const res = await sendPostRequest(url, {
                    product_id: product_id,
                    batch_id: batch_id,
                    raw_item_id: id,
                    _token: "{{ csrf_token() }}"
                }).then(res => {
                    if (res.success) {
                        $.each(res.sirItems, function(i, sirItem) {
                            const sirCode = sirItem.store_issue_requisition?.code ?? 'N/A';
                            const qty = sirItem.quantity ?? 0;
                            const unit = sirItem.unit ?? '';
                            const rate = sirItem.unit_price ?? 0;

                            const optionText = `${sirCode} — Qty: ${qty}`;

                            const option = $('<option></option>')
                                .attr('value', sirItem.id)
                                .attr('data-qty', qty)
                                .attr('data-unit', unit)
                                .attr('data-unit_price', rate)
                                .text(optionText);

                            // append to select
                            $(sirEl).append(option);
                        });
                    } else {
                        toastr.error(res.message ??
                            'Failed to Fetch Store Issue Requisitions For This Batch !');
                    }
                });
            }
        }

        $(document).on('change', '.sir_id', function() {
            let main_row = $(this).closest('.item-set'),
                qtyEl = $(main_row).find('.sir_qty'),
                lonQtyEl = $(main_row).find('.product_quantity'),
                unitEl = $(main_row).find('.unit'),
                unitPriceEl = $(main_row).find('.unit_price'),
                totalEl = $(main_row).find('.total_item_amount');

            $(qtyEl).val('');
            $(lonQtyEl).val('');
            $(unitEl).val('');
            $(unitPriceEl).val('');
            $(totalEl).val('');

            if ($(this).val()) {
                let selectedOption = main_row.find('.sir_id').find('option[value="' + $(this).val() + '"]')

                let qty = $(selectedOption).attr('data-qty'),
                    unit = $(selectedOption).attr('data-unit'),
                    unitPrice = $(selectedOption).attr('data-unit_price');

                $(qtyEl).val(qty);
                $(unitEl).val(unit);
                $(unitPriceEl).val(unitPrice);
                $(main_row).find('.product_quantity').attr('max', qty).prop('max', qty);
            }
        });

        $(document).on('change', '.product_quantity', function() {
            let main_row = $(this).closest('.item-set'),
                totalEl = $(main_row).find('.total_item_amount');

            $(totalEl).val((this.value * $(main_row).find('.unit_price').val()) || 0);
        })

        function showHideRepeater() {
            $('#repeater_col').addClass('d-none');
            if ($('#product_id').val() > 0 && $('#batch_id').val() > 0)
                $('#repeater_col').removeClass('d-none');
        }

        const itemSets = document.querySelectorAll('#item-group .item-set');
        let itemIndex = itemSets.length;

        function addItem() {
            let html = `
                <div class="item-set">
                    <div class="card-header bg-white py-2 d-flex justify-content-between align-items-center">
                        <h4 class="card-title mb-0">Item ${itemIndex + 1}</h4>
                        <button type="button" onclick="removeLastItem()" class="btn btn-danger btn-sm">
                            <i class="fa fa-trash"></i>
                        </button>
                    </div>
                    <div class="card-body px-0 pb-0">
                        <div class="row">
                            <div class="mb-3 col-md-4">
                                <label for="">Code</label>
                                <input type="text"
                                    name="items[${itemIndex}][code]"
                                    class="form-control code"
                                    placeholder="Code"
                                    readonly>
                            </div>

                            <div class="mb-3 col-md-4">
                                <label for="">Raw Material Items <span class="text-danger">*</span></label>
                                <select required
                                    name="items[${itemIndex}][raw_material_item]"
                                    class="js-example-basic-single select2 raw_material_items_dropdown"
                                    onchange="selectRmiDetailsT(this.value, this); getSirs(this.value, this);">
                                    <option value="">Select Raw Material</option>
                                </select>
                                <input type="hidden"
                                    class="rmi_title"
                                    name="items[${itemIndex}][title]"
                                    value="">
                            </div>

                            <div class="mb-3 col-md-4">
                                <label for="">Store Issue Requisition <span class="text-danger">*</span></label>
                                <select name="items[${itemIndex}][sir_item_id]"
                                    class="js-example-basic-single select2 sir_id"
                                    required>
                                    <option value="">Select SIR</option>
                                </select>
                            </div>

                            <div class="mb-3 col-md-4">
                                <label for="">SIR Quantity</label>
                                <input type="text"
                                    name="items[${itemIndex}][sir_qty]"
                                    class="form-control sir_qty"
                                    placeholder="SIR Item Quantity"
                                    readonly>
                            </div>

                            <div class="mb-3 col-md-2">
                                <label>Quantity Left Over <span class="text-danger">*</span></label>
                                <input type="number" min="0.01"
                                    class="form-control product_quantity"
                                    name="items[${itemIndex}][quantity]"
                                    placeholder="Quantity"
                                    required>
                            </div>

                            <div class="mb-3 col-md-3">
                                <label>Unit Price <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <input type="number"
                                        class="form-control w-25 unit_price"
                                        name="items[${itemIndex}][unit_price]"
                                        placeholder="Unit Price"
                                        required
                                        readonly>
                                    <input type="text"
                                        class="form-control unit"
                                        name="items[${itemIndex}][unit]"
                                        placeholder="Unit"
                                        required
                                        readonly>
                                </div>
                            </div>

                            <div class="mb-3 col-md-3">
                                <label>Total</label>
                                <input type="number"
                                    class="form-control total_item_amount"
                                    name="items[${itemIndex}][total_amount]"
                                    placeholder="Total"
                                    required
                                    value="0"
                                    readonly>
                            </div>

                            <div class="mb-3 col-md-12">
                                <label>Description</label>
                                <textarea name="items[${itemIndex}][description]"class="form-control description"></textarea>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            // ✅ Append the new item HTML
            $("#item-group").append(html);

            // ✅ Clone options from the first Raw Material dropdown
            const firstDropdownOptions = $(".raw_material_items_dropdown:first option").clone();

            const $newDropdown = $(`#item-group .item-set:last .raw_material_items_dropdown`);
            $newDropdown.append(firstDropdownOptions);

            // ✅ Clean up any leftover Select2 attributes before re-initializing
            $newDropdown.removeAttr('data-select2-id').find('option').removeAttr('data-select2-id');
            $newDropdown.off(); // remove old event handlers
            $newDropdown.select2(); // re-init

            // ✅ Initialize select2 for SIR dropdown as well
            const $sirDropdown = $(`#item-group .item-set:last .sir_id`);
            $sirDropdown.select2();

            // ✅ Update title field if option already selected
            const newDropdown = $newDropdown;
            const newTitleInput = $(`#item-group .item-set:last .rmi_title`);
            if (newDropdown.val() && newTitleInput.length > 0) {
                const optionText = newDropdown.find('option:selected').text().trim();
                newTitleInput.val(optionText);
            }

            itemIndex++;
        }


        function removeLastItem() {
            // Select all .item-set elements within #item-group
            const itemSets = document.querySelectorAll('#item-group .item-set');

            // Only remove if there is more than one item set
            // if (itemSets.length > 1) {
            itemSets[itemSets.length - 1].remove(); // Remove the last added item set
            itemIndex--; // Decrement the index to keep track accurately
            // }
        }

        function updateRmiTitle(selectElement) {
            const selectedOption = selectElement.options[selectElement.selectedIndex];
            const titleInput = selectElement.closest('.row').querySelector('.rmi_title');

            if (selectedOption && titleInput) {
                titleInput.value = selectedOption.text.trim();
            }
        }

        function removeItem(button) {
            const itemSets = document.querySelectorAll('#item-group .item-set');
            // Find the closest parent .item-set of the clicked button and remove it
            if (itemSets && itemSets.length > 1) {
                const item = button.closest('.item-set');
                if (item) {
                    item.remove();
                    itemIndex--; // Decrement itemIndex to ensure consistency
                }
            }
        }
    </script>

    @include('admin.left-over-notes.validation-script')
@endsection
