@extends('layouts.dashboard.superadminapp')
@section('title', 'Edit Purchase Order')

@section('styles')
<link rel="stylesheet" href="{{ asset('css/modern-form-pattern.css') }}">
<!-- DataTables Bootstrap 5 styling for buttons -->
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<!-- Bootstrap Select CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/css/bootstrap-select.min.css">
<style>
    /* Summary Section */
    .total-fields .row {
        margin-bottom: 0.75rem;
    }

    .total-fields label {
        font-weight: 600;
        color: #475569;
        display: flex;
        align-items: center;
        margin-bottom: 0;
    }

    .total-fields input {
        font-weight: 600;
        background: #f8fafc;
        border: 2px solid #e2e8f0;
    }

    .total-fields .row:last-child input {
        background: linear-gradient(135deg, #ecfeff 0%, #cffafe 100%);
        border-color: #06b6d4;
        color: #0e7490;
        font-size: 1.1rem;
    }

    /* Toast Notification */
    #toastContainer {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
    }

    .toast {
        background: white;
        border-radius: 8px;
        padding: 1rem 1.25rem;
        margin-bottom: 0.75rem;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        display: flex;
        align-items: center;
        gap: 0.75rem;
        min-width: 300px;
        animation: slideIn 0.3s ease;
    }

    .toast.success {
        border-left: 4px solid #10b981;
    }

    .toast.error {
        border-left: 4px solid #ef4444;
    }

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

    .toast.success i {
        color: #10b981;
    }

    .toast.error i {
        color: #ef4444;
    }

    @keyframes slideIn {
        from {
            transform: translateX(400px);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
</style>
@endsection

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

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

    <!-- Modern Page Header -->
    <div class="modern-page-header">
        <div class="header-left">
            <div class="icon-wrapper">
                <i class="fas fa-edit"></i>
            </div>
            <div class="header-title">
                <h1>Edit Purchase Order</h1>
                <div class="header-subtitle">{{ $po->purchase_order_no }}</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>

    <!-- Form -->
    <form id="soForm" method="POST" action="{{ route('superadmin.purchase.order.update', $po->id) }}" enctype="multipart/form-data">
        @csrf
        @method('PUT')
        <input type="hidden" id="editOrderId" value="{{ $po->id }}">
        <input type="hidden" id="tableProducts" name="tableProducts">

        <!-- PO Information Section -->
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-file-invoice"></i>
                <h2>Purchase Order Information</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Purchase Order No.</label>
                        <input type="text" id="sOrderNo" name="soNo1" value="{{ $po->purchase_order_no }}" readonly class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Quotation ID</label>
                        <input type="text" id="quotationSelect" name="quotationId" value="{{ $po->quotation_no }}" class="form-control">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Purchase Date</label>
                        <input type="date" id="sOrderDate" name="soDate" value="{{ $po->purchase_order_date }}" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Quotation Date</label>
                        <input type="date" id="quotationDate" name="quotationDate" value="{{ $po->quotation_date }}" class="form-control">
                    </div>
                </div>
            </div>
        </div>

        <!-- Vendor Details Section -->
        <div class="section-card">
            <div class="section-header info">
                <i class="fas fa-building"></i>
                <h2>Vendor Details</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Vendor Company Name</label>
                        <input type="text" id="soCompanyName" name="soCompanyName" value="{{ optional($po->vendor)->company ?? $po->company_name }}" class="form-control">
                        <input type="hidden" id="soCompanyId" name="soCompanyId" value="{{ optional($po->vendor)->id ?? $po->vendor_id }}">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Vendor Reference No.</label>
                        <input type="text" id="custRefNo" name="custRefNo" value="{{ $po->customer_ref_no }}" class="form-control">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Address</label>
                        <input type="text" id="soCompanyAddress" name="soCompanyAddress" value="{{ $po->company_address }}" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">GSTN</label>
                        <input type="text" id="soCompanyGSTN" name="soCompanyGSTN" value="{{ $po->company_gstn }}" class="form-control">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Phone</label>
                        <input type="tel" id="soCompanyPhone" name="soCompanyPhone" value="{{ $po->company_phone }}" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" id="soCompanyEmail" name="soCompanyEmail" value="{{ $po->company_email }}" class="form-control">
                    </div>
                </div>
            </div>
        </div>

        <!-- Reference Information Section -->
        <div class="section-card">
            <div class="section-header warning">
                <i class="fas fa-info-circle"></i>
                <h2>Reference Information</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label for="rfqNo" class="form-label">RFQ No</label>
                        <input type="text" id="rfqNo" name="rfqNo" value="{{ $po->rfq_no }}" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="rfqDate" class="form-label">RFQ Date</label>
                        <input type="date" id="rfqDate" name="rfqDate" value="{{ $po->rfq_date }}" class="form-control">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label for="projectDescription" class="form-label">Note Ⅰ</label>
                        <input type="text" id="projectDescription" name="projectDescription" value="{{ $po->description }}" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="deliveryTerms" class="form-label">Delivery Terms</label>
                        <input type="text" id="deliveryTerms" name="deliveryTerms" value="{{ $po->delivery_terms }}" class="form-control" placeholder="Delivery Terms">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label for="additionalCharges" class="form-label">Additional Charges</label>
                        <input type="text" id="additionalCharges" name="additionalCharges" value="{{ $po->additional_charges }}" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="note" class="form-label">Note ⅠⅠ</label>
                        <textarea id="note" name="note" rows="2" class="form-control">{{ $po->note }}</textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- Addresses Section -->
        <div class="section-card">
            <div class="section-header secondary">
                <i class="fas fa-map-marker-alt"></i>
                <h2>Billing & Shipping Addresses</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Bill To</label>
                        <textarea name="billAddress" id="billAddress" rows="3" class="form-control">{{ $po->bill_address }}</textarea>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Ship To</label>
                        <textarea name="shipAddress" id="shipAddress" rows="3" class="form-control">{{ $po->ship_address }}</textarea>
                    </div>
                </div>
            </div>
        </div>

        <!-- Product Details Section -->
        <div class="section-card">
            <div class="section-header success">
                <i class="fas fa-boxes"></i>
                <h2>Product Details</h2>
            </div>
            <div class="section-body">
                <div style="overflow-x: auto; width: 100%;">
                    <table id="productTable" class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Sl No.</th>
                                <th>Item</th>
                                <th>Description</th>
                                <th>Req By Date</th>
                                <th>Quantity</th>
                                <th>UOM</th>
                                <th>Unit Rate (INR)</th>
                                <th>TDS (%)</th>
                                <th>Discount (%)</th>
                                <th>Value (INR)</th>
                                <th>SGST (%)</th>
                                <th>CGST (%)</th>
                                <th>IGST (%)</th>
                                <th>Amount (INR)</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($po->items as $index => $item)
                            <tr>
                                <td>{{ $loop->iteration }}</td>
                                <td>
                                    <select class="form-select item-select w-100" name="item[]" required>
                                        <option value="">Select Item</option>
                                        @foreach ($stock_items as $stock)
                                            <option value="{{ $stock->id }}" {{ $stock->id == $item->item ? 'selected' : '' }}>
                                                {{ $stock->item_name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </td>
                                <td>
                                    <input type="text" name="description[]" value="{{ $item->description }}" placeholder="Description" class="form-control" />
                                </td>
                                <td>
                                    <input type="date" name="req_by_date[]" value="{{ $item->req_by_date }}" placeholder="Select date" class="form-control" />
                                </td>
                                <td>
                                    <input type="number" name="quantity[]" value="{{ $item->quantity }}" step="1" min="0" placeholder="Qty" class="form-control" />
                                </td>
                                <td>
                                    <input type="text" name="uom[]" value="{{ $item->uom }}" placeholder="UOM" class="form-control" />
                                </td>
                                <td>
                                    <input type="number" name="unit_rate[]" value="{{ $item->unit_rate }}" step="0.01" placeholder="Rate" class="form-control" />
                                </td>
                                <td>
                                    <input type="number" name="tds[]" value="{{ $item->tds }}" step="0.01" placeholder="TDS %" class="form-control" />
                                </td>
                                <td>
                                    <input type="number" name="discount[]" value="{{ $item->discount }}" step="0.01" placeholder="Discount %" class="form-control" />
                                </td>
                                <td>
                                    <input type="number" name="value[]" value="{{ $item->value }}" step="0.01" placeholder="Value" class="form-control" readonly />
                                </td>
                                <td>
                                    <input type="number" name="sgst[]" value="{{ $item->sgst }}" step="0.01" placeholder="SGST %" class="form-control" />
                                </td>
                                <td>
                                    <input type="number" name="cgst[]" value="{{ $item->cgst }}" step="0.01" placeholder="CGST %" class="form-control" />
                                </td>
                                <td>
                                    <input type="number" name="igst[]" value="{{ $item->igst }}" step="0.01" placeholder="IGST %" class="form-control" />
                                </td>
                                <td>
                                    <input type="number" name="amount[]" value="{{ $item->amount }}" step="0.01" placeholder="Amount" class="form-control" readonly />
                                </td>
                                <td>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                            @endforeach
                        </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>

        <!-- Summary Section -->
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-calculator"></i>
                <h2>Order Summary</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label for="inr_in_words" class="form-label">Grand Total in Words (INR)</label>
                        <input type="text" id="inr_in_words" name="inr_in_words" value="{{ $po->inr_in_words }}" readonly class="form-control" style="font-weight: 600; color: #0e7490;">
                    </div>
                    <div class="col-md-6 total-fields">
                        <div class="row">
                            <label class="col-md-4">SUB TOTAL</label>
                            <div class="col-md-8"><input type="text" id="totalAmount" name="totalAmount" value="{{ $po->subtotal }}" readonly class="form-control" style="text-align: right;"></div>
                        </div>
                        <div class="row">
                            <label class="col-md-4">SGST</label>
                            <div class="col-md-8"><input type="text" id="sgstA" name="sgstA" value="{{ $po->sgst_amount }}" readonly class="form-control" style="text-align: right;"></div>
                        </div>
                        <div class="row">
                            <label class="col-md-4">CGST</label>
                            <div class="col-md-8"><input type="text" id="cgstA" name="cgstA" value="{{ $po->cgst_amount }}" readonly class="form-control" style="text-align: right;"></div>
                        </div>
                        <div class="row">
                            <label class="col-md-4">IGST</label>
                            <div class="col-md-8"><input type="text" id="IgstA" name="IgstA" value="{{ $po->igst_amount }}" readonly class="form-control" style="text-align: right;"></div>
                        </div>
                        <div class="row">
                            <label class="col-md-4">Round Up</label>
                            <div class="col-md-8"><input type="text" id="roundUp" name="roundUp" value="{{ $po->round_up }}" readonly class="form-control" style="text-align: right;"></div>
                        </div>
                        <div class="row">
                            <label class="col-md-4">Grand Total</label>
                            <div class="col-md-8"><input type="text" id="grandTotal" name="grandTotal" value="{{ $po->grand_total }}" readonly class="form-control" style="text-align: right;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer Actions -->
        <div class="footer-actions">
            <a href="{{ route('superadmin.purchase.purchasedetails') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to List
            </a>
            <div>
                <button class="btn btn-success" type="submit">
                    <i class="fas fa-save"></i> Update Purchase Order
                </button>
            </div>
        </div>
    </form>

</div>
@endsection

@section('scripts')
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <!-- Load jQuery FIRST -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

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

    <!-- Bootstrap JS (required by Bootstrap Select) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <!-- Bootstrap Select JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta3/dist/js/bootstrap-select.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);

        // Toast Notification Function
        function showToast(message, type = 'success') {
            const container = document.getElementById('toastContainer');
            const toast = document.createElement('div');
            toast.className = `toast ${type}`;

            const icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
            toast.innerHTML = `
                <i class="fas ${icon}"></i>
                <span>${message}</span>
            `;

            container.appendChild(toast);

            setTimeout(() => {
                toast.style.animation = 'slideOut 0.3s ease';
                setTimeout(() => toast.remove(), 300);
            }, 5000);
        }

        // Show session messages as toasts
        @if (session('success'))
            showToast("{{ session('success') }}", 'success');
        @endif

        @if (session('error'))
            showToast("{{ session('error') }}", 'error');
        @endif

        const stockItems = @json($stock_items);
        const poItems = @json($po->items);

        $(document).ready(function () {
            initializeSelect2();

            // Apply selected values explicitly from JSON (ensures correctness)
            poItems.forEach((item, index) => {
                const select = $(`select[name='item[]']`).eq(index);

                if (select.length) {
                    select.val(String(item.item)).trigger('change.select2');
                }
            });
        });

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

        function convertNumberToWords(num) {
            var a = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
                'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'];
            var b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];

            if ((num = num.toString()).length > 9) return 'Overflow';
            if (parseInt(num) === 0) return 'Zero';

            num = ('000000000' + num).substr(-9);
            var n = [
                parseInt(num.substr(0, 2), 10), // crore
                parseInt(num.substr(2, 2), 10), // lakh
                parseInt(num.substr(4, 2), 10), // thousand
                parseInt(num.substr(6, 1), 10), // hundred
                parseInt(num.substr(7, 2), 10)  // rest
            ];

            var str = '';
            if (n[0]) str += (n[0] < 20 ? a[n[0]] : b[Math.floor(n[0] / 10)] + ' ' + a[n[0] % 10]) + ' crore ';
            if (n[1]) str += (n[1] < 20 ? a[n[1]] : b[Math.floor(n[1] / 10)] + ' ' + a[n[1] % 10]) + ' lakh ';
            if (n[2]) str += (n[2] < 20 ? a[n[2]] : b[Math.floor(n[2] / 10)] + ' ' + a[n[2] % 10]) + ' thousand ';
            if (n[3]) str += a[n[3]] + ' hundred ';
            if (n[4]) str += (str !== '' ? 'and ' : '') + (n[4] < 20 ? a[n[4]] : b[Math.floor(n[4] / 10)] + ' ' + a[n[4] % 10]);

            return str.replace(/\s+/g, ' ').trim().replace(/^\w/, c => c.toUpperCase());
        }

        function calculateRowValue(row) {
            const quantity = parseFloat(row.querySelector('[name="quantity[]"]').value) || 0;
            const rate = parseFloat(row.querySelector('[name="unit_rate[]"]').value) || 0;
            const discount = parseFloat(row.querySelector('[name="discount[]"]').value) || 0;
            const sgst = parseFloat(row.querySelector('[name="sgst[]"]').value) || 0;
            const cgst = parseFloat(row.querySelector('[name="cgst[]"]').value) || 0;
            const igst = parseFloat(row.querySelector('[name="igst[]"]').value) || 0;
            const tds = parseFloat(row.querySelector('[name="tds[]"]').value) || 0;

            // Base after discount
            const base = quantity * rate * (1 - discount / 100);
            const gstTotal = base * (sgst + cgst + igst) / 100;
            const tdsAmount = base * (tds / 100);

            const total = base + gstTotal - tdsAmount;

            row.querySelector('[name="value[]"]').value = base.toFixed(2);
            row.querySelector('[name="amount[]"]').value = total.toFixed(2);

            calculateAllTotals();
        }

        function calculateAllTotals() {
            let subtotal = 0, sgstTotal = 0, cgstTotal = 0, igstTotal = 0, tdsTotal = 0;

            document.querySelectorAll("#productTable tbody tr").forEach(row => {
                const value = parseFloat(row.querySelector('[name="value[]"]').value) || 0;
                const sgst = parseFloat(row.querySelector('[name="sgst[]"]').value) || 0;
                const cgst = parseFloat(row.querySelector('[name="cgst[]"]').value) || 0;
                const igst = parseFloat(row.querySelector('[name="igst[]"]').value) || 0;
                const tds = parseFloat(row.querySelector('[name="tds[]"]').value) || 0;

                subtotal += value;
                sgstTotal += value * sgst / 100;
                cgstTotal += value * cgst / 100;
                igstTotal += value * igst / 100;
                tdsTotal += value * tds / 100;
            });

            const rawGrand = subtotal + sgstTotal + cgstTotal + igstTotal - tdsTotal;
            const round = Math.ceil(rawGrand) - rawGrand;
            const grand = rawGrand + round;

            document.getElementById("totalAmount").value = subtotal.toFixed(2);
            document.getElementById("sgstA").value = sgstTotal.toFixed(2);
            document.getElementById("cgstA").value = cgstTotal.toFixed(2);
            document.getElementById("IgstA").value = igstTotal.toFixed(2);
            document.getElementById("roundUp").value = round.toFixed(2);
            document.getElementById("grandTotal").value = grand.toFixed(2);
            document.getElementById("inr_in_words").value = convertNumberToWords(grand.toFixed(0));
        }

        function addRowEventListeners(row) {
            const fields = ['quantity[]', 'unit_rate[]', 'tds[]', 'discount[]', 'sgst[]', 'cgst[]', 'igst[]'];

            fields.forEach(name => {
                const input = row.querySelector(`[name="${name}"]`);
                if (input) {
                    input.addEventListener('input', () => {
                        calculateRowValue(row);
                    });
                }
            });
        }

        function getTableData() {
            const rows = document.querySelectorAll("#productTable tbody tr");
            const data = [];
            let slNo = 1;

            rows.forEach(row => {
                const itemSelect = row.querySelector('[name="item[]"]');
                const rowData = {
                    sl_no: slNo++,
                    item: itemSelect ? itemSelect.value : "",
                    description: row.querySelector('[name="description[]"]')?.value || "",
                    req_by_date: row.querySelector('[name="req_by_date[]"]')?.value || "",
                    quantity: row.querySelector('[name="quantity[]"]')?.value || "",
                    uom: row.querySelector('[name="uom[]"]')?.value || "",
                    unit_rate: row.querySelector('[name="unit_rate[]"]')?.value || "",
                    tds: row.querySelector('[name="tds[]"]')?.value || "",
                    discount: row.querySelector('[name="discount[]"]')?.value || "",
                    value: row.querySelector('[name="value[]"]')?.value || "",
                    sgst: row.querySelector('[name="sgst[]"]')?.value || "",
                    cgst: row.querySelector('[name="cgst[]"]')?.value || "",
                    igst: row.querySelector('[name="igst[]"]')?.value || "",
                    amount: row.querySelector('[name="amount[]"]')?.value || ""
                };
                data.push(rowData);
            });

            return data;
        }

        window.addRow = function () {
            const table = document.getElementById("productTable").querySelector("tbody");
            const idx = table.rows.length + 1;
            const row = document.createElement("tr");

            row.innerHTML = `
                <td>${idx}</td>
                <td>
                    <select class="form-select 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" placeholder="Description" /></td>
                <td><input type="date" name="req_by_date[]" class="form-control" placeholder="Select date" /></td>
                <td><input type="number" name="quantity[]" class="form-control" step="1" min="0" placeholder="Qty" /></td>
                <td><input type="text" name="uom[]" class="form-control" placeholder="UOM" /></td>
                <td><input type="number" name="unit_rate[]" class="form-control" step="0.01" placeholder="Rate" /></td>
                <td><input type="number" name="tds[]" class="form-control" step="0.01" placeholder="TDS %" /></td>
                <td><input type="number" name="discount[]" class="form-control" step="0.01" placeholder="Discount %" /></td>
                <td><input type="number" name="value[]" class="form-control" step="0.01" readonly placeholder="Value" /></td>
                <td><input type="number" name="sgst[]" class="form-control" step="0.01" placeholder="SGST %" /></td>
                <td><input type="number" name="cgst[]" class="form-control" step="0.01" placeholder="CGST %" /></td>
                <td><input type="number" name="igst[]" class="form-control" step="0.01" placeholder="IGST %" /></td>
                <td><input type="number" name="amount[]" class="form-control" step="0.01" readonly placeholder="Amount" /></td>
                <td>
                    <button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)">
                        <i class="fa fa-trash"></i>
                    </button>
                </td>
            `;

            table.appendChild(row);

            addRowEventListeners(row);

            const itemSelect = row.querySelector('.item-select');
            if (itemSelect) {
                initializeSelect2OnElement(itemSelect);
            }
        };

        function initializeSelect2OnElement(element) {
            if (!$(element).hasClass("select2-hidden-accessible")) {
                $(element).select2({
                    dropdownParent: $('#soForm'),
                    width: 'resolve',
                    placeholder: "Select Item",
                    allowClear: true
                });
            }
        }

        window.deleteRow = function (btn) {
            const row = btn.closest("tr");
            row.remove();
            calculateAllTotals();
        };

        document.addEventListener("DOMContentLoaded", function () {
            document.querySelectorAll("#productTable tbody tr").forEach(row => addRowEventListeners(row));
            calculateAllTotals();

            document.getElementById("soForm").addEventListener("submit", async function (e) {
                e.preventDefault();
                const form = this;

                document.getElementById("tableProducts").value = JSON.stringify(getTableData());

                const formData = new FormData(form);
                const payload = {};
                formData.forEach((value, key) => { payload[key] = value; });
                payload['tableProducts'] = getTableData();
                payload['_method'] = 'PUT';

                Swal.fire({
                    title: "Saving...",
                    text: "Updating Purchase Order, please wait.",
                    allowOutsideClick: false,
                    didOpen: () => Swal.showLoading()
                });

                try {
                    const response = await fetch(form.action, {
                        method: "POST",
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                        },
                        body: JSON.stringify(payload)
                    });

                    const result = await response.json();
                    Swal.close();

                    if (response.ok && result.message?.includes("updated")) {
                        Swal.fire("Success", result.message, "success").then(() => {
                            window.location.href = "{{ route('superadmin.purchase.purchasedetails') }}";
                        });
                    } else {
                        Swal.fire("Error", result.error || result.message || "An error occurred.", "error");
                    }
                } catch (error) {
                    Swal.close();
                    Swal.fire("Error", "Something went wrong during submission.", "error");
                }
            });
        });

</script>
@endsection
