<?php $__env->startSection('title', 'Purchase Order'); ?>

<?php $__env->startSection('styles'); ?>
<link rel="stylesheet" href="<?php echo e(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-container { z-index: 999999 !important; }

    /* Summary Section */
    .summary-table {
        background: linear-gradient(135deg, #f0fdfa 0%, #ccfbf1 100%);
        border-radius: 12px;
        padding: 1rem;
        border: 2px solid #06b6d4;
    }

    .summary-table table tr:last-child {
        border-top: 2px solid #06b6d4;
    }

    .summary-table table tr:last-child td {
        font-weight: 700;
        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>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('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-shopping-cart"></i>
            </div>
            <div class="header-title">
                <h1>Create Purchase Order</h1>
                <div class="header-subtitle">Purchase Order Registration Form</div>
            </div>
        </div>
        <div class="datetime-display">
            <div class="date-box">
                <i class="far fa-calendar-alt"></i>
                <span id="day"><?php echo e(now()->format('l')); ?></span>,
                <span id="daynum"><?php echo e(now()->format('d')); ?></span>
                <span id="month"><?php echo e(now()->format('F')); ?></span>
                <span id="year"><?php echo e(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">
        <!-- 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. <span class="required-star">*</span></label>
                        <input type="text" id="sOrderNo" required class="form-control" readonly>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Quotation ID</label>
                        <select id="quotationSelect" name="quotationSelect" class="form-control">
                            <option value="">Select Quotation</option>
                        </select>
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Purchase Date <span class="required-star">*</span></label>
                        <input type="date" id="sOrderDate" required class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Quotation Date</label>
                        <input type="date" id="quotationDate" 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" class="form-control">
                        <input type="hidden" id="soCompanyId" name="soCompanyId">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Vendor Reference No.</label>
                        <input type="text" id="custRefNo" name="custRefNo" 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" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">GSTN</label>
                        <input type="text" id="soCompanyGSTN" 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" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" id="soCompanyEmail" 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 class="form-label">RFQ No</label>
                        <input type="text" id="rfqNo" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">RFQ Date</label>
                        <input type="date" id="rfqDate" class="form-control">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Note I</label>
                        <input type="text" id="projectDescription" name="projectDescription" class="form-control">
                    </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">
                    </div>
                </div>

                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Additional Charges</label>
                        <input type="text" id="additionalCharges" name="additionalCharges" class="form-control">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Note II</label>
                        <textarea id="note" name="note" rows="2" class="form-control"></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" class="form-control" rows="3"></textarea>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Ship To</label>
                        <textarea name="shipAddress" id="shipAddress" class="form-control" rows="3"></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 class="table-responsive">
                    <table id="productTable" class="table table-bordered table-sm">
                        <thead>
                            <tr>
                                <th width="50">Sl No.</th>
                                <th>Item</th>
                                <th>Description</th>
                                <th width="110">Req By Date</th>
                                <th width="80">Qty</th>
                                <th width="70">UOM</th>
                                <th width="90">Unit Rate</th>
                                <th width="70">TDS %</th>
                                <th width="70">Disc %</th>
                                <th width="90">Value</th>
                                <th width="70">SGST %</th>
                                <th width="70">CGST %</th>
                                <th width="70">IGST %</th>
                                <th width="100">Amount</th>
                                <th width="50"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>1</td>
                                <td>
                                    <select class="form-control item-select" name="item[]" required>
                                        <option value="">Select Item</option>
                                        <?php $__currentLoopData = $stock_items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <option value="<?php echo e($item->id); ?>"><?php echo e($item->item_name); ?></option>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </td>
                                <td><input type="text" name="description" class="form-control" /></td>
                                <td><input type="date" name="req_by_date" class="form-control" /></td>
                                <td><input type="number" name="quantity" class="form-control" step="1" min="0" /></td>
                                <td><input type="text" name="uom" class="form-control" /></td>
                                <td><input type="number" name="unit_rate" class="form-control" step="0.01" /></td>
                                <td><input type="number" name="tds" class="form-control" step="0.01" /></td>
                                <td><input type="number" name="discount" class="form-control" step="0.01" /></td>
                                <td><input type="number" name="value" class="form-control" step="0.01" readonly /></td>
                                <td><input type="number" name="sgst" class="form-control" step="0.01" /></td>
                                <td><input type="number" name="cgst" class="form-control" step="0.01" /></td>
                                <td><input type="number" name="igst" class="form-control" step="0.01" /></td>
                                <td><input type="number" name="amount" class="form-control" step="0.01" readonly /></td>
                                <td>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <button type="button" class="btn btn-primary mt-3" id="addRowBtn">
                    <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 class="form-label">Grand Total in Words (INR)</label>
                        <input type="text" id="inr_in_words" name="inr_in_words" readonly class="form-control" style="font-weight: 600; color: #0e7490;">
                    </div>
                    <div class="col-md-6">
                        <div class="summary-table">
                            <table class="table table-sm table-borderless mb-0">
                                <tr>
                                    <td class="text-right font-weight-bold">Sub Total:</td>
                                    <td width="150"><input type="text" id="totalAmount" readonly class="form-control form-control-sm text-right"></td>
                                </tr>
                                <tr>
                                    <td class="text-right">SGST Amount:</td>
                                    <td><input type="text" id="sgstA" readonly class="form-control form-control-sm text-right"></td>
                                </tr>
                                <tr>
                                    <td class="text-right">CGST Amount:</td>
                                    <td><input type="text" id="cgstA" readonly class="form-control form-control-sm text-right"></td>
                                </tr>
                                <tr>
                                    <td class="text-right">IGST Amount:</td>
                                    <td><input type="text" id="IgstA" readonly class="form-control form-control-sm text-right"></td>
                                </tr>
                                <tr>
                                    <td class="text-right">Round Up:</td>
                                    <td><input type="text" id="roundUp" readonly class="form-control form-control-sm text-right"></td>
                                </tr>
                                <tr>
                                    <td class="text-right font-weight-bold">Grand Total:</td>
                                    <td><input type="text" id="grandTotal" readonly class="form-control form-control-sm text-right font-weight-bold"></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer Actions -->
        <div class="footer-actions">
            <a href="<?php echo e(route('superadmin.purchase.purchasedetails')); ?>" 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" onclick="saveSO(event)">
                    <i class="fas fa-save"></i> Save Purchase Order
                </button>
            </div>
        </div>
    </form>

</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('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
    <?php if(session('success')): ?>
        showToast("<?php echo e(session('success')); ?>", 'success');
    <?php endif; ?>

    <?php if(session('error')): ?>
        showToast("<?php echo e(session('error')); ?>", 'error');
    <?php endif; ?>

    const stockItems = <?php echo json_encode($stock_items, 15, 512) ?>;

    document.addEventListener("DOMContentLoaded", async function() {

        // ==== 1. Populate Quotation Dropdown ====
        try {
            const response = await fetch("<?php echo e(url('/superadmin/purchase/quotations')); ?>");
            const quotations = await response.json();
            const select = document.getElementById("quotationSelect");
            quotations.forEach(q => {
                const opt = document.createElement("option");
                opt.value = q.id;
                opt.textContent = q.quotation_no;
                select.appendChild(opt);
            });
        } catch (err) {
            console.error("Failed to load quotations:", err);
        }

        // ==== 2. On Quotation Select, Autofill All Fields ====
        document.getElementById("quotationSelect").addEventListener("change", async function() {
            const quotationId = this.value;
            if (!quotationId) return;
            try {
                const response = await fetch(
                    `<?php echo e(url('/superadmin/purchase/quotation')); ?>/${quotationId}`);
                const data = await response.json();
                if (data.error) {
                    alert(data.error);
                    return;
                }
                // Autofill header fields
                document.getElementById("quotationDate").value = formatDate(data.quotation_date);
                document.getElementById("soCompanyName").value = data.vendor_name || "";
                document.getElementById("soCompanyId").value = data.vendor_id || "";
                document.getElementById("soCompanyAddress").value = data.address || "";
                document.getElementById("soCompanyGSTN").value = data.gst || "";
                document.getElementById("soCompanyPhone").value = data.phone || "";
                document.getElementById("soCompanyEmail").value = data.email || "";
                document.getElementById("billAddress").value = data.address || "";
                document.getElementById("shipAddress").value = data.address || "";
                document.getElementById("custRefNo").value = data.vendor_reference_no || "";
                document.getElementById("rfqNo").value = data.rfq_no || "";
                document.getElementById("rfqDate").value = formatDate(data.rfq_date);
                document.getElementById("projectDescription").value = data.description || "";
                document.getElementById("deliveryTerms").value = data.delivery_terms || "";
                document.getElementById("additionalCharges").value = data.additional_charges || "";
                document.getElementById("note").value = data.note || "";

                // Fill product table using raw_materials array
                fillProductTableFromQuotation(data.items);
                // Totals and financials
                document.getElementById("totalAmount").value = data.sub_total || "";
                document.getElementById("grandTotal").value = data.grand_total || "";
                document.getElementById("roundUp").value = data.round_up || "";
                calculateAllTotals();
            } catch (err) {
                console.error("Failed to load quotation data:", err);
            }
        });

        // ==== 3. On Page Load: Set Dates, Generate SO Number, Setup Initial Row ====
        try {
            const soResponse = await fetch("<?php echo e(url('superadmin/generate-po-id')); ?>");
            const soData = await soResponse.json();
            document.getElementById('sOrderNo').value = soData.so_id;
        } catch (error) {
            document.getElementById('sOrderNo').value = 'UEPL/PO/0001';
        }
        document.getElementById('sOrderDate').value = new Date().toISOString().split('T')[0];

        // Setup event listeners for initial row
        document.querySelectorAll("#productTable tbody tr").forEach(row => {
            addRowEventListeners(row);
        });

        // ==== 4. Add/Remove Product Rows, Calculation Logic ====

        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-control item-select" name="item[]" required>
                        <option value="">Select Item</option>
                        <?php $__currentLoopData = $stock_items; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($item->id); ?>"><?php echo e($item->item_name); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </td>
                <td><input type="text" name="description" class="form-control" /></td>
                <td><input type="date" name="req_by_date" class="form-control" /></td>
                <td><input type="number" name="quantity" class="form-control" step="1" min="0" /></td>
                <td><input type="text" name="uom" class="form-control" /></td>
                <td><input type="number" name="unit_rate" class="form-control" step="0.01" /></td>
                <td><input type="number" name="tds" class="form-control" step="0.01" /></td>
                <td><input type="number" name="discount" class="form-control" step="0.01" /></td>
                <td><input type="number" name="value" class="form-control" step="0.01" readonly /></td>
                <td><input type="number" name="sgst" class="form-control" step="0.01" /></td>
                <td><input type="number" name="cgst" class="form-control" step="0.01" /></td>
                <td><input type="number" name="igst" class="form-control" step="0.01" /></td>
                <td><input type="number" name="amount" class="form-control" step="0.01" readonly /></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); // attach input listeners
            const itemSelect = row.querySelector('.item-select');
            if (itemSelect) {
                initializeSelect2OnElement(itemSelect);
            }
        };

        document.getElementById("addRowBtn").addEventListener("click", addRow);

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

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

        function updateRowNumbers() {
            const rows = document.querySelectorAll("#productTable tbody tr");
            rows.forEach((row, i) => row.cells[0].textContent = i + 1);
        }

        function addRowEventListeners(row) {
            ["quantity", "unit_rate", "discount","tds", "sgst", "cgst", "igst"].forEach(name => {
                row.querySelector(`[name="${name}"]`).addEventListener("input", () => calculateRowValue(row));
            });
        }

        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 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] !== 0) {
                str += (n[0] < 20) ? a[n[0]] : b[Math.floor(n[0] / 10)] + ' ' + a[n[0] % 10];
                str += ' crore ';
            }
            if (n[1] !== 0) {
                str += (n[1] < 20) ? a[n[1]] : b[Math.floor(n[1] / 10)] + ' ' + a[n[1] % 10];
                str += ' lakh ';
            }
            if (n[2] !== 0) {
                str += (n[2] < 20) ? a[n[2]] : b[Math.floor(n[2] / 10)] + ' ' + a[n[2] % 10];
                str += ' thousand ';
            }
            if (n[3] !== 0) {
                str += a[n[3]] + ' hundred ';
            }
            if (n[4] !== 0) {
                if (str !== '') str += 'and ';
                str += (n[4] < 20) ? a[n[4]] : b[Math.floor(n[4] / 10)] + ' ' + a[n[4] % 10];
                str += ' ';
            }
            str = str.replace(/\s+/g, ' ').trim();
            return str.charAt(0).toUpperCase() + str.slice(1);
        }

        // ==== 5. Fill product table from quotation data ====
        function fillProductTableFromQuotation(items) {
            const tbody = document.querySelector("#productTable tbody");
            tbody.innerHTML = ""; // clear existing rows
            items.forEach((rm, i) => {
                const row = document.createElement("tr");
                row.innerHTML = `
                    <td>${i + 1}</td>
                    <td>
                        <select class="form-control item-select" name="item[]" required>
                            <option value="">Select Item</option>
                            ${stockItems.map(si => `
                                <option value="${si.id}" ${rm.stock_item == si.id ? 'selected' : ''}>${si.item_name}</option>
                            `).join('')}
                        </select>
                    </td>
                    <td><input type="text" name="description" class="form-control" value="${rm.description || ''}" /></td>
                    <td><input type="date" name="req_by_date" class="form-control" value="${rm.req_by_date || ''}" /></td>
                    <td><input type="number" name="quantity" class="form-control" step="1" min="0" value="${rm.quantity || 0}" /></td>
                    <td><input type="text" name="uom" class="form-control" value="${rm.uom || ''}" /></td>
                    <td><input type="number" name="unit_rate" class="form-control" step="0.01" value="${rm.unit_rate || 0}" /></td>
                    <td><input type="number" name="tds" class="form-control" step="0.01" value="${rm.tds || 0}" /></td>
                    <td><input type="number" name="discount" class="form-control" step="0.01" value="${rm.discount || 0}" /></td>
                    <td><input type="number" name="value" class="form-control" step="0.01" readonly value="0" /></td>
                    <td><input type="number" name="sgst" class="form-control" step="0.01" value="${rm.sgst || 0}" /></td>
                    <td><input type="number" name="cgst" class="form-control" step="0.01" value="${rm.cgst || 0}" /></td>
                    <td><input type="number" name="igst" class="form-control" step="0.01" value="${rm.igst || 0}" /></td>
                    <td><input type="number" name="amount" class="form-control" step="0.01" readonly value="0" /></td>
                    <td><button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
                `;
                tbody.appendChild(row);
                addRowEventListeners(row);
                calculateRowValue(row);
            });
            updateRowNumbers();

            initializeItemSelects();
        }

        window.printSO = function() {
            window.print();
        }

        function getTableData(tableId) {
            const table = document.getElementById(tableId);
            const rows = table.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
            const data = [];
            let slNo = 1;

            for (let row of rows) {
                const itemSelect = row.cells[1].querySelector("select");
                const rowData = {
                    sl_no: slNo++,
                    item: itemSelect ? itemSelect.value : "",
                    description: row.cells[2].querySelector("input")?.value || "",
                    req_by_date: row.cells[3].querySelector("input")?.value || "",
                    quantity: row.cells[4].querySelector("input")?.value || "",
                    uom: row.cells[5].querySelector("input")?.value || "",
                    unit_rate: row.cells[6].querySelector("input")?.value || "",
                    tds: row.cells[7].querySelector("input")?.value || "",
                    discount: row.cells[8].querySelector("input")?.value || "",
                    value: row.cells[9].querySelector("input")?.value || "",
                    sgst: row.cells[10].querySelector("input")?.value || "",
                    cgst: row.cells[11].querySelector("input")?.value || "",
                    igst: row.cells[12].querySelector("input")?.value || "",
                    amount: row.cells[13].querySelector("input")?.value || ""
                };
                data.push(rowData);
            }

            return data;
        }



        // --- Save SO function ---
        window.saveSO = async function(event) {
            event.preventDefault();
            Swal.fire({
                title: 'Please wait...',
                text: 'Saving Purchase Order...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            calculateAllTotals();

            // Collect form data
            const formData = {

                sOrderNo: document.getElementById('sOrderNo').value,
                sOrderDate: document.getElementById('sOrderDate').value,
                quotationNo2: document.getElementById('quotationSelect').selectedOptions[0].text === 'Select Quotation'
                    ? null
                    : document.getElementById('quotationSelect').selectedOptions[0].text,
                quotationId: document.getElementById('quotationSelect').value,
                quotationDate: document.getElementById('quotationDate').value,
                billAddress: document.getElementById('billAddress').value,
                shipAddress: document.getElementById('shipAddress').value,

                soCompanyId: document.getElementById('soCompanyId').value,
                soCompanyName: document.getElementById('soCompanyName').value,

                soCompanyAddress: document.getElementById('soCompanyAddress').value,
                soCompanyGSTN: document.getElementById('soCompanyGSTN').value,
                soCompanyPhone: document.getElementById('soCompanyPhone').value,
                soCompanyEmail: document.getElementById('soCompanyEmail').value,

                custRefNo: document.getElementById('custRefNo').value,

                rfqNo: document.getElementById('rfqNo').value,
                rfqDate: document.getElementById('rfqDate').value,
                projectDescription: document.getElementById('projectDescription').value,
                deliveryTerms: document.getElementById('deliveryTerms').value,
                additionalCharges: document.getElementById('additionalCharges').value,
                note: document.getElementById('note').value,

                tableProducts: getTableData("productTable"),
                inr_in_words: document.getElementById('inr_in_words').value,
                totalAmount: document.getElementById('totalAmount').value,
                sgstA: document.getElementById('sgstA').value,
                cgstA: document.getElementById('cgstA').value,
                IgstA: document.getElementById('IgstA').value,
                roundUp: document.getElementById('roundUp').value,
                grandTotal: document.getElementById('grandTotal').value
            };


            // Debug log
            console.log("[saveSO] FormData to send:", formData);

            try {
                const response = await fetch("<?php echo e(route('superadmin.purchase.order.store')); ?>", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]')
                            .getAttribute('content')
                    },
                    body: JSON.stringify(formData)
                });

                const data = await response.json();
                console.log("[saveSO] Response:", data);

                Swal.close();

                if (data.message && data.message.includes('Purchase Order saved')) {
                    Swal.fire('Success!', data.message, 'success').then(() =>
                        window.location.href = "<?php echo e(url('superadmin/purchaseorder')); ?>"
                    );
                } else {
                    Swal.fire('Error!', data.message || data.error ||
                        'Something went wrong.', 'error');
                }
            } catch (err) {
                Swal.close();
                Swal.fire('Error!', 'Failed to save purchase order.', 'error');
                console.error("[saveSO] Exception:", err);
            }
        }


        // --- Make the form submit use saveSO ---
        document.getElementById('soForm').addEventListener('submit', window.saveSO);

        // Calculate totals initially
        calculateAllTotals();

    });

    function initializeItemSelects() {
        $('.item-select').each(function () {
            const $this = $(this);

            // Initialize only if not already initialized
            if (!$this.hasClass("select2-hidden-accessible")) {
                $this.select2({
                    dropdownParent: $('#soForm'),
                    width: 'resolve',
                    placeholder: "Select Item",
                    allowClear: true
                });
            }
        });
    }


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

    function formatDate(dateString) {
        if (!dateString) return "";
        const date = new Date(dateString);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // months are 0-indexed
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }
</script>

<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.dashboard.superadminapp', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\Users\Admin\Desktop\ip.co.in\resources\views/superadmin/purchase/purchaseorder.blade.php ENDPATH**/ ?>