@extends('admin.layouts.app')

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

    <ul class="nav nav-pills">
        <li class="nav-item">
            <a class="nav-link" href="javascript:void(0)" @disabled(true)>General</a>
        </li>
        <li class="nav-item">
            <a class="nav-link active" aria-current="page" @disabled(true)
                href="javascript:void(0)">Production</a>
        </li>
    </ul>

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

                        <input type="hidden" name="is_production" value="1">
                        <input type="hidden" name="is_general" value="0">

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

                            <div class="mb-3 col-md-6">
                                <label for="code">Code</label>
                                <input type="text" class="form-control" name="code" id="code" readonly
                                    value="{{ $rejectionReturnNote->code }}">
                            </div>

                            <div class="mb-3 col-md-6">
                                <label for="invoice_id">Invoice</label>
                                <select name="invoice" id="invoice_id" class="js-example-basic-single select2" required
                                    onchange="selectSupplierByInvoice(this.value);">
                                    <option value="">Select Invoice</option>
                                    @foreach ($invoices->where('company_id', $rejectionReturnNote->company_id) as $invoice)
                                        <option value="{{ $invoice->id }}"
                                            {{ $rejectionReturnNote->invoice_id == $invoice->id ? 'selected' : '' }}>
                                            {{ $invoice->code }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            <div class="mb-3 col-md-4">
                                <label for="supplier">Supplier</label>
                                <input type="text" class="form-control" name="supplier_name" id="supplier_name"
                                    value="{{ $rejectionReturnNote->party->name ?? '' }}" readonly>
                                <input type="hidden" name="supplier" id="supplier_id"
                                    value="{{ $rejectionReturnNote->party_id }}">
                            </div>

                            <div class="mb-3 col-md-4">
                                <label for="type">Type</label>
                                <select name="type" id="type" class="js-example-basic-single select2" required>
                                    <option value="gate_pass"
                                        {{ $rejectionReturnNote->type == 'gate_pass' ? 'selected' : '' }}>Gate Pass
                                    </option>
                                    <option value="burn_note"
                                        {{ $rejectionReturnNote->type == 'burn_note' ? 'selected' : '' }}>Destruction/Burn
                                        Note</option>
                                </select>
                            </div>

                            <div class="mb-3 col-md-4">
                                <label for="store_issue_requisition_id">Store Issue Requisition</label>
                                <select name="store_issue_requisition" id="store_issue_requisition_id"
                                    class="js-example-basic-single select2" required
                                    onchange="getGeneralStoreRequisitionDetails(this.value)">
                                    <option value="">Select Store Issue Requisition</option>
                                    @foreach ($requisitions as $requisition)
                                        <option value="{{ $requisition->id }}"
                                            {{ $rejectionReturnNote->store_issue_requisition_id == $requisition->id ? 'selected' : '' }}>
                                            {{ $requisition->code }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            {{-- ITEM SECTION --}}
                            <div class="col-md-12">
                                <div class="card border-0 mb-0" id="item-group">
                                    @forelse ($rejectionReturnNote->items as $i => $item)
                                        <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>
                                                <button type="button" onclick="removeItem(this)"
                                                    class="btn btn-danger btn-sm">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                            </div>
                                            <div class="card-body px-0 pb-0">
                                                <input type="hidden" name="items[{{ $i }}][types]"
                                                    value="{{ $item->product_id ? 'product' : 'raw_material_item' }}">
                                                <div class="row">
                                                    <div class="mb-3 col-md">
                                                        <label>Description</label>
                                                        <input type="text" class="form-control"
                                                            name="items[{{ $i }}][name]"
                                                            value="{{ $item->item_name }}" readonly>
                                                        <input type="hidden"
                                                            name="items[{{ $i }}][{{ $item->product_id ? 'product' : 'raw_material_item' }}]"
                                                            value="{{ $item->product_id ?? $item->raw_material_item_id }}">
                                                    </div>

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

                                                    <div class="mb-3 col-md">
                                                        <label>Quantity</label>
                                                        <input type="number" class="form-control quantity" readonly
                                                            name="items[{{ $i }}][quantity]"
                                                            value="{{ $item->quantity }}"
                                                            oninput="calculateSingleProductAmount()" min="1"
                                                            max="{{ $item->max_quantity ?? 999 }}">
                                                        <input type="hidden"
                                                            name="items[{{ $i }}][max_quantity]"
                                                            value="{{ $item->max_quantity ?? 999 }}">
                                                    </div>

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

                                                    <div class="mb-3 col-12">
                                                        <label>Remarks</label>
                                                        <textarea class="form-control" name="items[{{ $i }}][remarks]" required>{{ $item->remarks }}</textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    @empty
                                        <div class="item-set">
                                            <div class="card-header bg-white py-2 mb-3">
                                                <p class="mb-0 text-center">No items available.</p>
                                            </div>
                                        </div>
                                    @endforelse
                                </div>
                            </div>
                        </div>

                        <a class="btn btn-secondary" href="{{ route('rejection-return-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;">
                            Update
                        </button>

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

    <script>
        let allGrns = @json($goodsReceivings);

        $(document).on('change', '#invoice_id', function() {
            console.log("🚀 ~ allGrns:", allGrns);
            const invoiceId = $(this).val();
            console.log("🚀 ~ $(this).val():", invoiceId);
            if (invoiceId > 0) {
                selectProductionSIRs(document.getElementById('company_id').value, invoiceId);
            }
        });

        function selectProductionSIRs(companyId, invoiceId) {
            var sirEl = document.getElementById("store_issue_requisition_id");
            sirEl.innerHTML = '<option value="">Select Store Issue Requisition</option>';
            // sirEl.appendChild(option);

            if (companyId && invoiceId && sirEl) {
                let url =
                    '{{ route('ajax-companies.production-sir-by-invoice', ['companyId' => ':id', 'invoiceId' => ':invoiceId']) }}'
                    .replace(':id', companyId).replace(':invoiceId', invoiceId);
                // fetch(`/companies/${companyId}/general-store-requisitions`)
                fetch(url)
                    .then((response) => {
                        if (!response.ok) {
                            throw new Error(
                                "Unauthorized or error fetching store issue requisitions"
                            );
                        }
                        return response.json();
                    })
                    .then((data) => {
                        data.storeIssueRequisitions.forEach(function(storeIssueRequisition) {
                            var option = document.createElement("option");
                            option.value = storeIssueRequisition.id;
                            option.textContent = storeIssueRequisition.code;
                            sirEl.appendChild(option);
                        });
                    })
                    .catch((error) =>
                        console.error("Error fetching store issue requisitions:", error)
                    );
            }
        }

        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.rejection-return-notes.production-validation-script')
@endsection
