@extends('layouts.dashboard.managerapp')

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

@section('content')

    <!-- Page Heading -->
    <x-layout.page-header title="UEPL | Request For Quotation" icon="file-alt" iconColor="info" />
    @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">
                <h1 class="pt-5 pb-5">Request For Quotation</h1>
            <form id="rfqform" action="{{ route('manager.rfq.store') }}" method="POST" enctype="multipart/form-data">
                @csrf

                <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>
                        </div>
                        <div class="col-md-6">
                            <label>RFQ Date *</label>
                            <input type="date" id="rfqDate" name="rfqDate" class="form-control" required>
                        </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 }}">{{ $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">
                        </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 }}">{{ $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 }}">{{ $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>
                        </div>
                        <div class="col-md-6">
                            <label>Project/Material No *</label>
                            <input type="text" id="project-materialNo" name="project_materialNo" class="form-control"
                                required>
                        </div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label>Drawing File *</label>
                            <input type="file" id="drawingFile" name="drawingFile" class="form-control" required
                                accept=".pdf">
                        </div>
                        <div class="col-md-3">
                            <label>Drawing No *</label>
                            <input type="text" id="drawingNo" name="drawingNo" class="form-control" required>
                        </div>
                        <div class="col-md-3">
                            <label>Drawing Revision *</label>
                            <input type="text" id="drawingRev" name="drawingRev" class="form-control" required>
                        </div>
                    </div>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label>Material Specification File</label>
                            <input type="file" id="material-specificationFile" name="material_specificationFile"
                                class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label>RFQ Form File</label>
                            <input type="file" id="rfqformFile" name="rfqformFile" class="form-control">
                        </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>
                        </div>
                        <div class="col-md-6">
                            <label>UOM *</label>
                            <input type="text" id="uom" name="uom" class="form-control" required>
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col-md-12">
                            <label>Annexure File</label>
                            <input type="file" id="annexureFile" name="annexure_file" class="form-control">
                        </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"></textarea>
                        </div>
                    </div>

                    <div class="row mt-4">
                        <div class="col-md-12">
                            <label>Raw Materials *</label>
                            <div id="materials-wrapper">
                                <div class="input-group mb-2 material-group">
                                    <select name="rawmaterials[]" class="form-control raw-material-select" required>
                                        <!-- Loaded by JS -->
                                    </select>
                                    <div class="input-group-append">
                                        <button type="button" class="btn btn-danger remove-material"
                                            style="margin-top: -26px;height: 39px;">
                                            <i class="fas fa-trash-alt"></i>
                                        </button>
                                    </div>
                                </div>
                            </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">Submit</button>-->
                    <!--    </div>-->
                    <!--</div>-->
                    <div class="row p-5">
                        <!-- Submit Button -->
                        <div class="btn pt-5 pb-5"><button class="btn btn-success" type="submit">Save</button>
                        </div>

                        <div class="btn pt-5 pb-5"><button class="btn btn-danger" type="reset"
                                onclick="resetForm()">Clear</button></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>
        // Get today's date and format it (YYYY-MM-DD)
        const today = new Date();
        const formattedDate = formatDate(today);

        // document.getElementById('receiveDate').value = formattedDate;
        document.getElementById('rfqDate').value = formattedDate;

        // Function to format the date as yyyy-mm-dd
        function formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // Add leading zero for single-digit months
            const day = String(date.getDate()).padStart(2, '0'); // Add leading zero for single-digit days
            return `${year}-${month}-${day}`; // Return in YYYY-MM-DD format
        }

        function loadRawMaterials(select = null, callback = null) {
            $.get('{{ route('manager.rawmaterials.list') }}', function (data) {
                $('.raw-material-select').each(function () {
                    var selectedVal = $(this).val();
                    $(this).empty().append('<option value="">Select Raw Material</option>');
                    $.each(data, function (_, mat) {
                        $(this).append(
                            `<option value="${mat.id}" ${selectedVal == mat.id ? 'selected' : ''}>${mat.name} (${mat.iso_specification})</option>`
                        );
                    }.bind(this));
                    if (selectedVal) $(this).val(selectedVal);
                });
                if (select) {
                    $(select).empty().append('<option value="">Select Raw Material</option>');
                    $.each(data, function (_, mat) {
                        $(select).append(
                            `<option value="${mat.id}">${mat.name} (${mat.iso_specification})</option>`
                        );
                    });
                }
                // After options loaded, enforce uniqueness
                setTimeout(disableDuplicateOptions, 100);
                if (callback) callback();
            });
        }

        function disableDuplicateOptions() {
            // Collect all selected values
            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();
                    // Only disable if value is selected in another select
                    if (optVal && optVal !== currentVal && selectedVals.includes(optVal)) {
                        $(this).prop('disabled', true);
                    } else {
                        $(this).prop('disabled', false);
                    }
                });
            });
        }

        $(document).ready(function () {
            // Initial load and uniqueness
            loadRawMaterials();

            // On change, re-enforce uniqueness
            $(document).on('change', '.raw-material-select', function () {
                disableDuplicateOptions();
            });

            // Add material row dynamically
            $('#add-material').click(function () {
                var $newRow = $(
                    `<div class="input-group mb-2 material-group">
                    <select name="rawmaterials[]" class="form-control raw-material-select" required></select>
                    <div class="input-group-append">
                        <button type="button" class="btn btn-danger remove-material" style="margin-top: -26px;height: 39px;">
                            <i class="fas fa-trash-alt"></i>
                        </button>
                    </div>
                </div>`
                );
                $('#materials-wrapper').append($newRow);
                loadRawMaterials($newRow.find('select'), disableDuplicateOptions);
            });

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

            // Add new raw material via modal form
            $('#addRawMaterialForm').submit(function (e) {
                e.preventDefault();
                var form = this;
                $.ajax({
                    url: '{{ route('manager.rawmaterials.store') }}',
                    method: 'POST',
                    data: $(form).serialize(),
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    success: function (response) {
                        if (response.success) {
                            var newMaterialId = response.material.id;
                            $('#addRawMaterialModal').modal('hide');
                            form.reset();
                            loadRawMaterials(null, function () {
                                $('.raw-material-select').last().val(newMaterialId);
                                disableDuplicateOptions();
                            });
                        }
                    },
                    error: function (xhr) {
                        alert('Error adding new raw material');
                    }
                });
            });

            // Focus on modal open
            $('#addRawMaterialModal').on('shown.bs.modal', function () {
                $(this).find('input[name="name"]').focus();
            });

            // 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');
            });

            // Generate RFQ ID
            $.ajax({
                url: "{{ route('manager.rfq.generateId') }}",
                method: 'GET',
                success: function (response) {
                    $('#rfqNo').val(response.rfqId);
                },
                error: function () {
                    alert('Failed to generate RFQ ID.');
                }
            });

            // Prevent form submit on duplicate selection
            $('#rfqform').on('submit', function (e) {
                let values = [];
                let duplicate = false;
                $('.raw-material-select').each(function () {
                    let val = $(this).val();
                    if (val) {
                        if (values.includes(val)) {
                            duplicate = true;
                            return false; // break loop
                        }
                        values.push(val);
                    }
                });
                if (duplicate) {
                    alert(
                        'Each Raw Material must be unique. Please select different materials for each row.');
                    e.preventDefault();
                    return false;
                }
            });
        });
    </script>
@endsection