@extends('layouts.dashboard.adminapp')
@section('title', 'Sales Order')
@section('content')

@php
    $editOrderId = $editOrderId ?? '';
@endphp

<input type="hidden" id="editOrderId" value="{{ $editOrderId }}">

<x-layout.page-header title="UEPL / Sales Order" icon="shopping-cart" iconColor="success" />

<div class="bg-white row">
    <div class="col-lg-12">
        <div class="sales-form" id="soContent">
            <h1 class="pt-5 pb-5">Sales Order</h1>
            <br>
            <form id="soForm" class="bg-white p-4 rounded shadow-sm">
                <div class="row">
                    <div class="col-md-6">
                        <label>Sales Order No. <span class="required" title="required">*</span>
                            <input type="text" id="sOrderNo" name="soNo1" required class="form-control" readonly>
                        </label>
                        <label>Date <span class="required" title="required">*</span>
                            <input type="date" id="sOrderDate" name="soDate" required class="form-control">
                        </label>
                        <label>GRN No.
                            <input type="text" id="grnNo" name="grnNo1" class="form-control">
                        </label>
                        <label>Customer Reference No.
                            <input type="text" id="custRefNo" name="custRefSoNo" class="form-control">
                        </label>
                    </div>
                    <div class="col-md-6">
                        <section class="order-company-info">
                            <label>Customer Company Name <span class="required" title="required">*</span>
                                <input type="text" id="soCompanyId" name="companyId" required class="form-control">
                                <input type="hidden" id="soCompanyName" name="companyName" required class="form-control">
                            </label>
                            <label>Address <span class="required" title="required">*</span>
                                <input type="text" id="soCompanyAddress" name="soCompanyAddress" required class="form-control">
                            </label>
                            <label>GSTN <span class="required" title="required">*</span>
                                <input type="text" id="soCompanyGSTN" name="soCompanyGSTN" required class="form-control">
                            </label>
                            <label>Phone <span class="required" title="required">*</span>
                                <input type="tel" id="soCompanyPhone" name="soCompanyPhone" required class="form-control">
                            </label>
                        </section>
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-6">
                        <label for="customerSO">Customer SO</label>
                        <input type="file" id="customerSO" name="customerSO" accept=".pdf" class="form-control">
                    </div>
                    <div class="col-md-6">
                        <label>Email <span class="required" title="required">*</span>
                            <input type="email" id="soCompanyEmail" name="soCompanyEmail" required class="form-control">
                        </label>
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-6">
                        <!--<label>Quotation ID <span class="required" title="required">*</span>-->
                        <!--    <select id="quotationSelect" name="quotationId" class="form-select">-->
                        <!--        <option value="">Select Quotation</option>-->
                        <!--    </select>-->
                        <!--</label>-->
                        <label>Quotation ID
                            <!--<select id="quotationSelect" name="quotationId" class="form-select">-->
                            <!--    <option value="">Select Quotation</option>-->
                            <!--</select>-->
                        <input type="text" id="quotationSelect" name="quotationId" class="form-control" readonly>
                        </label>
                    </div>
                    <div class="col-md-6">
                        <label>Quotation Date <span class="required" title="required">*</span>
                            <input type="date" id="quotationDate" name="quotationDate" required class="form-control">
                        </label>
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-6">
                        <label for="rfqNo">RFQ No</label>
                        <input type="text" id="rfqNo" name="rfqNo" class="form-control">
                    </div>
                    <div class="col-md-6">
                        <label for="rfqDate">RFQ Date</label>
                        <input type="date" id="rfqDate" name="rfqDate" class="form-control">
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-6">
                        <label for="partNo">Part No</label>
                        <input type="text" id="partNo" name="partNo" class="form-control">
                    </div>
                    <div class="col-md-6">
                        <label for="project-materialNo">Project Material No</label>
                        <input type="text" id="projectMaterialNo" name="projectMaterialNo" placeholder="Project Material No"
                            class="form-control">
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-6">
                        <label for="drawingNo">Drawing No</label>
                        <input type="text" id="drawingId" name="drawingId" class="form-control">
                    </div>
                    <div class="col-md-6">
                        <label for="drawingRev">Drawing Revision</label>
                        <input type="text" id="drawingRevision" name="drawingRevision" class="form-control">
                    </div>
                </div>

                <div class="row mt-3">
                    <div class="col-md-12">
                        <label for="description">Description</label>
                        <textarea id="projectDescription" name="projectDescription" rows="2" placeholder="Project Description"
                            class="form-control"></textarea>
                    </div>
                </div>

                <hr>

                <div class="row">
                    <div class="col-md-6">
                        <div class="Billing-info">
                            <label>Bill To
                                <textarea name="billAddress" id="billAddress" class="form-control"></textarea>
                            </label>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="Shipping-info">
                            <label>Ship To
                                <textarea name="shipAddress" id="shipAddress" class="form-control"></textarea>
                            </label>
                        </div>
                    </div>

                    <div class="col-lg-12">
                        <div class="product-selection">
                            <label for="productType">Product Type</label>
                            <input type="text" id="productType" name="productType" placeholder="Product Type"
                                required class="form-control">
                        </div>
                        <div class="po-so">
                            <table id="productTable" class="table table-bordered product-table">
                                <thead>
                                    <tr>
                                        <th>Sl No.</th>
                                        <th>Material Code/Item Rev</th>
                                        <th>HSN Code</th>
                                        <th>Material Description</th>
                                        <th>Additional Details</th>
                                        <th>Req By Date</th>
                                        <th>Quantity</th>
                                        <th>UOM</th>
                                        <th>Unit Rate (INR)</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>
                                    <tr>
                                        <td>1</td>
                                        <td><input type="text" class="material-code form-control"></td>
                                        <td><input type="text" class="hsn-code form-control"></td>
                                        <td>
                                            <textarea class="description form-control" rows="1"></textarea>
                                        </td>
                                        <td>
                                            <textarea class="additional-details form-control" rows="1"></textarea>
                                        </td>
                                        <td><input type="date" class="req-by-date form-control"></td>
                                        <td><input type="number" class="quantity form-control"></td>
                                        <td><input type="text" class="uom form-control"></td>
                                        <td><input type="number" class="rate form-control"></td>
                                        <td><input type="number" class="discount form-control"></td>
                                        <td><input type="number" class="value form-control" readonly></td>
                                        <td><input type="number" class="sgst form-control"></td>
                                        <td><input type="number" class="cgst form-control"></td>
                                        <td><input type="number" class="igst form-control"></td>
                                        <td><input type="number" class="amount form-control" readonly></td>
                                        <td><button type="button" class="btn btn-danger" onclick="deleteRow(this)">
                                                <i class="fa fa-trash"></i></button></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <div class="row mt-3">
                            <div class="col-md-2">
                                <button type="button" class="btn btn-primary" id="addRowBtn">Add Row</button>
                            </div>
                        </div>

                        <hr>

                        <div class="row mt-4">
                            <div class="col-md-6">
                                <label for="INR">Indian Rupees</label>
                                <input type="text" id="GT-in-letters" name="GT_in_letters" readonly class="form-control">
                            </div>
                            <div class="col-md-6 total-fields">
                                <div class="totals align-self-lg-end">
                                    <div class="row mb-2">
                                        <div class="col-md-3"><label>SUB TOTAL</label></div>
                                        <div class="col-md-9"><input type="text" id="totalAmount" name="totalAmount" readonly
                                                class="form-control"></div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-3"><label>SGST Amount</label></div>
                                        <div class="col-md-9"><input type="text" id="sgstA" name="sgstA" readonly
                                                class="form-control"></div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-3"><label>CGST Amount</label></div>
                                        <div class="col-md-9"><input type="text" id="cgstA" name="cgstA" readonly
                                                class="form-control"></div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-3"><label>IGST Amount</label></div>
                                        <div class="col-md-9"><input type="text" id="IgstA" name="IgstA" readonly
                                                class="form-control"></div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-3"><label>RoundUp Amount</label></div>
                                        <div class="col-md-9"><input type="text" id="roundUp" name="roundUp" readonly
                                                class="form-control"></div>
                                    </div>
                                    <div class="row mb-2">
                                        <div class="col-md-3"><label>Grand Total</label></div>
                                        <div class="col-md-9"><input type="text" id="grandTotal" name="grandTotal" readonly
                                                class="form-control"></div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <hr>

                         <div class="row p-3">
                            <!-- Submit Button -->
                            <div class="btn"><button class="btn btn-success" type="submit">Save</button>
                            </div>
    
                            <div class="btn"><button class="btn btn-danger" type="reset" onclick="resetForm()">Clear</button>
                            </div>
                        </div>
            </form>
        </div>
    </div>
</div>
   <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.addEventListener("DOMContentLoaded", async function() {
    // 1. Populate Quotation Dropdown
    async function loadQuotations() {
        let quotations = [];
        const select = document.getElementById("quotationSelect");
        select.innerHTML = '<option value="">Select Quotation</option>'; // reset options
        try {
            const response = await fetch("{{ url('/admin/quotations') }}");
            quotations = await response.json();
            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);
        }
        return quotations;
    }

    // Autofill from Quotation select
    document.getElementById("quotationSelect").addEventListener("change", async function() {
        const quotationId = this.value;
        if (!quotationId) return;
        try {
            const response = await fetch(`{{ url('/admin/quotation') }}/${quotationId}`);
            const data = await response.json();
            if (data.error) {
                alert(data.error);
                return;
            }
            document.getElementById("quotationDate").value = data.quotation_date || "";
            document.getElementById("soCompanyId").value = data.customer.company || "";
            document.getElementById("soCompanyName").value = data.customer.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.cust_ref_no || "";
            document.getElementById("rfqNo").value = data.rfq ? data.rfq.rfq_no : "";
            document.getElementById("rfqDate").value = data.rfq_date || "";
            document.getElementById("partNo").value = data.part_no || "";
            document.getElementById("projectMaterialNo").value = data.project_material_no || "";
            document.getElementById("drawingId").value = data.drawing_no || "";
            document.getElementById("drawingRevision").value = data.drawing_rev || "";
            document.getElementById("projectDescription").value = data.description || "";
            document.getElementById("productType").value = data.product_type || "";
            fillProductTableFromQuotation(data);
            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);
        }
    });

    // Main page logic: WAIT for quotations, then load order if edit
    const editOrderId = document.getElementById('editOrderId').value;
    const quotations = await loadQuotations();
    if (editOrderId) {
        // Fetch and fill for edit
        fetch("{{ url('admin/sales-order') }}/" + editOrderId)
            .then(res => res.json())
            .then(order => {
                let qId = '';
                // Try various possibilities for quotation ID
                if (order.quotation_id) {
                    qId = String(order.quotation_id);
                } else if (order.quotationId) {
                    qId = String(order.quotationId);
                } else if (order.quotation_no) {
                    const match = quotations.find(q => q.quotation_no == order.quotation_no);
                    if (match) qId = String(match.id);
                } else if (order.quotation && order.quotation.id) {
                    qId = String(order.quotation.id);
                }
                // // Set dropdown
                // const select = document.getElementById('quotationSelect');
                // select.value = qId;
                // // If not matched, show warning
                // if (select.value !== qId) {
                //     console.warn('Not matched! Maybe qId is missing or not in the options?', {qId, options: [...select.options].map(o=>o.value)});
                // }
                // Fill rest fields
                document.getElementById('sOrderNo').value = order.sales_order_no || '';
                document.getElementById('sOrderDate').value = order.sales_order_date || '';
                document.getElementById('grnNo').value = order.grn_no || '';
                document.getElementById('custRefNo').value = order.customer_ref_no || '';
                document.getElementById('soCompanyId').value = order.customer?.company || '';
                document.getElementById('soCompanyName').value = order.customer?.id || '';
                document.getElementById('soCompanyAddress').value = order.company_address || '';
                document.getElementById('soCompanyGSTN').value = order.company_gstn || '';
                document.getElementById('soCompanyPhone').value = order.company_phone || '';
                document.getElementById('soCompanyEmail').value = order.company_email || '';
                document.getElementById('quotationSelect').value = order.quotation_no || '';
                document.getElementById('quotationDate').value = order.quotation_date || '';
                document.getElementById('billAddress').value = order.bill_address || '';
                document.getElementById('shipAddress').value = order.ship_address || '';
                document.getElementById('productType').value = order.product_type || '';
                document.getElementById('totalAmount').value = order.subtotal || '';
                document.getElementById('sgstA').value = order.sgst_amount || '';
                document.getElementById('cgstA').value = order.cgst_amount || '';
                document.getElementById('IgstA').value = order.igst_amount || '';
                document.getElementById('roundUp').value = order.round_up || '';
                document.getElementById('grandTotal').value = order.grand_total || '';
                document.getElementById('GT-in-letters').value = order.inr_in_words || '';
                document.getElementById('rfqNo').value = order.rfq_no || '';
                document.getElementById('rfqDate').value = order.rfq_date || '';
                document.getElementById('partNo').value = order.part_no || '';
                document.getElementById('projectMaterialNo').value = order.project_material_no || '';
                document.getElementById('drawingId').value = order.drawing_no || '';
                document.getElementById('drawingRevision').value = order.drawing_rev || '';
                document.getElementById('projectDescription').value = order.description || '';
                fillProductTableFromOrder(order.items || []);
                calculateAllTotals();
            });
    } else {
        // Generate new SO ID
        try {
            const soResponse = await fetch("{{ url('admin/generate-so-id') }}");
            const soData = await soResponse.json();
            document.getElementById('sOrderNo').value = soData.so_id;
        } catch (error) {
            document.getElementById('sOrderNo').value = 'UEPL/SO/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);
    });

    document.getElementById('addRowBtn').addEventListener('click', function() {
        addRow();
    });
    window.addRow = function() {
        const productTableBody = document.querySelector("#productTable tbody");
        const newRow = document.createElement("tr");
        newRow.innerHTML = `
    <td></td>
    <td><input type="text" class="material-code form-control"></td>
    <td><input type="text" class="hsn-code form-control"></td>
    <td><textarea class="description form-control" rows="1"></textarea></td>
    <td><textarea class="additional-details form-control" rows="1"></textarea></td>
    <td><input type="date" class="req-by-date form-control"></td>
    <td><input type="number" class="quantity form-control"></td>
    <td><input type="text" class="uom form-control"></td>
    <td><input type="number" class="rate form-control"></td>
    <td><input type="number" class="discount form-control"></td>
    <td><input type="number" class="value form-control" readonly></td>
    <td><input type="number" class="sgst form-control"></td>
    <td><input type="number" class="cgst form-control"></td>
    <td><input type="number" class="igst form-control"></td>
    <td><input type="number" class="amount form-control" readonly></td>
    <td><button class="btn btn-danger" type="button" onclick="deleteRow(this)">
        <i class="fa fa-trash"></i></button></td>`;
        productTableBody.appendChild(newRow);
        updateRowNumbers();
        addRowEventListeners(newRow);
    };

    window.deleteRow = function(button) {
        const row = button.closest("tr");
        row.parentNode.removeChild(row);
        updateRowNumbers();
        calculateAllTotals();
    };

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

    window.calculateRowValue = function(input) {
        const row = input.closest("tr");
        const quantity = parseFloat(row.cells[6].querySelector("input").value) || 0;
        const rate = parseFloat(row.cells[8].querySelector("input").value) || 0;
        const discount = parseFloat(row.cells[9].querySelector("input").value) || 0;
        const sgst = parseFloat(row.cells[11].querySelector("input").value) || 0;
        const cgst = parseFloat(row.cells[12].querySelector("input").value) || 0;
        const igst = parseFloat(row.cells[13].querySelector("input").value) || 0;

        const baseValue = quantity * rate * (1 - discount / 100);
        row.cells[10].querySelector("input").value = baseValue.toFixed(2);

        const amount = baseValue * (1 + (sgst + cgst + igst) / 100);
        row.cells[14].querySelector("input").value = amount.toFixed(2);

        calculateAllTotals();
    };

    window.calculateAllTotals = function() {
        let subtotal = 0,
            sgstTotal = 0,
            cgstTotal = 0,
            igstTotal = 0;
        document.querySelectorAll("#productTable tbody tr").forEach(row => {
            const val = parseFloat(row.cells[10].querySelector("input").value) || 0;
            const sgst = parseFloat(row.cells[11].querySelector("input").value) || 0;
            const cgst = parseFloat(row.cells[12].querySelector("input").value) || 0;
            const igst = parseFloat(row.cells[13].querySelector("input").value) || 0;

            subtotal += val;
            sgstTotal += val * sgst / 100;
            cgstTotal += val * cgst / 100;
            igstTotal += val * igst / 100;
        });

        const grandTotalRaw = subtotal + sgstTotal + cgstTotal + igstTotal;
        const roundUp = Math.ceil(grandTotalRaw) - grandTotalRaw;
        const grandTotal = grandTotalRaw + roundUp;

        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 = roundUp.toFixed(2);
        document.getElementById("grandTotal").value = grandTotal.toFixed(2);
        document.getElementById("GT-in-letters").value = convertNumberToWords(Math.round(grandTotal));
    };

    function addRowEventListeners(row) {
        row.querySelector(".quantity").addEventListener("input", function() {
            calculateRowValue(this);
        });
        row.querySelector(".rate").addEventListener("input", function() {
            calculateRowValue(this);
        });
        row.querySelector(".discount").addEventListener("input", function() {
            calculateRowValue(this);
        });
        row.querySelector(".sgst").addEventListener("input", function() {
            calculateRowValue(this);
        });
        row.querySelector(".cgst").addEventListener("input", function() {
            calculateRowValue(this);
        });
        row.querySelector(".igst").addEventListener("input", function() {
            calculateRowValue(this);
        });
    }

    function fillProductTableFromQuotation(quotation) {
        const table = document.getElementById("productTable").getElementsByTagName("tbody")[0];
        table.innerHTML = ""; // Clear old

        let rawMaterials = quotation.raw_materials;
        if (typeof rawMaterials === "string") {
            try {
                rawMaterials = JSON.parse(rawMaterials);
            } catch (e) {
                rawMaterials = [];
            }
        }
        if (Array.isArray(rawMaterials) && rawMaterials.length > 0) {
            rawMaterials.forEach((item, idx) => {
                const row = document.createElement("tr");
                row.innerHTML = `
                <td>${idx + 1}</td>
                <td><input type="text" class="material-code form-control" value="${item.material_code || item.material || ''}"></td>
                <td><input type="text" class="hsn-code form-control" value="${item.hsn_code || ''}"></td>
                <td><textarea class="description form-control" rows="1">${item.description || ''}</textarea></td>
                <td><textarea class="additional-details form-control" rows="1">${item.additional_details || ''}</textarea></td>
                <td><input type="date" class="req-by-date form-control" value="${item.req_by_date || ''}"></td>
                <td><input type="number" class="quantity form-control" value="${item.quantity || ''}"></td>
                <td><input type="text" class="uom form-control" value="${item.quantity_uom || ''}"></td>
                <td><input type="number" class="rate form-control" value="${item.unit_rate || item.rate || ''}"></td>
                <td><input type="number" class="discount form-control" value="${item.discount || ''}"></td>
                <td><input type="number" class="value form-control" readonly></td>
                <td><input type="number" class="sgst form-control" value="${item.sgst || ''}"></td>
                <td><input type="number" class="cgst form-control" value="${item.cgst || ''}"></td>
                <td><input type="number" class="igst form-control" value="${item.igst || ''}"></td>
                <td><input type="number" class="amount form-control" readonly></td>
                <td><button class="btn btn-danger" type="button" onclick="deleteRow(this)">
                    <i class="fa fa-trash"></i></button></td>
            `;
                table.appendChild(row);
                addRowEventListeners(row);
            });
        }
    }

    // For Edit
    function fillProductTableFromOrder(items) {
        const table = document.getElementById("productTable").getElementsByTagName("tbody")[0];
        table.innerHTML = "";
        if (Array.isArray(items) && items.length > 0) {
            items.forEach((item, idx) => {
                const row = document.createElement("tr");
                row.innerHTML = `
                <td>${idx + 1}</td>
                <td><input type="text" class="material-code form-control" value="${item.material_code || ''}"></td>
                <td><input type="text" class="hsn-code form-control" value="${item.hsn_code || ''}"></td>
                <td><textarea class="description form-control" rows="1">${item.material_description || ''}</textarea></td>
                <td><textarea class="additional-details form-control" rows="1">${item.additional_details || ''}</textarea></td>
                <td><input type="date" class="req-by-date form-control" value="${item.required_by_date || ''}"></td>
                <td><input type="number" class="quantity form-control" value="${item.quantity || ''}"></td>
                <td><input type="text" class="uom form-control" value="${item.uom || ''}"></td>
                <td><input type="number" class="rate form-control" value="${item.unit_rate || ''}"></td>
                <td><input type="number" class="discount form-control" value="${item.discount || ''}"></td>
                <td><input type="number" class="value form-control" value="${item.value || ''}" readonly></td>
                <td><input type="number" class="sgst form-control" value="${item.sgst || ''}"></td>
                <td><input type="number" class="cgst form-control" value="${item.cgst || ''}"></td>
                <td><input type="number" class="igst form-control" value="${item.igst || ''}"></td>
                <td><input type="number" class="amount form-control" value="${item.amount || ''}" readonly></td>
                <td><button class="btn btn-danger" type="button" onclick="deleteRow(this)">
                    <i class="fa fa-trash"></i></button></td>
            `;
                table.appendChild(row);
                addRowEventListeners(row);
            });
        }
    }

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

    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);
        //           1   2    3    4      5
        // crore lakh thousand hundred units
        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);
    }

    function getTableData(tableId) {
        const table = document.getElementById(tableId);
        const rows = table.getElementsByTagName("tbody")[0].getElementsByTagName("tr");
        const data = [];
        for (let row of rows) {
            const rowData = {
                slNo: row.cells[0].textContent,
                materialCode: row.cells[1].querySelector("input").value,
                hsnCode: row.cells[2].querySelector("input").value,
                description: row.cells[3].querySelector("textarea").value,
                additionalDetails: row.cells[4].querySelector("textarea").value,
                reqByDate: row.cells[5].querySelector("input").value,
                quantity: row.cells[6].querySelector("input").value,
                uom: row.cells[7].querySelector("input").value,
                unitRate: row.cells[8].querySelector("input").value,
                discount: row.cells[9].querySelector("input").value,
                value: row.cells[10].querySelector("input").value,
                sgst: row.cells[11].querySelector("input").value,
                cgst: row.cells[12].querySelector("input").value,
                igst: row.cells[13].querySelector("input").value,
                amount: row.cells[14].querySelector("input").value
            };
            data.push(rowData);
        }
        return data;
    }

    // --- Save SO function (works for both create and edit!) ---
    window.saveSO = async function(event) {
        event.preventDefault();

        const editOrderId = document.getElementById('editOrderId').value;
        const url = editOrderId
            ? "{{ url('admin/sales/update') }}/" + editOrderId
            : "{{ route('admin.sales.order.store') }}";
            "{{ route('admin.sales.order.store') }}";
        const method = "POST";

        Swal.fire({
            title: 'Please wait...',
            text: editOrderId ? 'Updating Sales Order...' : 'Saving Sales Order...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        const form = document.getElementById('soForm');
        const formData = new FormData(form);

        // Add table data as JSON string (not picked up automatically)
        formData.append('tableProducts', JSON.stringify(getTableData("productTable")));

        // Spoof PUT method for update
        if (editOrderId) {
            formData.append('_method', 'PUT');
        }

        try {
            const csrfMeta = document.querySelector('meta[name="csrf-token"]');
            const csrfToken = csrfMeta ? csrfMeta.getAttribute('content') : '';

            const response = await fetch(url, {
                method: method,
                headers: {
                    "X-CSRF-TOKEN": csrfToken
                },
                body: formData
            });
            const data = await response.json();
            Swal.close();
            console.log("[saveSO] Response Data:", data); // <-- ADD THIS LINE
            if (data.message && (data.message.includes('Sales Order saved') || data.message
                    .includes('updated'))) {
                Swal.fire('Success!', data.message, 'success').then(() =>
                    window.location.href = "{{ url('admin/salesorder') }}"
                );
            } else {
                Swal.fire('Error!', data.message || data.error || 'Something went wrong.',
                    'error');
            }
        } catch (err) {
            Swal.close();
            Swal.fire('Error!', 'Failed to save sales order.', 'error');
            console.error("[saveSO] Exception:", err);
        }
    };

    // Hook form submit to saveSO
    document.getElementById('soForm').addEventListener('submit', window.saveSO);

    // Calculate totals initially
    calculateAllTotals();
});
</script>

@endsection
