@extends('layouts.dashboard.superadminapp')

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

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

@section('content')

<style>

    /* Force Select2 dropdown above everything */
    .select2-container {
        z-index: 999999 !important;
    }

</style>

<!-- Page Heading -->
<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 | Request For Quotation</h1>
    <div class="display-date">
        <span id="day">day</span>,
        <span id="daynum">00</span>
        <span id="month">month</span>
        <span id="year">0000</span>
    </div>
    <div class="display-time"></div>
</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="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-file-alt mr-2"></i> Request For Quotation
        </h6>
    </div>
    <div class="card-body">
        <form id="rfqform" action="{{ route('superadmin.purchasebom.rfq.store') }}" method="POST" enctype="multipart/form-data">
            @csrf

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="small font-weight-bold">RFQ ID <span class="text-danger">*</span></label>
                    <input type="text" id="rfqNo" name="rfqNo" class="form-control" required readonly>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="small font-weight-bold">RFQ Date <span class="text-danger">*</span></label>
                    <input type="date" id="rfqDate" name="rfqDate" class="form-control" required>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="small font-weight-bold">Vendor <span class="text-danger">*</span></label>
                    <select id="vendor" name="vendor" class="form-control" required>
                        <option value="">Select Vendor</option>
                        @foreach ($vendors as $vendor)
                            <option value="{{ $vendor->id }}">{{ $vendor->company }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="small font-weight-bold">Vendor Reference No</label>
                    <input type="text" id="venRefNo" name="venRefNo" class="form-control">
                </div>
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="small font-weight-bold">RFQ Type <span class="text-danger">*</span></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 mb-3">
                    <label class="small font-weight-bold">Annexure Files</label>
                    <input type="file" id="annexureFiles" name="annexureFiles[]" class="form-control" multiple accept=".pdf,image/*">
                    <div id="annexureFiles_preview" class="mt-2"></div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="small font-weight-bold">Note I</label>
                    <input type="text" id="description" name="description_main" class="form-control">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="small font-weight-bold">Delivery Terms</label>
                    <input type="text" id="deliveryTerms" name="deliveryTerms" class="form-control">
                </div>
            </div>

            <div class="row">
                <div class="col-md-12 mb-3">
                    <label class="small font-weight-bold">Note II</label>
                    <textarea id="note" name="note" class="form-control" rows="3"></textarea>
                </div>
            </div>

            <hr>

            <h6 class="font-weight-bold text-primary mb-3"><i class="fas fa-list mr-2"></i>RFQ Items</h6>

            <div class="table-responsive">
                <table id="rfqTable" class="table table-bordered table-sm">
                    <thead class="thead-light">
                        <tr>
                            <th width="60">Sl.No</th>
                            <th>Item</th>
                            <th>Description</th>
                            <th width="100">Quantity</th>
                            <th width="100">UOM</th>
                            <th width="140">Required By</th>
                            <th width="50"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>1</td>
                            <td>
                                <select class="form-control item-select w-100" name="item[]" required>
                                    <option value="">Select Item</option>
                                    @foreach ($stock_items as $item)
                                        <option value="{{ $item->id }}">{{ $item->item_name }}</option>
                                    @endforeach
                                </select>
                            </td>
                            <td><input type="text" name="description[]" class="form-control" /></td>
                            <td><input type="number" name="quantity[]" class="form-control" min="1" /></td>
                            <td><input type="text" name="uom[]" class="form-control" /></td>
                            <td><input type="date" name="requiredBy[]" class="form-control" /></td>
                            <td>
                                <button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <button type="button" class="btn btn-primary btn-sm mb-4" onclick="addRow()">
                <i class="fa fa-plus mr-1"></i> Add Row
            </button>

            <hr>

            <div class="d-flex justify-content-end">
                <button class="btn btn-secondary mr-2" type="reset" onclick="resetForm()">
                    <i class="fas fa-undo mr-1"></i> Clear
                </button>
                <button class="btn btn-success" type="submit">
                    <i class="fas fa-save mr-1"></i> Save RFQ
                </button>
            </div>
        </form>
    </div>
</div>

@endsection

@section('scripts')

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>

    function initializeItemSelects() {
        $('.item-select').each(function () {
            const $this = $(this);
    
            if ($this.hasClass("select2-hidden-accessible")) {
                $this.select2('destroy');
            }
    
            $this.select2({
                dropdownParent: $('#rfqform'),
                width: 'resolve', // or '100%' if needed
                placeholder: "Select Item",
                allowClear: true
            });
        });
    }

    $(document).ready(function () {
        initializeItemSelects();
    });

    // 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
    }

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

    let rowCount = document.querySelectorAll('#rfqTable tbody tr').length;

    window.deleteRow = function(btn) {
        $(btn).closest('tr').remove();
        updateSerialNumbers();
    };

    function addRow_old() {
        const tableBody = document.getElementById("rfqTable").getElementsByTagName('tbody')[0];
        const row = tableBody.insertRow();

        row.innerHTML = `
            <td></td>
            <td><input type="text" name="item[]" class="form-control" /></td>
            <td><input type="text" name="description[]" class="form-control" /></td>
            <td><input type="number" name="quantity[]" min="1" class="form-control" /></td>
            <td><input type="text" name="uom[]" class="form-control" /></td>
            <td><input type="date" name="requiredBy[]" class="form-control" /></td>
            <td><button type="button" class="btn btn-danger" onclick="deleteRow(this)">
                <i class="fa fa-trash"></i></button></td>
        `;

        updateSerialNumbers();
    }
    
    function addRow() {
        const tableBody = document.querySelector("#rfqTable tbody");
        const firstRow = tableBody.querySelector("tr");
    
        if (!firstRow) return;
    
        const newRow = firstRow.cloneNode(true); // Deep clone
        newRow.querySelectorAll('input, select').forEach(input => {
            if (input.tagName === "SELECT") {
                input.value = "";
            } else {
                input.value = "";
            }
        });
    
        // Remove any existing select2 container from the cloned row
        $(newRow).find('.select2').remove();
        $(newRow).find('.item-select').removeClass('select2-hidden-accessible').removeAttr('data-select2-id tabindex aria-hidden');
    
        tableBody.appendChild(newRow);
        updateSerialNumbers();
        initializeItemSelects(); // Re-initialize Select2 for new dropdown
    }

    function updateSerialNumbers() {
        const rows = document.querySelectorAll("#rfqTable tbody tr");
        rows.forEach((row, index) => {
            row.cells[0].innerText = index + 1;
        });
    }

    function resetForm() {
        document.getElementById("rfqform").reset();
        const tableBody = document.getElementById("rfqTable").getElementsByTagName('tbody')[0];
        tableBody.innerHTML = '';
        addRow();
    }
</script>

@endsection
