@extends('layouts.dashboard.superadminapp')

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

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

@section('content')
<div class="container-fluid theme-purple">
    <!-- Modern Page Header -->
    <div class="modern-page-header">
        <div class="header-left">
            <div class="icon-wrapper">
                <i class="fas fa-shopping-cart"></i>
            </div>
            <div class="header-title">
                <h1>Edit Sales Order</h1>
                <div class="header-subtitle">{{ $order->sales_order_no }}</div>
            </div>
        </div>
        <div class="datetime-display">
            <div class="date-box">
                <i class="far fa-calendar-alt"></i>
                <span id="day">{{ now()->format('l') }}</span>,
                <span id="daynum">{{ now()->format('d') }}</span>
                <span id="month">{{ now()->format('F') }}</span>
                <span id="year">{{ now()->format('Y') }}</span>
            </div>
            <div class="time-box">
                <i class="far fa-clock"></i>
                <span class="display-time"></span>
            </div>
        </div>
    </div>

    <!-- 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" action="{{ route('superadmin.sales.order.update', $order->id) }}" method="POST">
        @csrf
        @method('PUT')

        <!-- 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 mb-3">
                        <label class="form-label">Sales Order No <span class="required-star">*</span></label>
                        <input type="text" class="form-control" id="sOrderNo" name="sales_order_no" value="{{ $order->sales_order_no }}" readonly required>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Sales Order Date <span class="required-star">*</span></label>
                        <input type="date" class="form-control" id="sOrderDate" name="sales_order_date" value="{{ $order->sales_order_date ? $order->sales_order_date->format('Y-m-d') : '' }}" required>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Quotation</label>
                        <input type="text" class="form-control" value="{{ $order->quotation->quotation_no ?? 'N/A' }}" readonly>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">GRN No</label>
                        <input type="text" class="form-control" id="grnNo" name="grn_no" value="{{ $order->grn_no }}" placeholder="GRN Number">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Customer Reference No</label>
                        <input type="text" class="form-control" id="custRefNo" name="customer_ref_no" value="{{ $order->customer_ref_no }}" placeholder="Customer Ref No">
                    </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 mb-3">
                        <label class="form-label">Company Name</label>
                        <input type="text" class="form-control" value="{{ $order->customer->company ?? 'N/A' }}" readonly>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Address</label>
                        <input type="text" class="form-control" id="soCompanyAddress" name="company_address" value="{{ $order->company_address }}" placeholder="Company Address">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">GST No</label>
                        <input type="text" class="form-control" id="soCompanyGSTN" name="company_gstn" value="{{ $order->company_gstn }}" placeholder="GSTIN">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Phone</label>
                        <input type="tel" class="form-control" id="soCompanyPhone" name="company_phone" value="{{ $order->company_phone }}" placeholder="Contact Number">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" id="soCompanyEmail" name="company_email" value="{{ $order->company_email }}" 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 mb-3">
                        <label class="form-label">RFQ No</label>
                        <input type="text" class="form-control" value="{{ $order->rfq_no }}" readonly>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">RFQ Date</label>
                        <input type="date" class="form-control" value="{{ $order->rfq_date ? $order->rfq_date->format('Y-m-d') : '' }}" readonly>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Part No</label>
                        <input type="text" class="form-control" value="{{ $order->part_no }}" readonly>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Project/Material No</label>
                        <input type="text" class="form-control" value="{{ $order->project_material_no }}" readonly>
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Drawing No</label>
                        <input type="text" class="form-control" value="{{ $order->drawing_no }}" readonly>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Drawing Revision</label>
                        <input type="text" class="form-control" value="{{ $order->drawing_rev }}" readonly>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Product Type</label>
                        <input type="text" class="form-control" value="{{ $order->product_type }}" readonly>
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-12 mb-3">
                        <label class="form-label">Description / Notes</label>
                        <textarea class="form-control" rows="2" readonly>{{ $order->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 mb-3">
                        <label class="form-label">Bill To</label>
                        <textarea class="form-control" id="billAddress" name="bill_address" rows="2" placeholder="Billing Address">{{ $order->bill_address }}</textarea>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Ship To</label>
                        <textarea class="form-control" id="shipAddress" name="ship_address" rows="2" placeholder="Shipping Address">{{ $order->ship_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-modern table-bordered" 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>
                            @foreach($order->items as $index => $item)
                            <tr>
                                <td class="text-center">{{ $index + 1 }}</td>
                                <td><input type="text" class="form-control material-code" value="{{ $item->material_code ?? '' }}"></td>
                                <td><input type="text" class="form-control hsn-code" value="{{ $item->hsn_code ?? '' }}"></td>
                                <td><textarea class="form-control description" rows="1">{{ $item->material_description ?? '' }}</textarea></td>
                                <td><textarea class="form-control additional-details" rows="1">{{ $item->additional_details ?? '' }}</textarea></td>
                                <td><input type="date" class="form-control req-by-date" value="{{ $item->required_by_date ?? '' }}"></td>
                                <td><input type="number" class="form-control quantity" value="{{ $item->quantity ?? 0 }}" min="0"></td>
                                <td><input type="text" class="form-control uom" value="{{ $item->uom ?? '' }}"></td>
                                <td><input type="number" class="form-control rate" value="{{ $item->unit_rate ?? 0 }}" step="0.01" min="0"></td>
                                <td><input type="number" class="form-control discount" value="{{ $item->discount ?? 0 }}" step="0.01" min="0" max="100"></td>
                                <td><input type="number" class="form-control value" value="{{ $item->value ?? 0 }}" readonly></td>
                                <td><input type="number" class="form-control sgst" value="{{ $item->sgst ?? 0 }}" step="0.01" min="0"></td>
                                <td><input type="number" class="form-control cgst" value="{{ $item->cgst ?? 0 }}" step="0.01" min="0"></td>
                                <td><input type="number" class="form-control igst" value="{{ $item->igst ?? 0 }}" step="0.01" min="0"></td>
                                <td><input type="number" class="form-control amount" value="{{ $item->amount ?? 0 }}" 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>
                            @endforeach
                        </tbody>
                    </table>
                </div>
                <div class="mt-3">
                    <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 success">
                <i class="fas fa-calculator"></i>
                <h2>Summary</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Grand Total in Words (INR)</label>
                        <input type="text" class="form-control" id="GT-in-letters" name="inr_in_words" value="{{ $order->inr_in_words }}" 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">Sub Total:</td>
                                    <td width="150"><input type="text" id="totalAmount" name="subtotal" value="{{ $order->subtotal }}" 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" name="sgst_amount" value="{{ $order->sgst_amount }}" 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" name="cgst_amount" value="{{ $order->cgst_amount }}" 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" name="igst_amount" value="{{ $order->igst_amount }}" 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" name="round_up" value="{{ $order->round_up }}" readonly class="form-control form-control-sm text-right"></td>
                                </tr>
                                <tr class="border-top">
                                    <td class="text-right font-weight-bold">Grand Total:</td>
                                    <td><input type="text" id="grandTotal" name="grand_total" value="{{ $order->grand_total }}" readonly class="form-control form-control-sm text-right font-weight-bold"></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer Actions -->
        <div class="footer-actions">
            <a href="{{ route('superadmin.sales.salesdetails') }}" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to List
            </a>
            <div>
                <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">Update 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);

let productRowCounter = {{ $order->items->count() }};

$(document).ready(function() {
    // Setup event listeners for existing rows
    document.querySelectorAll("#productTable tbody tr").forEach(row => {
        setupRowEventListeners(row);
    });

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

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

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

// 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);
    productRowCounter++;
}

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

// Update SO
async function updateSO() {
    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('Updating...');

    const formData = {
        soNo1: document.getElementById('sOrderNo').value,
        soDate: document.getElementById('sOrderDate').value,
        grnNo1: document.getElementById('grnNo').value,
        custRefSoNo: document.getElementById('custRefNo').value,
        companyName: @json($order->company_name ?? ''),
        soCompanyAddress: document.getElementById('soCompanyAddress').value,
        soCompanyGSTN: document.getElementById('soCompanyGSTN').value,
        soCompanyPhone: document.getElementById('soCompanyPhone').value,
        soCompanyEmail: document.getElementById('soCompanyEmail').value,
        quotationId: @json($order->quotation_no ?? ''),
        quotationDate: '{{ $order->quotation_date ? $order->quotation_date->format("Y-m-d") : "" }}',
        billAddress: document.getElementById('billAddress').value,
        shipAddress: document.getElementById('shipAddress').value,
        productType: @json($order->product_type ?? ''),
        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: @json($order->rfq_no ?? ''),
        rfqDate: '{{ $order->rfq_date ? $order->rfq_date->format("Y-m-d") : "" }}',
        partNo: @json($order->part_no ?? ''),
        projectMaterialNo: @json($order->project_material_no ?? ''),
        drawingId: @json($order->drawing_no ?? ''),
        drawingRevision: @json($order->drawing_rev ?? ''),
        projectDescription: @json($order->description ?? ''),
        tableProducts: getTableData()
    };

    try {
        const response = await fetch("{{ route('superadmin.sales.order.update', $order->id) }}", {
            method: 'PUT',
            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('updated successfully')) {
            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 update sales order.', 'error');
        console.error("Update error:", err);
    } finally {
        $btn.prop('disabled', false);
        $spinner.addClass('d-none');
        $icon.removeClass('d-none');
        $text.text('Update Sales Order');
    }
}

// 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
