@extends('layouts.dashboard.superadminapp')

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

@section('styles')
<link rel="stylesheet" href="{{ asset('css/modern-form-pattern.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 theme-teal">

    <!-- Modern Page Header -->
    <div class="modern-page-header">
        <div class="header-left">
            <div class="icon-wrapper">
                <i class="fas fa-file-alt"></i>
            </div>
            <div class="header-title">
                <h1>Create Purchase RFQ</h1>
                <div class="header-subtitle">Purchase Request for Quotation Form</div>
            </div>
        </div>
        <div class="datetime-display">
            <div class="date-box">
                <i class="far fa-calendar-alt"></i>
                <span id="day">{{ now()->format('l') }}</span>,
                <span id="daynum">{{ now()->format('d') }}</span>
                <span id="month">{{ now()->format('F') }}</span>
                <span id="year">{{ now()->format('Y') }}</span>
            </div>
            <div class="time-box">
                <i class="far fa-clock"></i>
                <span class="display-time"></span>
            </div>
        </div>
    </div>

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

        <!-- Section 1: RFQ Information -->
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-file-alt"></i>
                <h2>RFQ Information</h2>
            </div>
            <div class="section-body">
                <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>
            </div>
        </div>

        <!-- Section 2: Vendor Information -->
        <div class="section-card">
            <div class="section-header info">
                <i class="fas fa-building"></i>
                <h2>Vendor Information</h2>
            </div>
            <div class="section-body">
                <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>
            </div>
        </div>

        <!-- Section 3: Additional Details -->
        <div class="section-card">
            <div class="section-header warning">
                <i class="fas fa-info-circle"></i>
                <h2>Additional Details</h2>
            </div>
            <div class="section-body">
                <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>
            </div>
        </div>

        <!-- Section 4: RFQ Items -->
        <div class="section-card">
            <div class="section-header success">
                <i class="fas fa-list"></i>
                <h2>RFQ Items</h2>
            </div>
            <div class="section-body">
                <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>
            </div>
        </div>

        <!-- Section 5: Notes & Terms -->
        <div class="section-card">
            <div class="section-header secondary">
                <i class="fas fa-sticky-note"></i>
                <h2>Notes & Terms</h2>
            </div>
            <div class="section-body">
                <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>
            </div>
        </div>

        <!-- Section 6: File Attachments -->
        <div class="section-card">
            <div class="section-header danger">
                <i class="fas fa-paperclip"></i>
                <h2>File Attachments</h2>
            </div>
            <div class="section-body">
                <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>
            </div>
        </div>

        <!-- Footer Actions -->
        <div class="footer-actions">
            <a href="{{ route('superadmin.purchasebom.rfq.rfqdetails') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to List
            </a>
            <div>
                <button class="btn btn-danger" type="reset" onclick="resetForm()">
                    <i class="fas fa-undo"></i> Clear Form
                </button>
                <button class="btn btn-success" type="submit">
                    <i class="fas fa-save"></i> Save RFQ
                </button>
            </div>
        </div>

    </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>
// Dynamic Date/Time Update
function updateDateTime() {
    const now = new Date();
    const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

    document.getElementById('day').textContent = days[now.getDay()];
    document.getElementById('daynum').textContent = now.getDate();
    document.getElementById('month').textContent = months[now.getMonth()];
    document.getElementById('year').textContent = now.getFullYear();

    const timeStr = now.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
    document.querySelector('.display-time').textContent = timeStr;
}
updateDateTime();
setInterval(updateDateTime, 1000);

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

function resetForm() {
    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
