@extends('layouts.dashboard.superadminapp')

@section('title', 'Create Sales Order')

@section('styles')
<link rel="stylesheet" href="{{ asset('css/modern-form-pattern.css') }}">
@endsection

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

    {{-- 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 Sales Order</h1>
                <div class="header-subtitle">Sales Order Registration Form</div>
            </div>
        </div>
        <div class="datetime-display">
            <div class="date-box">
                <i class="far fa-calendar-alt"></i>
                <span id="day">{{ now()->format('l') }}</span>,
                <span id="daynum">{{ now()->format('d') }}</span>
                <span id="month">{{ now()->format('F') }}</span>
                <span id="year">{{ now()->format('Y') }}</span>
            </div>
            <div class="time-box">
                <i class="far fa-clock"></i>
                <span class="display-time"></span>
            </div>
        </div>
    </div>

    {{-- ALERTS --}}
    @if (session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif
    @if (session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    {{-- MAIN FORM --}}
    <form id="soForm">

        {{-- SALES ORDER DETAILS SECTION --}}
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-file-invoice"></i>
                <h2>Sales Order Details</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-3">
                        <label class="form-label">Sales Order No <span class="required-star">*</span></label>
                        <input type="text" class="form-control" id="sOrderNo" readonly required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Sales Order Date <span class="required-star">*</span></label>
                        <input type="date" class="form-control" id="sOrderDate" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Quotation</label>
                        <select class="form-control selectpicker" id="quotationSelect" data-live-search="true">
                            <option value="">Select Quotation</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Quotation Date</label>
                        <input type="date" class="form-control" id="quotationDate">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-3">
                        <label class="form-label">GRN No</label>
                        <input type="text" class="form-control" id="grnNo" placeholder="GRN Number">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Customer Reference No</label>
                        <input type="text" class="form-control" id="custRefNo" placeholder="Customer Ref No">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Customer SO Document</label>
                        <input type="file" class="form-control" id="customerSO" name="customerSO" accept=".pdf">
                    </div>
                </div>
            </div>
        </div>

        {{-- CUSTOMER INFORMATION SECTION --}}
        <div class="section-card">
            <div class="section-header info">
                <i class="fas fa-user"></i>
                <h2>Customer Information</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6">
                        <label class="form-label">Company Name</label>
                        <select class="form-control selectpicker" id="soCompanyId" data-live-search="true">
                            <option value="">Select Company</option>
                        </select>
                        <input type="hidden" id="soCompanyName">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Address</label>
                        <input type="text" class="form-control" id="soCompanyAddress" placeholder="Company Address">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-4">
                        <label class="form-label">GST No</label>
                        <input type="text" class="form-control" id="soCompanyGSTN" placeholder="GSTIN">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Phone</label>
                        <input type="tel" class="form-control" id="soCompanyPhone" placeholder="Contact Number">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" id="soCompanyEmail" placeholder="Email Address">
                    </div>
                </div>
            </div>
        </div>

        {{-- RFQ & PRODUCT INFORMATION SECTION --}}
        <div class="section-card">
            <div class="section-header success">
                <i class="fas fa-box"></i>
                <h2>RFQ & Product Information</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-3">
                        <label class="form-label">RFQ No</label>
                        <input type="text" class="form-control" id="rfqNo" placeholder="RFQ Number">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">RFQ Date</label>
                        <input type="date" class="form-control" id="rfqDate">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Part No</label>
                        <input type="text" class="form-control" id="partNo" placeholder="Part Number">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Project/Material No</label>
                        <input type="text" class="form-control" id="projectMaterialNo" placeholder="Project Material No">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-3">
                        <label class="form-label">Drawing No</label>
                        <input type="text" class="form-control" id="drawingId" placeholder="Drawing Number">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">Drawing Revision</label>
                        <input type="text" class="form-control" id="drawingRevision" placeholder="Revision">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Product Type</label>
                        <input type="text" class="form-control" id="productType" placeholder="Product Type">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-12">
                        <label class="form-label">Description / Notes</label>
                        <textarea class="form-control" id="projectDescription" rows="2" placeholder="Project Description"></textarea>
                    </div>
                </div>
            </div>
        </div>

        {{-- BILLING & SHIPPING SECTION --}}
        <div class="section-card">
            <div class="section-header warning">
                <i class="fas fa-shipping-fast"></i>
                <h2>Billing & Shipping</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6">
                        <label class="form-label">Bill To</label>
                        <textarea class="form-control" id="billAddress" rows="2" placeholder="Billing Address"></textarea>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Ship To</label>
                        <textarea class="form-control" id="shipAddress" rows="2" placeholder="Shipping Address"></textarea>
                    </div>
                </div>
            </div>
        </div>

        {{-- PRODUCT ITEMS SECTION --}}
        <div class="section-card">
            <div class="section-header secondary">
                <i class="fas fa-list"></i>
                <h2>Product Items</h2>
            </div>
            <div class="section-body">
                <div class="table-responsive">
                    <table id="productTable" class="table table-sm product-table" style="min-width: 1400px;">
                        <thead>
                            <tr>
                                <th width="50">#</th>
                                <th width="130">Material Code</th>
                                <th width="110">HSN Code</th>
                                <th width="200">Description</th>
                                <th width="180">Additional Details</th>
                                <th width="130">Req By Date</th>
                                <th width="80">Qty</th>
                                <th width="80">UOM</th>
                                <th width="110">Unit Rate</th>
                                <th width="80">Disc %</th>
                                <th width="110">Value</th>
                                <th width="80">SGST %</th>
                                <th width="80">CGST %</th>
                                <th width="80">IGST %</th>
                                <th width="120">Amount</th>
                                <th width="50"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="text-center">1</td>
                                <td><input type="text" class="form-control form-control-sm material-code"></td>
                                <td><input type="text" class="form-control form-control-sm hsn-code"></td>
                                <td><textarea class="form-control form-control-sm description" rows="1"></textarea></td>
                                <td><textarea class="form-control form-control-sm additional-details" rows="1"></textarea></td>
                                <td><input type="date" class="form-control form-control-sm req-by-date"></td>
                                <td><input type="number" class="form-control form-control-sm quantity" min="0"></td>
                                <td><input type="text" class="form-control form-control-sm uom"></td>
                                <td><input type="number" class="form-control form-control-sm rate" step="0.01" min="0"></td>
                                <td><input type="number" class="form-control form-control-sm discount" step="0.01" min="0" max="100"></td>
                                <td><input type="number" class="form-control form-control-sm value" readonly></td>
                                <td><input type="number" class="form-control form-control-sm sgst" step="0.01" min="0"></td>
                                <td><input type="number" class="form-control form-control-sm cgst" step="0.01" min="0"></td>
                                <td><input type="number" class="form-control form-control-sm igst" step="0.01" min="0"></td>
                                <td><input type="number" class="form-control form-control-sm amount" readonly></td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="add-row-container">
                    <button type="button" class="btn btn-primary btn-sm" id="addRowBtn">
                        <i class="fas fa-plus mr-1"></i> Add Row
                    </button>
                </div>
            </div>
        </div>

        {{-- SUMMARY SECTION --}}
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-calculator"></i>
                <h2>Summary</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6">
                        <label class="form-label">Grand Total in Words (INR)</label>
                        <input type="text" class="form-control" id="GT-in-letters" readonly>
                    </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 total-row">Grand Total:</td>
                                    <td class="total-row"><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>

        {{-- FORM ACTIONS --}}
        <div class="footer-actions">
            <a href="{{ route('superadmin.sales.salesdetails') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to List
            </a>
            <div>
                <button type="button" class="btn btn-danger" onclick="resetForm()">
                    <i class="fas fa-undo"></i> Clear Form
                </button>
                <button type="submit" class="btn btn-success" id="submitBtn">
                    <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                    <i class="fas fa-save" id="submitIcon"></i>
                    <span id="submitText">Save Sales Order</span>
                </button>
            </div>
        </div>
    </form>
</div>
@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></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);

$(document).ready(function() {
    // Initialize selectpicker
    $('.selectpicker').selectpicker();

    // Set today's date
    document.getElementById('sOrderDate').value = new Date().toISOString().split('T')[0];

    // Generate SO Number
    generateSONumber();

    // Load Quotations
    loadQuotations();

    // Load Companies
    loadCompanies();

    // Setup initial row event listeners
    setupRowEventListeners(document.querySelector("#productTable tbody tr"));

    // Add Row button
    $('#addRowBtn').click(function() {
        addRow();
    });

    // Form submit
    $('#soForm').on('submit', function(e) {
        e.preventDefault();
        saveSO();
    });

    // Quotation select change
    $('#quotationSelect').on('change', function() {
        loadQuotationDetails(this.value);
    });

    // Company select change - load customer details
    $('#soCompanyId').on('change', function() {
        loadCustomerDetails(this.value);
    });

    // Calculate totals initially
    calculateAllTotals();
});

// Generate SO Number
async function generateSONumber() {
    try {
        const response = await fetch("{{ url('superadmin/generate-so-id') }}");
        const data = await response.json();
        document.getElementById('sOrderNo').value = data.so_id;
    } catch (error) {
        document.getElementById('sOrderNo').value = 'UEPL/SO/0001';
    }
}

// Load Quotations
async function loadQuotations() {
    try {
        const response = await fetch("{{ url('/superadmin/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);
        });
        $('.selectpicker').selectpicker('refresh');
    } catch (err) {
        console.error("Failed to load quotations:", err);
    }
}

// Load Companies
async function loadCompanies() {
    try {
        const response = await fetch("{{ url('/superadmin/customers') }}");
        const companies = await response.json();
        const select = document.getElementById("soCompanyId");
        companies.forEach(c => {
            const opt = document.createElement("option");
            opt.value = c.id;
            opt.textContent = c.company;
            select.appendChild(opt);
        });
        $('.selectpicker').selectpicker('refresh');
    } catch (err) {
        console.error("Failed to load companies:", err);
    }
}

// Load Customer Details by ID
async function loadCustomerDetails(customerId) {
    if (!customerId) return;
    try {
        const response = await fetch(`{{ url('/superadmin/customer') }}/${customerId}`);
        const data = await response.json();
        if (data.error) return;

        document.getElementById("soCompanyName").value = customerId;
        document.getElementById("soCompanyAddress").value = data.billingAddress || "";
        document.getElementById("soCompanyGSTN").value = data.gstNo || "";
        document.getElementById("soCompanyPhone").value = data.mobile || "";
        document.getElementById("soCompanyEmail").value = data.email || "";
        document.getElementById("billAddress").value = data.billingAddress || "";
        document.getElementById("shipAddress").value = data.billingAddress || "";
    } catch (err) {
        console.error("Failed to load customer details:", err);
    }
}

// Load Quotation Details
async function loadQuotationDetails(quotationId) {
    if (!quotationId) return;
    try {
        const response = await fetch(`{{ url('/superadmin/quotation') }}/${quotationId}`);
        const data = await response.json();
        if (data.error) {
            Swal.fire('Error', data.error, 'error');
            return;
        }

        // Fill form fields
        document.getElementById("quotationDate").value = data.quotation_date || "";
        // Select the company in the dropdown
        if (data.customer?.id) {
            $('#soCompanyId').val(data.customer.id);
            $('.selectpicker').selectpicker('refresh');
        }
        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?.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.note || "";
        document.getElementById("productType").value = data.product_type || "";

        // Fill first row with description and quantity
        const firstRow = document.querySelector("#productTable tbody tr");
        if (firstRow) {
            firstRow.querySelector(".description").value = data.description || "";
            firstRow.querySelector(".quantity").value = data.quantity || "";
            firstRow.querySelector(".uom").value = data.quantity_uom || "";
        }

        calculateAllTotals();
    } catch (err) {
        console.error("Failed to load quotation data:", err);
    }
}

// Add Row
function addRow() {
    const tbody = document.querySelector("#productTable tbody");
    const rowCount = tbody.querySelectorAll('tr').length;
    const newRow = document.createElement("tr");
    newRow.innerHTML = `
        <td class="text-center">${rowCount + 1}</td>
        <td><input type="text" class="form-control form-control-sm material-code"></td>
        <td><input type="text" class="form-control form-control-sm hsn-code"></td>
        <td><textarea class="form-control form-control-sm description" rows="1"></textarea></td>
        <td><textarea class="form-control form-control-sm additional-details" rows="1"></textarea></td>
        <td><input type="date" class="form-control form-control-sm req-by-date"></td>
        <td><input type="number" class="form-control form-control-sm quantity" min="0"></td>
        <td><input type="text" class="form-control form-control-sm uom"></td>
        <td><input type="number" class="form-control form-control-sm rate" step="0.01" min="0"></td>
        <td><input type="number" class="form-control form-control-sm discount" step="0.01" min="0" max="100"></td>
        <td><input type="number" class="form-control form-control-sm value" readonly></td>
        <td><input type="number" class="form-control form-control-sm sgst" step="0.01" min="0"></td>
        <td><input type="number" class="form-control form-control-sm cgst" step="0.01" min="0"></td>
        <td><input type="number" class="form-control form-control-sm igst" step="0.01" min="0"></td>
        <td><input type="number" class="form-control form-control-sm amount" readonly></td>
        <td class="text-center">
            <button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)">
                <i class="fa fa-trash"></i>
            </button>
        </td>
    `;
    tbody.appendChild(newRow);
    setupRowEventListeners(newRow);
}

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

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

// Setup Row Event Listeners
function setupRowEventListeners(row) {
    const inputs = ['quantity', 'rate', 'discount', 'sgst', 'cgst', 'igst'];
    inputs.forEach(className => {
        const input = row.querySelector(`.${className}`);
        if (input) {
            input.addEventListener('input', function() {
                calculateRowValue(row);
            });
        }
    });
}

// Calculate Row Value
function calculateRowValue(row) {
    const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
    const rate = parseFloat(row.querySelector('.rate').value) || 0;
    const discount = parseFloat(row.querySelector('.discount').value) || 0;
    const sgst = parseFloat(row.querySelector('.sgst').value) || 0;
    const cgst = parseFloat(row.querySelector('.cgst').value) || 0;
    const igst = parseFloat(row.querySelector('.igst').value) || 0;

    const baseValue = quantity * rate * (1 - discount / 100);
    row.querySelector('.value').value = baseValue.toFixed(2);

    const amount = baseValue * (1 + (sgst + cgst + igst) / 100);
    row.querySelector('.amount').value = amount.toFixed(2);

    calculateAllTotals();
}

// Calculate All Totals
function calculateAllTotals() {
    let subtotal = 0, sgstTotal = 0, cgstTotal = 0, igstTotal = 0;

    document.querySelectorAll("#productTable tbody tr").forEach(row => {
        const val = parseFloat(row.querySelector('.value').value) || 0;
        const sgst = parseFloat(row.querySelector('.sgst').value) || 0;
        const cgst = parseFloat(row.querySelector('.cgst').value) || 0;
        const igst = parseFloat(row.querySelector('.igst').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 = numberToWords(Math.round(grandTotal)) + ' Rupees Only';
}

// Get Table Data
function getTableData() {
    const rows = document.querySelectorAll("#productTable tbody tr");
    const data = [];
    rows.forEach(row => {
        data.push({
            slNo: row.cells[0].textContent,
            materialCode: row.querySelector('.material-code').value,
            hsnCode: row.querySelector('.hsn-code').value,
            description: row.querySelector('.description').value,
            additionalDetails: row.querySelector('.additional-details').value,
            reqByDate: row.querySelector('.req-by-date').value,
            quantity: row.querySelector('.quantity').value,
            uom: row.querySelector('.uom').value,
            unitRate: row.querySelector('.rate').value,
            discount: row.querySelector('.discount').value,
            value: row.querySelector('.value').value,
            sgst: row.querySelector('.sgst').value,
            cgst: row.querySelector('.cgst').value,
            igst: row.querySelector('.igst').value,
            amount: row.querySelector('.amount').value
        });
    });
    return data;
}

// Save SO
async function saveSO() {
    const $btn = $('#submitBtn');
    const $spinner = $btn.find('.spinner-border');
    const $icon = $('#submitIcon');
    const $text = $('#submitText');

    // Validation
    if (!document.getElementById('sOrderNo').value || !document.getElementById('sOrderDate').value) {
        Swal.fire('Error', 'Sales Order No and Date are required!', 'error');
        return;
    }

    $btn.prop('disabled', true);
    $spinner.removeClass('d-none');
    $icon.addClass('d-none');
    $text.text('Saving...');

    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('soCompanyId').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: (() => {
            const sel = document.getElementById('quotationSelect');
            const text = sel.options[sel.selectedIndex]?.text;
            return (text && text !== 'Select Quotation') ? text : null;
        })(),
        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()
    };

    try {
        const response = await fetch("{{ route('superadmin.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();

        if (data.message && data.message.includes('Sales Order saved')) {
            Swal.fire('Success!', data.message, 'success').then(() => {
                window.location.href = "{{ route('superadmin.sales.salesdetails') }}";
            });
        } else {
            Swal.fire('Error!', data.message || data.error || 'Something went wrong.', 'error');
        }
    } catch (err) {
        Swal.fire('Error!', 'Failed to save sales order.', 'error');
        console.error("Save error:", err);
    } finally {
        $btn.prop('disabled', false);
        $spinner.addClass('d-none');
        $icon.removeClass('d-none');
        $text.text('Save Sales Order');
    }
}

// Reset Form
function resetForm() {
    Swal.fire({
        title: 'Clear Form?',
        text: 'Are you sure you want to clear all fields?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#e74a3b',
        cancelButtonColor: '#858796',
        confirmButtonText: 'Yes, clear it!'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('soForm').reset();
            generateSONumber();
            document.getElementById('sOrderDate').value = new Date().toISOString().split('T')[0];
            $('.selectpicker').selectpicker('refresh');
            calculateAllTotals();
        }
    });
}

// Number to Words (Indian Format)
function numberToWords(num) {
    if (num === 0) return 'Zero';

    const ones = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine',
                  'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen',
                  'Seventeen', 'Eighteen', 'Nineteen'];
    const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];

    function convertLessThanHundred(n) {
        if (n < 20) return ones[n];
        return tens[Math.floor(n / 10)] + (n % 10 ? ' ' + ones[n % 10] : '');
    }

    function convertLessThanThousand(n) {
        if (n < 100) return convertLessThanHundred(n);
        return ones[Math.floor(n / 100)] + ' Hundred' + (n % 100 ? ' ' + convertLessThanHundred(n % 100) : '');
    }

    if (num < 0) return 'Negative ' + numberToWords(-num);
    if (num < 1000) return convertLessThanThousand(num);
    if (num < 100000) {
        return convertLessThanHundred(Math.floor(num / 1000)) + ' Thousand' +
               (num % 1000 ? ' ' + convertLessThanThousand(num % 1000) : '');
    }
    if (num < 10000000) {
        return convertLessThanHundred(Math.floor(num / 100000)) + ' Lakh' +
               (num % 100000 ? ' ' + numberToWords(num % 100000) : '');
    }
    return convertLessThanHundred(Math.floor(num / 10000000)) + ' Crore' +
           (num % 10000000 ? ' ' + numberToWords(num % 10000000) : '');
}
</script>
@endsection
