@extends('layouts.dashboard.superadminapp')
@section('title', 'SuperAdmin GRN Order')

@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 z-index override */
    .select2-container {
        background: linear-gradient(135deg, #ffffff 0%, #f0fdfa 100%);
        border-radius: 1rem;
        padding: 1.25rem 1.5rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        margin-bottom: 1.5rem;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 1rem;
    }

    .modern-page-header h1 {
        font-size: 1.25rem;
        font-weight: 600;
        color: #0f172a;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .header-right {
        display: flex;
        align-items: center;
        gap: 1.5rem;
    }

    .display-date {
        font-size: 0.875rem;
        color: #64748b;
        font-weight: 500;
    }

    .display-time {
        font-family: 'SF Mono', 'Monaco', monospace;
        background: #ecfeff;
        color: #0e7490;
        padding: 0.375rem 0.75rem;
        border-radius: 0.5rem;
        font-size: 0.875rem;
        font-weight: 600;
    }

    /* Section Cards */
    .section-card {
        background: #ffffff;
        border-radius: 1rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        margin-bottom: 1.5rem;
        overflow: hidden;
        border: 1px solid #e2e8f0;
    }

    .section-header {
        padding: 1rem 1.5rem;
        font-weight: 600;
        font-size: 1rem;
        color: #ffffff;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .section-card.teal .section-header {
        background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
    }

    .section-card.blue .section-header {
        background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    }

    .section-card.cyan .section-header {
        background: linear-gradient(135deg, #22d3ee 0%, #06b6d4 100%);
    }

    .section-card.amber .section-header {
        background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    }

    .section-card.green .section-header {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    }

    .section-card .card-body {
        padding: 1.5rem;
    }

    /* Modern Form Controls */
    .form-control {
        border: 2px solid #e2e8f0;
        border-radius: 0.5rem;
        padding: 0.625rem 1rem;
        font-size: 0.875rem;
        transition: all 0.2s;
        background: #f8fafc;
    }

    .form-control:hover {
        border-color: #cbd5e1;
    }

    .form-control:focus {
        border-color: #06b6d4;
        box-shadow: 0 0 0 3px rgba(6, 182, 212, 0.1);
        background: #ffffff;
        outline: none;
    }

    .form-control[readonly] {
        background: #f1f5f9;
        color: #64748b;
        cursor: not-allowed;
    }

    label {
        font-weight: 500;
        color: #475569;
        margin-bottom: 0.5rem;
        font-size: 0.875rem;
        display: block;
    }

    label .text-danger {
        color: #ef4444;
        margin-left: 0.25rem;
    }

    /* Enhanced Table */
    .table-responsive {
        border-radius: 0.75rem;
        overflow: hidden;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        margin-bottom: 1rem;
    }

    #productTable {
        margin-bottom: 0;
    }

    #productTable thead th {
        background: linear-gradient(135deg, #f0fdfa 0%, #ccfbf1 100%);
        border-bottom: 2px solid #06b6d4;
        color: #0e7490;
        font-weight: 600;
        text-transform: uppercase;
        font-size: 0.75rem;
        letter-spacing: 0.5px;
        padding: 1rem;
        white-space: nowrap;
    }

    #productTable tbody tr {
        transition: all 0.15s;
    }

    #productTable tbody tr:hover {
        background: #f0fdfa;
    }

    #productTable tbody td {
        padding: 0.75rem;
        vertical-align: middle;
        border-bottom: 1px solid #e2e8f0;
    }

    #productTable input.form-control {
        padding: 0.375rem 0.625rem;
        font-size: 0.875rem;
        min-height: 38px;
    }

    /* Modern Buttons */
    .btn {
        border-radius: 0.5rem;
        padding: 0.625rem 1.25rem;
        font-weight: 500;
        transition: all 0.2s;
        border: none;
        font-size: 0.875rem;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
    }

    .btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    }

    .btn-primary {
        background: linear-gradient(135deg, #06b6d4 0%, #0891b2 100%);
        color: #ffffff;
    }

    .btn-primary:hover {
        background: linear-gradient(135deg, #0891b2 0%, #0e7490 100%);
        box-shadow: 0 4px 12px rgba(6, 182, 212, 0.4);
    }

    .btn-success {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: #ffffff;
    }

    .btn-success:hover {
        background: linear-gradient(135deg, #059669 0%, #047857 100%);
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.4);
    }

    .btn-danger {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        color: #ffffff;
    }

    .btn-danger:hover {
        background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
        box-shadow: 0 4px 12px rgba(239, 68, 68, 0.4);
    }

    .btn-secondary {
        background: linear-gradient(135deg, #64748b 0%, #475569 100%);
        color: #ffffff;
    }

    .btn-outline-secondary {
        background: transparent;
        border: 2px solid #cbd5e1;
        color: #64748b;
    }

    .btn-outline-secondary:hover {
        background: #f8fafc;
        border-color: #94a3b8;
        color: #475569;
    }

    .btn-light {
        background: #ffffff;
        color: #06b6d4;
        border: 2px solid #06b6d4;
    }

    .btn-light:hover {
        background: #06b6d4;
        color: #ffffff;
    }

    .btn-sm {
        padding: 0.375rem 0.875rem;
        font-size: 0.8125rem;
    }

    /* Select2 Enhancement */
    .select2-container .select2-selection--single {
        height: 38px;
        border: 2px solid #e2e8f0;
        border-radius: 0.5rem;
        background: #f8fafc;
    }

    .select2-container--default .select2-selection--single .select2-selection__rendered {
        line-height: 34px;
        color: #1e293b;
    }

    .select2-container--default .select2-selection--single .select2-selection__arrow {
        height: 34px;
    }

    .select2-container--default.select2-container--focus .select2-selection--single {
        border-color: #06b6d4;
        box-shadow: 0 0 0 3px rgba(6, 182, 212, 0.1);
    }

    /* Invoice Details Box */
    #purchaseInvoiceDetails {
        background: linear-gradient(135deg, #f0fdfa 0%, #ccfbf1 100%);
        border: 2px solid #06b6d4;
        border-radius: 0.5rem;
        padding: 0.875rem;
        min-height: 38px;
        font-size: 0.875rem;
        color: #0e7490;
    }

    /* Toast Notifications */
    .toast-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
    }

    .toast {
        background: #ffffff;
        border-radius: 0.75rem;
        box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        padding: 1rem 1.25rem;
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        min-width: 300px;
        animation: slideIn 0.3s ease;
        border-left: 4px solid;
    }

    .toast.success {
        border-left-color: #10b981;
    }

    .toast.error {
        border-left-color: #ef4444;
    }

    .toast-icon {
        font-size: 1.25rem;
    }

    .toast.success .toast-icon {
        color: #10b981;
    }

    .toast.error .toast-icon {
        color: #ef4444;
    }

    .toast-message {
        flex: 1;
        color: #1e293b;
        font-size: 0.875rem;
    }

    .toast-close {
        background: none;
        border: none;
        color: #94a3b8;
        cursor: pointer;
        padding: 0;
        font-size: 1.25rem;
        line-height: 1;
    }

    @keyframes slideIn {
        from {
            transform: translateX(400px);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }

    /* Responsive */
    @media (max-width: 768px) {
        .modern-page-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .header-right {
            width: 100%;
            justify-content: space-between;
        }
    }
</style>
@endsection

@section('content')

<!-- Toast Container -->
<div class="toast-container" id="toastContainer"></div>

{{-- Modern Page Header Component --}}
<x-modern-ui.page-header
    title="Create Goods Received Note"
    subtitle="Goods Receipt Note Registration Form"
    icon="clipboard-check"
    theme="teal"
/>

<form method="POST" action="{{ route('superadmin.grn.store') }}" enctype="multipart/form-data" id="grnForm">
    @csrf

    {{-- Section 1: GRN Information --}}
    <x-modern-ui.section-card
        title="GRN Information"
        icon="file-alt"
        theme="teal"
    >
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label>GRN ID <span class="text-danger">*</span></label>
                    <input type="text" id="grnNo" name="grn_no" class="form-control" value="{{ $grnNo }}" readonly>
                </div>
                <div class="col-md-3 mb-3">
                    <label>GRN Date <span class="text-danger">*</span></label>
                    <input type="date" id="grnDate" name="grn_date" class="form-control" required>
                </div>
                <div class="col-md-3 mb-3">
                    <label>
                        <i class="fas fa-file-invoice text-primary mr-1"></i>
                        Purchase Invoice
                    </label>
                    <select id="purchaseInvoiceSelect" name="purchase_invoice_id" class="form-control">
                        <option value="">Select Purchase Invoice</option>
                    </select>
                    <small class="text-muted">Optional: Auto-fill from invoice</small>
                </div>
                <div class="col-md-3 mb-3">
                    <label>Invoice Details</label>
                    <div id="purchaseInvoiceDetails">
                        Select invoice to view details
                    </div>
                </div>
            </div>
    </x-modern-ui.section-card>

    {{-- Section 2: Order Details --}}
    <x-modern-ui.section-card
        title="Order Details"
        icon="shopping-cart"
        theme="info"
    >
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label>Order Type</label>
                    <select id="orderTypeSelect" class="form-control">
                        <option value="">Select Type (Optional)</option>
                        <option value="purchase">Purchase Order</option>
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label>Order ID</label>
                    <select id="orderNoSelect" name="order_no" class="form-control">
                        <option value="">Select Order (Optional)</option>
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label>Order Date</label>
                    <input type="date" id="orderDate" name="order_date" class="form-control" readonly>
                </div>
                <div class="col-md-3 mb-3">
                    <label>Order Reference No</label>
                    <input type="text" id="orderRefNo" name="order_ref_no" class="form-control">
                </div>
            </div>
    </x-modern-ui.section-card>

    {{-- Section 3: Company/Vendor Details --}}
    <x-modern-ui.section-card
        title="Company/Vendor Details"
        icon="building"
        theme="warning"
    >
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label>Order Company Name <span class="text-danger">*</span></label>
                    <select id="companyNameSelect" name="company_name" class="form-control" required onchange="fillCompanyDetails(this)">
                        <option value="">Select Company</option>
                        @foreach ($companies as $company)
                            <option value="{{ $company->company }}"
                                data-address="{{ $company->billing_address }}"
                                data-gst="{{ $company->gstno }}"
                                data-email="{{ $company->email }}"
                                data-phone="{{ $company->mobile }}">
                                {{ $company->company }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-6 mb-3">
                    <label>Address</label>
                    <input type="text" id="companyAddress" name="company_address" class="form-control">
                </div>
            </div>

            <div class="row">
                <div class="col-md-3 mb-3">
                    <label>GST No</label>
                    <input type="text" id="companyGSTN" name="company_gstn" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Email</label>
                    <input type="email" id="companyEmail" name="company_email" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Contact Number</label>
                    <input type="tel" id="companyPhone" name="company_phone" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Upload Challan (PDF)</label>
                    <input type="file" id="grnChallan" name="challan" accept=".pdf" class="form-control">
                </div>
            </div>
    </x-modern-ui.section-card>

    {{-- Section 4: Additional References --}}
    <x-modern-ui.section-card
        title="Additional References"
        icon="tags"
        theme="secondary"
    >
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label>Quotation ID</label>
                    <input type="text" id="quotationNo" name="quotation_no" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Quotation Date</label>
                    <input type="date" id="quotationDate" name="quotation_date" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label>RFQ No</label>
                    <input type="text" id="rfqNo" name="rfq_no" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label>RFQ Date</label>
                    <input type="date" id="rfqDate" name="rfq_date" class="form-control">
                </div>
            </div>

            <div class="row">
                <div class="col-md-3 mb-3">
                    <label>Part No</label>
                    <input type="text" id="partNo" name="part_no" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Project Material No</label>
                    <input type="text" id="project-materialNo" name="project_material_no" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Drawing No</label>
                    <input type="text" id="drawingNo" name="drawing_no" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label>Drawing Revision</label>
                    <input type="text" id="drawingRev" name="drawing_rev" class="form-control">
                </div>
            </div>

            <div class="row">
                <div class="col-md-12 mb-3">
                    <label>Description</label>
                    <textarea id="description" name="description" rows="2" class="form-control"></textarea>
                </div>
            </div>
    </x-modern-ui.section-card>

    {{-- Section 5: Product Details --}}
    <x-modern-ui.section-card
        title="Product Details"
        icon="boxes"
        theme="success"
    >
            <div class="row mb-3">
                <div class="col-md-4">
                    <label>Product Type</label>
                    <input type="text" id="productType" name="product_type" class="form-control">
                </div>
            </div>

            <div class="table-responsive">
                <table id="productTable" class="table table-bordered table-sm">
                    <thead>
                        <tr>
                            <th width="50">Sl No.</th>
                            <th>Description</th>
                            <th width="100">Quantity</th>
                            <th width="80">UOM</th>
                            <th width="130">Date</th>
                            <th>Supplier</th>
                            <th>Remarks</th>
                            <th width="50"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>1</td>
                            <td>
                                <select name="products[0][description]" class="description form-control stock-item-select" style="width: 100%;" required>
                                    <option value="">Search or type...</option>
                                </select>
                                <input type="hidden" name="products[0][stock_item_id]" class="stock-item-id">
                            </td>
                            <td><input type="number" name="products[0][quantity]" class="quantity form-control" required></td>
                            <td><input type="text" name="products[0][unit]" class="unit form-control" required></td>
                            <td><input type="date" name="products[0][date]" class="date form-control" required></td>
                            <td><input type="text" name="products[0][supplier]" class="supplier form-control"></td>
                            <td><input type="text" name="products[0][remarks]" class="remarks form-control"></td>
                            <td><button class="btn btn-danger btn-sm" type="button" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="mb-3">
                <button type="button" class="btn btn-primary btn-sm" onclick="addRow()">
                    <i class="fa fa-plus"></i> Add Row
                </button>
            </div>
    </x-modern-ui.section-card>

    {{-- Footer Actions Component --}}
    <x-modern-ui.footer-actions
        backUrl="{{ route('superadmin.grn.grndetails') }}"
        backText="Back to List"
        submitText="Save GRN"
        submitIcon="save"
        submitId="save-GRN"
        :showClear="true"
        clearText="Clear Form"
    />
</form>

@endsection

@section('scripts')
<script>
// Toast Notification Function
function showToast(message, type = 'success') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} toast-icon"></i>
        <div class="toast-message">${message}</div>
        <button class="toast-close" onclick="this.parentElement.remove()">&times;</button>
    `;
    container.appendChild(toast);
    setTimeout(() => toast.remove(), 5000);
}

// Live Clock Update
function updateTime() {
    const el = document.getElementById('current-time');
    if (!el) return;
    const now = new Date();
    const timeString = now.toLocaleTimeString('en-US', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: true
    });
    el.textContent = timeString;
}
setInterval(updateTime, 1000);

// Show session messages as toasts
@if(session('success'))
    showToast("{{ session('success') }}", 'success');
@endif
@if(session('error'))
    showToast("{{ session('error') }}", 'error');
@endif
@if($errors->any())
    @foreach($errors->all() as $error)
        showToast("{{ $error }}", 'error');
    @endforeach
@endif

document.addEventListener('DOMContentLoaded', function () {
    // Set GRN date to today
    document.getElementById('grnDate').value = new Date().toISOString().split('T')[0];

    let ordersData = [];

    // When order type changes, load orders
    document.getElementById('orderTypeSelect').addEventListener('change', function () {
        const type = this.value;
        loadOrderDropdown(type);
    });

    // When order is selected, autofill details
    document.getElementById('orderNoSelect').addEventListener('change', function () {
        const orderNo = this.value;
        const type = document.getElementById('orderTypeSelect').value;
        if (!orderNo || !type) return;
        fetch("{{ url('superadmin/grn/order-details') }}?type=" + type + "&order_no=" + orderNo)
            .then(r => r.json())
            .then(order => {
                if (order.error) return;
                document.getElementById('orderDate').value = (type === 'sales' ? order.sales_order_date : order.purchase_order_date) || '';
                // Auto-fill company/vendor/customer details
                if (type === 'sales' && order.customer) {
                    document.getElementById('companyNameSelect').value = order.customer.company || '';
                    document.getElementById('companyAddress').value = order.company_address || '';
                    document.getElementById('companyGSTN').value = order.customer.gstno || '';
                    document.getElementById('companyEmail').value = order.customer.email || '';
                    document.getElementById('companyPhone').value = order.customer.mobile || '';
                } else if (type === 'purchase' && order.vendor) {
                    document.getElementById('companyNameSelect').value = order.vendor.company || '';
                    document.getElementById('companyAddress').value = order.company_address || '';
                    document.getElementById('companyGSTN').value = order.company_gstn || '';
                    document.getElementById('companyEmail').value = order.company_email || '';
                    document.getElementById('companyPhone').value = order.company_phone || '';
                }
                document.getElementById('orderRefNo').value = order.customer_ref_no || '';
                document.getElementById('quotationNo').value = order.quotation_no || '';
                document.getElementById('quotationDate').value = order.quotation_date || '';
                document.getElementById('rfqNo').value = order.rfq_no || '';
                document.getElementById('rfqDate').value = order.rfq_date || '';
                document.getElementById('partNo').value = order.part_no || '';
                document.getElementById('project-materialNo').value = order.project_material_no || '';
                document.getElementById('drawingNo').value = order.drawing_no || '';
                document.getElementById('drawingRev').value = order.drawing_rev || '';
                document.getElementById('description').value = order.description || '';
                document.getElementById('productType').value = order.product_type || '';
            });
    });

    function loadOrderDropdown(type) {
        if (!type) {
            document.getElementById('orderNoSelect').innerHTML = '<option value="">Select Order</option>';
            return;
        }
        fetch("{{ url('superadmin/grn/available-orders') }}")
            .then(r => r.json())
            .then(data => {
                ordersData = data;
                const options = data
                    .filter(o => o.order_type === type)
                    .map(o => `<option value="${o.order_no}">${o.order_no}</option>`);
                document.getElementById('orderNoSelect').innerHTML =
                    '<option value="">Select Order</option>' + options.join('');
            });
    }

    // Load available Purchase Invoices
    loadPurchaseInvoices();

    function loadPurchaseInvoices() {
        fetch("{{ url('superadmin/grn/available-purchase-invoices') }}")
            .then(r => r.json())
            .then(data => {
                const options = data.map(inv =>
                    `<option value="${inv.id}" data-vendor="${inv.vendor_name}" data-total="${inv.grand_total}">
                        ${inv.purchase_no} - ${inv.vendor_name} (${inv.vendor_invoice_no || 'N/A'})
                    </option>`
                );
                document.getElementById('purchaseInvoiceSelect').innerHTML =
                    '<option value="">Select Purchase Invoice</option>' + options.join('');
            });
    }

    // Handle Purchase Invoice selection
    document.getElementById('purchaseInvoiceSelect').addEventListener('change', function() {
        const invoiceId = this.value;
        if (!invoiceId) {
            document.getElementById('purchaseInvoiceDetails').innerHTML = 'Select invoice to view details';
            return;
        }

        fetch("{{ url('superadmin/grn/purchase-invoice-details') }}/" + invoiceId)
            .then(r => r.json())
            .then(data => {
                if (!data.success) {
                    document.getElementById('purchaseInvoiceDetails').innerHTML = 'Error loading invoice details';
                    return;
                }

                const inv = data.invoice;
                // Display invoice summary
                document.getElementById('purchaseInvoiceDetails').innerHTML =
                    `<strong>${inv.purchase_no}</strong><br>` +
                    `Vendor: ${inv.party ? inv.party.company : 'N/A'}<br>` +
                    `Date: ${inv.purchase_date}<br>` +
                    `Total: ₹${parseFloat(inv.grand_total || 0).toLocaleString('en-IN', {minimumFractionDigits: 2})}`;

                // Auto-fill company details from purchase invoice
                if (inv.party) {
                    // Try to select the company in the dropdown
                    const companySelect = document.getElementById('companyNameSelect');
                    for (let i = 0; i < companySelect.options.length; i++) {
                        if (companySelect.options[i].value === inv.party.company) {
                            companySelect.selectedIndex = i;
                            fillCompanyDetails(companySelect);
                            break;
                        }
                    }
                }

                // Auto-fill product details if available
                if (data.items && data.items.length > 0) {
                    const tableBody = document.querySelector("#productTable tbody");
                    // Clear existing rows
                    tableBody.innerHTML = '';

                    data.items.forEach((item, index) => {
                        const row = document.createElement("tr");
                        row.innerHTML = `
                            <td>${index + 1}</td>
                            <td><input type="text" name="products[${index}][description]" class="description form-control" value="${item.description || ''}"></td>
                            <td><input type="number" name="products[${index}][quantity]" class="quantity form-control" value="${item.quantity || ''}"></td>
                            <td><input type="text" name="products[${index}][unit]" class="unit form-control" value="${item.unit || 'Nos'}"></td>
                            <td><input type="date" name="products[${index}][date]" class="date form-control" value="${new Date().toISOString().split('T')[0]}"></td>
                            <td><input type="text" name="products[${index}][supplier]" class="supplier form-control"></td>
                            <td><input type="text" name="products[${index}][remarks]" class="remarks form-control"></td>
                            <td><button class="btn btn-danger btn-sm" type="button" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
                        `;
                        tableBody.appendChild(row);
                    });
                }
            })
            .catch(err => {
                console.error('Error loading invoice details:', err);
                document.getElementById('purchaseInvoiceDetails').innerHTML = 'Error loading invoice details';
            });
    });
});

function addRow() {
    const table = document.querySelector("#productTable tbody");
    const index = table.rows.length;
    const row = document.createElement("tr");
    row.innerHTML = `
        <td>${index + 1}</td>
        <td>
            <select name="products[${index}][description]" class="description form-control stock-item-select" style="width: 100%;" required>
                <option value="">Search or type...</option>
            </select>
            <input type="hidden" name="products[${index}][stock_item_id]" class="stock-item-id">
        </td>
        <td><input type="number" name="products[${index}][quantity]" class="quantity form-control" required></td>
        <td><input type="text" name="products[${index}][unit]" class="unit form-control" required></td>
        <td><input type="date" name="products[${index}][date]" class="date form-control" required></td>
        <td><input type="text" name="products[${index}][supplier]" class="supplier form-control"></td>
        <td><input type="text" name="products[${index}][remarks]" class="remarks form-control"></td>
        <td><button class="btn btn-danger btn-sm" type="button" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
    `;
    table.appendChild(row);
    // Initialize Select2 on the new row
    initStockItemSelect(row.querySelector('.stock-item-select'));
}

function deleteRow(button) {
    const row = button.closest("tr");
    row.remove();
    // Re-index remaining rows
    const rows = document.querySelectorAll("#productTable tbody tr");
    rows.forEach((tr, i) => {
        tr.querySelectorAll("input, select").forEach(input => {
            const name = input.name.replace(/products\[\d+\]/, `products[${i}]`);
            input.name = name;
        });
        tr.querySelector("td").textContent = i + 1;
    });
}

function fillCompanyDetails(select) {
    const selected = select.options[select.selectedIndex];
    document.getElementById('companyAddress').value = selected.getAttribute('data-address') || '';
    document.getElementById('companyGSTN').value = selected.getAttribute('data-gst') || '';
    document.getElementById('companyEmail').value = selected.getAttribute('data-email') || '';
    document.getElementById('companyPhone').value = selected.getAttribute('data-phone') || '';
}

// Initialize Select2 for Stock Item dropdown with search capability
function initStockItemSelect(element) {
    $(element).select2({
        placeholder: 'Search stock item...',
        allowClear: true,
        tags: true, // Allow custom values
        createTag: function (params) {
            return {
                id: params.term,
                text: params.term,
                newTag: true
            };
        },
        ajax: {
            url: "{{ url('superadmin/grn/search-stock-items') }}",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return { q: params.term };
            },
            processResults: function (data) {
                return { results: data.results };
            },
            cache: true
        },
        minimumInputLength: 0,
        width: '100%'
    }).on('select2:select', function (e) {
        // Auto-fill UOM and stock_item_id when stock item is selected
        var data = e.params.data;
        var row = $(this).closest('tr');
        if (data.uom) {
            row.find('.unit').val(data.uom);
        }
        // Set stock_item_id if it's an existing stock item (not a custom tag)
        if (data.stock_item_id) {
            row.find('.stock-item-id').val(data.stock_item_id);
        } else {
            row.find('.stock-item-id').val('');
        }
    }).on('select2:clear', function (e) {
        var row = $(this).closest('tr');
        row.find('.stock-item-id').val('');
    });
}

// Initialize all existing stock item selects on page load
$(document).ready(function() {
    $('.stock-item-select').each(function() {
        initStockItemSelect(this);
    });
});
</script>
@endsection
