@extends('layouts.dashboard.adminapp')

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

@section('content')
    <div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h5 mb-0 text-gray-800">UEPL / Edit Request For Quotation</h1>
    </div>
    @if (session('success'))
        <div class="alert alert-success">{{ session('success') }}</div>
    @endif
    @if (session('error'))
        <div class="alert alert-danger">{{ session('error') }}</div>
    @endif

    <div class="row bg-white">
        <div class="col-lg-12">
            <h2>Edit Request For Quotation</h2><br><br>
            <form id="rfqform" action="{{ route('admin.rfq.update', $rfq->id) }}" method="POST"
                enctype="multipart/form-data">
                @csrf
                @method('PUT')
                <div class="rfq-form">
                    <div class="row">
                        <div class="col-md-6">
                            <label>RFQ ID *</label>
                            <input type="text" id="rfqNo" name="rfqNo" class="form-control" required readonly
                                value="{{ $rfq->rfq_no }}">
                        </div>
                        <div class="col-md-6">
                            <label>RFQ Date *</label>
                            <input type="date" id="rfqDate" name="rfqDate" class="form-control" required
                                value="{{ $rfq->rfq_date }}">
                        </div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label>Customer *</label>
                            <select id="customer" name="customer" class="form-control" required>
                                <option value="">Select Customer</option>
                                @foreach ($customers as $customer)
                                    <option value="{{ $customer->id }}"
                                        {{ $rfq->customer == $customer->id ? 'selected' : '' }}>{{ $customer->company }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label>Customer Reference No</label>
                            <input type="text" id="cusRefNo" name="cusRefNo" class="form-control"
                                value="{{ $rfq->cus_ref_no }}">
                        </div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label>RFQ Type *</label>
                            <select id="rfqType" name="rfqType" class="form-control" required>
                                <option value="">Select RFQ Type</option>
                                @foreach($rfqTypes as $type)
                                    <option value="{{ $type->rfqtype }}" {{ $rfq->rfq_type == $type->rfqtype ? 'selected' : '' }}>{{ $type->rfqtype }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label>Product Type *</label>
                            <select id="productType" name="productType" class="form-control" required>
                                <option value="">Select Product</option>
                                @foreach($productTypes as $type)
                                    <option value="{{ $type->name }}" {{ $rfq->product_type == $type->name ? 'selected' : '' }}>{{ $type->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label>Part No *</label>
                            <input type="text" id="partNo" name="partNo" class="form-control" required
                                value="{{ $rfq->part_no }}">
                        </div>
                        <div class="col-md-6">
                            <label>Project/Material No *</label>
                            <input type="text" id="project-materialNo" name="project_materialNo" class="form-control"
                                required value="{{ $rfq->project_material_no }}">
                        </div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label>Drawing File *</label>
                            @if ($rfq->drawing_file)
                                <a href="{{ Storage::url($rfq->drawing_file) }}" target="_blank" class="d-block mb-1">View
                                    Existing</a>
                            @endif
                            <input type="file" id="drawingFile" name="drawingFile" class="form-control" accept=".pdf">
                        </div>
                        <div class="col-md-3">
                            <label>Drawing No *</label>
                            <input type="text" id="drawingNo" name="drawingNo" class="form-control" required
                                value="{{ $rfq->drawing_no }}">
                        </div>
                        <div class="col-md-3">
                            <label>Drawing Revision *</label>
                            <input type="text" id="drawingRev" name="drawingRev" class="form-control" required
                                value="{{ $rfq->drawing_rev }}">
                        </div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label>Material Specification File</label>
                            @if ($rfq->material_specification_file)
                                <a href="{{ Storage::url($rfq->material_specification_file) }}" target="_blank"
                                    class="d-block mb-1">View Existing</a>
                            @endif
                            <input type="file" id="material-specificationFile" name="material_specificationFile"
                                class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label>RFQ Form File</label>
                            @if ($rfq->rfq_form_file)
                                <a href="{{ Storage::url($rfq->rfq_form_file) }}" target="_blank"
                                    class="d-block mb-1">View Existing</a>
                            @endif
                            <input type="file" id="rfqformFile" name="rfqformFile" class="form-control">
                        </div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label>Annexure File</label>
                            @if ($rfq->annexure_file)
                                <a href="{{ Storage::url($rfq->annexure_file) }}" target="_blank"
                                    class="d-block mb-1">View Existing</a>
                            @endif
                            <input type="file" id="annexureFile" name="annexureFile" class="form-control">
                        </div>
                        <div class="col-md-6"></div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label>Quantity *</label>
                            <input type="number" id="quantity" name="quantity" class="form-control" required
                                value="{{ $rfq->quantity }}">
                        </div>
                        <div class="col-md-6">
                            <label>UOM *</label>
                            <input type="text" id="uom" name="uom" class="form-control" required
                                value="{{ $rfq->uom }}">
                        </div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-md-12">
                            <label>Description</label>
                            <textarea id="note" name="note" class="form-control" rows="3">{{ $rfq->note }}</textarea>
                        </div>
                    </div>

                    <!-- Raw Materials (with select) -->
                    <div class="row mt-4">
                        <div class="col-md-12">
                            <label>Raw Materials *</label>
                            <div id="materials-wrapper">
                                {{-- Will be filled by JS for uniformity --}}
                            </div>
                            <button type="button" id="add-material" class="btn btn-primary btn-block mt-2">
                                Add Material
                            </button>
                        </div>
                    </div>

                    <div class="row mt-4">
                        <div class="col-md-2">
                            <button type="submit" class="btn btn-success">Update RFQ</button>
                        </div>
                        <div class="col-md-2">
                            <a href="{{ route('admin.rfq.rfqdetails') }}" class="btn btn-secondary">Back</a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal for Adding Raw Material -->
    <div class="modal fade" id="addRawMaterialModal" tabindex="-1" role="dialog"
        aria-labelledby="addRawMaterialLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <form id="addRawMaterialForm">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addRawMaterialLabel">Add New Raw Material</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"
                            style="width:auto">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="mb-2">
                            <label>Raw Material Name *</label>
                            <input type="text" name="name" class="form-control" required>
                        </div>
                        <div class="mb-2">
                            <label>ISO Specification *</label>
                            <input type="text" name="iso_specification" class="form-control" required>
                        </div>
                        <div class="mb-2">
                            <label>Material Density</label>
                            <input type="text" name="density" class="form-control">
                        </div>
                        <div class="mb-2">
                            <label>Mechanical Properties</label>
                            <input type="text" name="mechanical_properties" class="form-control">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" class="btn btn-success">Add</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
@endsection

@section('scripts')
    <script>
        // Load all raw materials for the selects
        let allMaterials = [];
        let initialMaterials = {!! json_encode(is_array(json_decode($rfq->raw_material, true)) ? json_decode($rfq->raw_material, true) : []) !!};
        let selectedMaterialIds = initialMaterials.map(x => x); // Will be filled by ids

        function loadRawMaterialsSelects(callback) {
            $.get('{{ route('admin.rawmaterials.list') }}', function(data) {
                allMaterials = data;
                renderMaterialRows();
                if (callback) callback();
            });
        }

        function renderMaterialRows() {
            let html = '';
            // If first load, map ids
            if (!Array.isArray(initialMaterials)) initialMaterials = [];
            initialMaterials = initialMaterials.filter(x => !!x); // Remove empty
            // Render all rows
            for (let i = 0; i < Math.max(initialMaterials.length, 1); i++) {
                html += buildMaterialRow(initialMaterials[i] || '');
            }
            $('#materials-wrapper').html(html);
            setTimeout(disableDuplicateOptions, 100);
        }

        function buildMaterialRow(selectedVal) {
            let select = `<select name="rawmaterials[]" class="form-control raw-material-select" required>`;
            select += '<option value="">Select Raw Material</option>';
            allMaterials.forEach(mat => {
                let sel = (mat.id == selectedVal) ? 'selected' : '';
                select += `<option value="${mat.id}" ${sel}>${mat.name} (${mat.iso_specification})</option>`;
            });
            select += '</select>';
            return `
            <div class="input-group mb-2 material-group">
                ${select}
                <div class="input-group-append">
                    <button type="button" class="btn btn-danger remove-material" style="margin-top: -27px;">
                        <i class="fas fa-trash-alt"></i>
                    </button>
                </div>
            </div>
        `;
        }

        function disableDuplicateOptions() {
            let selectedVals = [];
            $('.raw-material-select').each(function() {
                let val = $(this).val();
                if (val) selectedVals.push(val);
            });
            $('.raw-material-select').each(function() {
                let currentVal = $(this).val();
                $(this).find('option').each(function() {
                    let optVal = $(this).val();
                    if (optVal && optVal !== currentVal && selectedVals.includes(optVal)) {
                        $(this).prop('disabled', true);
                    } else {
                        $(this).prop('disabled', false);
                    }
                });
            });
        }

        // Show/hide Other fields
        $('#rfqType').on('change', function() {
            $('#other-rfq-type').toggle($(this).val() === 'other');
        });
        $('#productType').on('change', function() {
            $('#other-product-type').toggle($(this).val() === 'other');
        });

        // Add new material row
        $(document).on('click', '#add-material', function() {
            $('#materials-wrapper').append(buildMaterialRow(''));
            setTimeout(disableDuplicateOptions, 100);
        });

        // Remove material row
        $(document).on('click', '.remove-material', function() {
            $(this).closest('.material-group').remove();
            disableDuplicateOptions();
        });

        // Add raw material modal open
        $(document).on('click', '.add-rawmaterial-btn', function() {
            $('#addRawMaterialModal').modal('show');
        });

        // Store new raw material via modal
        $('#addRawMaterialForm').submit(function(e) {
            e.preventDefault();
            let form = this;
            $.ajax({
                url: '{{ route('admin.rawmaterials.store') }}',
                method: 'POST',
                data: $(form).serialize(),
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                success: function(response) {
                    if (response.success) {
                        $('#addRawMaterialModal').modal('hide');
                        form.reset();
                        loadRawMaterialsSelects(function() {
                            // Set last row value to new id
                            $('.raw-material-select').last().val(response.material.id);
                            disableDuplicateOptions();
                        });
                    }
                },
                error: function() {
                    alert('Error adding new raw material');
                }
            });
        });

        $(document).ready(function() {
            loadRawMaterialsSelects();
            // Show/hide Other fields if already selected on load
            $('#other-rfq-type').toggle($('#rfqType').val() === 'other');
            $('#other-product-type').toggle($('#productType').val() === 'other');
        });
    </script>
@endsection
