@extends('layouts.dashboard.superadminapp')

@section('title', 'Create Purchase RFQ')

@section('styles')
{{-- New Modern UI Stylesheet --}}
<link rel="stylesheet" href="{{ asset('css/modern-ui.css') }}">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    /* Select2 Customization */
    .select2-container {
        z-index: 999999 !important;
    }
</style>
@endsection

@section('content')
<div class="container-fluid">

    {{-- Modern Page Header Component --}}
    <x-modern-ui.page-header
        title="Create Purchase RFQ"
        subtitle="Purchase Request for Quotation Form"
        icon="file-alt"
        theme="teal"
    />

    {{-- RFQ Form --}}
    <form id="rfqform" action="{{ route('superadmin.purchasebom.rfq.store') }}" method="POST" enctype="multipart/form-data">
        @csrf

        {{-- Section 1: RFQ Information --}}
        <x-modern-ui.section-card
            title="RFQ Information"
            icon="file-alt"
            theme="teal"
        >
            <div class="row form-row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">RFQ ID <span class="required-star">*</span></label>
                    <input type="text" id="rfqNo" name="rfqNo" class="form-control" required readonly>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">RFQ Date <span class="required-star">*</span></label>
                    <input type="date" id="rfqDate" name="rfqDate" class="form-control" required>
                </div>
            </div>
        </x-modern-ui.section-card>

        {{-- Section 2: Vendor Information --}}
        <x-modern-ui.section-card
            title="Vendor Information"
            icon="building"
            theme="info"
        >
            <div class="row form-row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Vendor <span class="required-star">*</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="form-label">Vendor Reference No</label>
                    <input type="text" id="venRefNo" name="venRefNo" class="form-control" placeholder="Enter vendor reference number">
                </div>
            </div>
        </x-modern-ui.section-card>

        {{-- Section 3: Additional Details --}}
        <x-modern-ui.section-card
            title="Additional Details"
            icon="info-circle"
            theme="warning"
        >
            <div class="row form-row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">RFQ Type <span class="required-star">*</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="form-label">Delivery Terms</label>
                    <input type="text" id="deliveryTerms" name="deliveryTerms" class="form-control" placeholder="Enter delivery terms">
                </div>
            </div>
        </x-modern-ui.section-card>

        {{-- Section 4: RFQ Items --}}
        <x-modern-ui.section-card
            title="RFQ Items"
            icon="list"
            theme="success"
        >
            <div class="table-responsive">
                <table id="rfqTable" class="table table-bordered table-sm">
                    <thead>
                        <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 class="text-center">1</td>
                            <td>
                                <select class="form-control item-select" 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" placeholder="Description" /></td>
                            <td><input type="number" name="quantity[]" class="form-control" min="1" placeholder="Qty" /></td>
                            <td><input type="text" name="uom[]" class="form-control" placeholder="UOM" /></td>
                            <td><input type="date" name="requiredBy[]" class="form-control" /></td>
                            <td class="text-center">
                                <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 mt-3" onclick="addRow()">
                <i class="fa fa-plus mr-1"></i> Add Row
            </button>
        </x-modern-ui.section-card>

        {{-- Section 5: Notes & Terms --}}
        <x-modern-ui.section-card
            title="Notes & Terms"
            icon="sticky-note"
            theme="secondary"
        >
            <div class="row form-row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Note I</label>
                    <input type="text" id="description" name="description_main" class="form-control" placeholder="Additional note">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Note II</label>
                    <textarea id="note" name="note" class="form-control" rows="3" placeholder="Additional comments or terms"></textarea>
                </div>
            </div>
        </x-modern-ui.section-card>

        {{-- Section 6: File Attachments --}}
        <x-modern-ui.section-card
            title="File Attachments"
            icon="paperclip"
            theme="danger"
        >
            <div class="row form-row">
                <div class="col-md-12 mb-3">
                    <label class="form-label">Annexure Files</label>
                    <input type="file" id="annexureFiles" name="annexureFiles[]" class="form-control" multiple accept=".pdf,image/*">
                    <small class="text-muted">Accepted formats: PDF, Images (JPG, PNG)</small>
                    <div id="annexureFiles_preview" class="mt-2"></div>
                </div>
            </div>
        </x-modern-ui.section-card>

        {{-- Footer Actions Component --}}
        <x-modern-ui.footer-actions
            backUrl="{{ route('superadmin.purchasebom.rfq.rfqdetails') }}"
            backText="Back to List"
            submitText="Save RFQ"
            submitIcon="save"
            :showClear="true"
            clearText="Clear Form"
            clearId="clearBtn"
        />

    </form>

</div>
@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
// Initialize Select2
function initializeItemSelects() {
    $('.item-select').each(function () {
        const $this = $(this);

        if ($this.hasClass("select2-hidden-accessible")) {
            $this.select2('destroy');
        }

        $this.select2({
            dropdownParent: $('#rfqform'),
            width: '100%',
            placeholder: "Select Item",
            allowClear: true
        });
    });
}

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

// Set Today's Date
const today = new Date();
const formattedDate = formatDate(today);
document.getElementById('rfqDate').value = formattedDate;

function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

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

// Row Management
window.deleteRow = function(btn) {
    const rowCount = $('#rfqTable tbody tr').length;
    if (rowCount > 1) {
        $(btn).closest('tr').remove();
        updateSerialNumbers();
    } else {
        alert('At least one row is required.');
    }
};

function addRow() {
    const tableBody = document.querySelector("#rfqTable tbody");
    const firstRow = tableBody.querySelector("tr");

    if (!firstRow) return;

    const newRow = firstRow.cloneNode(true);
    newRow.querySelectorAll('input, select').forEach(input => {
        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();
}

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

// Custom reset function for Clear button
document.getElementById('clearBtn').addEventListener('click', function(e) {
    e.preventDefault();
    document.getElementById("rfqform").reset();
    const tableBody = document.getElementById("rfqTable").getElementsByTagName('tbody')[0];
    tableBody.innerHTML = '';
    addRow();

    // Re-generate RFQ ID and set date
    $.ajax({
        url: "{{ route('superadmin.purchasebom.rfq.generateId') }}",
        method: 'GET',
        success: function (response) {
            $('#rfqNo').val(response.rfqId);
        }
    });
    document.getElementById('rfqDate').value = formattedDate;
});
</script>
@endsection
