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

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

    <!-- Content Row -->
    <div class="bg-white row">
        <div class="col-lg-12">
            <!-- Project Planning Start -->
            <div class="sales-form" id="soContent">
                <h1 class="pt-5 pb-5">Sales Order</h1>
                <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" required class="form-control" readonly>
                            </label>
                            <label>Date <span class="required" title="required">*</span>
                                <input type="date" id="sOrderDate" required class="form-control">
                            </label>
                            <label>GRN No.
                                <input type="text" id="grnNo" class="form-control">
                            </label>
                            <label>Customer Reference No.
                                <input type="text" id="custRefNo" 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" required class="form-control">
                                    <input type="hidden" id="soCompanyName" required class="form-control">
                                </label>
                                <label>Address <span class="required" title="required">*</span>
                                    <input type="text" id="soCompanyAddress" required class="form-control">
                                </label>
                                <label>GSTN <span class="required" title="required">*</span>
                                    <input type="text" id="soCompanyGSTN" required class="form-control">
                                </label>
                                <label>Phone <span class="required" title="required">*</span>
                                    <input type="tel" id="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" 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="quotationSelect" class="form-select">
                                    <option value="">Select Quotation</option>
                                </select>
                            </label>
                        </div>
                        <div class="col-md-6">
                            <label>Quotation Date <span class="required" title="required">*</span>
                                <input type="date" id="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" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label for="rfqDate">RFQ Date</label>
                            <input type="date" id="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" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label for="project-materialNo">Project Material No</label>
                            <input type="text" id="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="drawingNo" class="form-control">
                        </div>
                        <div class="col-md-6">
                            <label for="drawingRev">Drawing Revision</label>
                            <input type="text" id="drawingRevision" name="drawingRev" class="form-control">
                        </div>
                    </div>

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


                    <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" 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" 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" 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" 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" 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" 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" 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" onclick="saveSO(event)">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 ====
            try {
                const response = await fetch("{{ url('/manager/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(
                        `{{ url('/manager/quotation') }}/${quotationId}`);
                    const data = await response.json();
                    if (data.error) {
                        alert(data.error);
                        return;
                    }
                    // Autofill header fields
                    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 || "";
                   
                    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("{{ url('manager/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);
            });

            // ==== 4. Add/Remove Product Rows, Calculation Logic ====
            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

                // If it's a string, parse to array
                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); // Make sure new row can calculate
                    });
                }
            }

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


            // Helper to collect product table data
            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 ---
            window.saveSO = async function(event) {
                event.preventDefault();
                Swal.fire({
                    title: 'Please wait...',
                    text: 'Saving Sales Order...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                // Collect form data
                const formData = {
                    soNo1: document.getElementById('sOrderNo').value,
                    soDate: document.getElementById('sOrderDate').value,
                    grnNo1: document.getElementById('grnNo').value,
                    custRefSoNo: document.getElementById('custRefNo').value,
                    companyName: document.getElementById('soCompanyName').value,
                    companyId: document.getElementById('soCompanyId').value,
                    soCompanyAddress: document.getElementById('soCompanyAddress').value,
                    soCompanyGSTN: document.getElementById('soCompanyGSTN').value,
                    soCompanyPhone: document.getElementById('soCompanyPhone').value,
                    soCompanyEmail: document.getElementById('soCompanyEmail').value,
                    quotationNo2: 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,
                    productType: document.getElementById('productType').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,
                    GT_in_letters: document.getElementById('GT-in-letters').value,
                    rfqNo: document.getElementById('rfqNo').value,
                    rfqDate: document.getElementById('rfqDate').value,
                    partNo: document.getElementById('partNo').value,
                    projectMaterialNo: document.getElementById('projectMaterialNo').value,
                    drawingId: document.getElementById('drawingId').value,
                    drawingRevision: document.getElementById('drawingRevision').value,
                    projectDescription: document.getElementById('projectDescription').value,
                    tableProducts: getTableData("productTable")
                };
                // Debug log
                console.log("[saveSO] FormData to send:", formData);

                try {
                    const response = await fetch("{{ route('manager.sales.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('Sales Order saved')) {
                        Swal.fire('Success!', data.message, 'success').then(() =>
                            window.location.href = "{{ url('manager/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);
                }
            };

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

            // Calculate totals initially
            calculateAllTotals();

        });
    </script>

@endsection
