@extends('layouts.dashboard.superadminapp')

@section('title', 'Create Tax Invoice')

@section('styles')
<style>
    .section-card {
        border: none;
        border-radius: 0.5rem;
        box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
        margin-bottom: 1.5rem;
    }
    .section-card .card-header {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: #fff;
        font-weight: 600;
        padding: 0.75rem 1rem;
        border-radius: 0.5rem 0.5rem 0 0 !important;
        font-size: 0.9rem;
    }
    .section-card .card-header.bg-success-gradient {
        background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
    }
    .section-card .card-header.bg-info-gradient {
        background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);
    }
    .section-card .card-header.bg-warning-gradient {
        background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);
    }
    .section-card .card-header.bg-secondary-gradient {
        background: linear-gradient(135deg, #858796 0%, #60616f 100%);
    }
    .section-card .card-header.bg-danger-gradient {
        background: linear-gradient(135deg, #e74a3b 0%, #be2617 100%);
    }
    .form-group label {
        font-weight: 600;
        font-size: 0.85rem;
        color: #5a5c69;
        margin-bottom: 0.25rem;
    }
    .form-control, .form-control-sm {
        font-size: 0.85rem;
    }
    .required {
        color: #e74a3b;
    }
    .invoice-table {
        width: 100%;
        font-size: 0.8rem;
    }
    .invoice-table th {
        background-color: #f8f9fc;
        font-weight: 600;
        font-size: 0.75rem;
        text-align: center;
        padding: 0.5rem;
        white-space: nowrap;
    }
    .invoice-table td {
        padding: 0.35rem;
        vertical-align: middle;
    }
    .invoice-table input, .invoice-table textarea {
        font-size: 0.8rem;
        padding: 0.25rem 0.5rem;
        text-align: center;
    }
    .invoice-table .btn-sm {
        padding: 0.2rem 0.4rem;
        font-size: 0.7rem;
    }
    .totals-section {
        background: #f8f9fc;
        border-radius: 0.5rem;
        padding: 1rem;
    }
    .totals-section .form-group {
        margin-bottom: 0.5rem;
    }
    .totals-section label {
        font-size: 0.8rem;
    }
    .totals-section input {
        text-align: right;
        font-weight: 600;
    }
    .company-info {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 1.25rem;
        border-radius: 0.5rem;
    }
    .company-info h5 {
        font-weight: 700;
        margin-bottom: 0.75rem;
    }
    .company-info p {
        margin-bottom: 0.25rem;
        font-size: 0.85rem;
    }
    .bank-info {
        background: #f8f9fc;
        border-radius: 0.5rem;
        padding: 1rem;
    }
    .bank-info h6 {
        color: #4e73df;
        font-weight: 700;
        margin-bottom: 0.75rem;
    }
    .bank-info p {
        margin-bottom: 0.25rem;
        font-size: 0.85rem;
    }
</style>
@endsection

@section('content')
    <!-- Page Heading -->
    <div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h5 mb-0 text-gray-800">UEPL | Create Tax Invoice</h1>
        <div class="display-date">
            <span id="day">day</span>,
            <span id="daynum">00</span>
            <span id="month">month</span>
            <span id="year">0000</span>
        </div>
        <div class="display-time"></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
    @if ($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle mr-2"></i><strong>Validation Errors:</strong>
            <ul class="mb-0 mt-2">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    @endif

    <form id="invoiceForm" action="{{ route('superadmin.tax-invoice.store') }}" method="POST" enctype="multipart/form-data">
        @csrf

        <!-- Invoice & Company Information -->
        <div class="card section-card">
            <div class="card-header">
                <i class="fas fa-file-invoice mr-2"></i> Invoice Information
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="company-info">
                            <h5><i class="fas fa-building mr-2"></i>UMBREY ENGINEERING PVT LTD</h5>
                            <p>No. 31, 2nd Phase, Peenya Industrial Area</p>
                            <p>Bengaluru 560 058, Karnataka, India</p>
                            <p><strong>GSTN:</strong> 29AAACU2461N1ZY</p>
                            <p><strong>PAN:</strong> AAACU2461N</p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="invoiceNo">Invoice No <span class="required">*</span></label>
                                    <input type="text" class="form-control" id="invoiceNo" name="invoice_no" readonly required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="invoiceDate">Invoice Date <span class="required">*</span></label>
                                    <input type="date" class="form-control" id="invoiceDate" name="invoice_date" required>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="deliveryNote">Delivery Note</label>
                                    <input type="text" class="form-control" id="deliveryNote" name="delivery_note" placeholder="Delivery Note">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="termsPayment">Mode/Terms of Payment</label>
                                    <input type="text" class="form-control" id="termsPayment" name="terms_payment" placeholder="Payment Terms">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="ReferenceNo">Reference Number</label>
                                    <input type="text" class="form-control" id="ReferenceNo" name="reference_no" placeholder="Reference No">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="otherreference">Other Reference</label>
                                    <input type="text" class="form-control" id="otherreference" name="other_reference" placeholder="Other Reference">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Buyer Information -->
        <div class="card section-card">
            <div class="card-header bg-success-gradient">
                <i class="fas fa-user mr-2"></i> Buyer Information (Bill To)
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="companyNameSelect">Customer <span class="required">*</span></label>
                            <select class="form-control selectpicker" id="companyNameSelect" name="company" data-live-search="true" required>
                                <option value="">Select Customer</option>
                                @foreach ($companies as $company)
                                    <option value="{{ $company->id }}">{{ $company->company }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="cCompanyAddress">Address</label>
                            <textarea class="form-control" id="cCompanyAddress" name="address" rows="2" placeholder="Customer Address"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="cCompanyGst">GST No</label>
                                    <input type="text" class="form-control" id="cCompanyGst" name="gst" placeholder="GSTIN">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="cCompanyPhone">Phone</label>
                                    <input type="tel" class="form-control" id="cCompanyPhone" name="phone" placeholder="Contact Number">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="cCompanyEmail">Email</label>
                            <input type="email" class="form-control" id="cCompanyEmail" name="email" placeholder="Email Address">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="orderNoSelect">Sales Order No</label>
                                    <select class="form-control selectpicker" id="orderNoSelect" name="order_no" data-live-search="true">
                                        <option value="">Select Order</option>
                                        @foreach($sales_orders as $order)
                                            <option value="{{ $order->id }}">{{ $order->sales_order_no }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="referenceDate">Order Date</label>
                                    <input type="date" class="form-control" id="referenceDate" name="reference_date">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="dispatchthrough">Dispatched Through</label>
                                    <input type="text" class="form-control" id="dispatchthrough" name="dispatch_through" placeholder="Dispatch Method">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="destination">Destination</label>
                                    <input type="text" class="form-control" id="destination" name="destination" placeholder="Destination">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="vehicleNo">Vehicle Number</label>
                                    <input type="text" class="form-control" id="vehicleNo" name="vehicle_no" placeholder="Vehicle No">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="termsDelivery">Terms of Delivery</label>
                                    <input type="text" class="form-control" id="termsDelivery" name="terms_of_delivery" placeholder="Delivery Terms">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Invoice Items Table -->
        <div class="card section-card">
            <div class="card-header bg-warning-gradient">
                <i class="fas fa-list mr-2"></i> Invoice Items
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="invoiceTable" class="table table-bordered invoice-table">
                        <thead>
                            <tr>
                                <th style="width:4%">#</th>
                                <th style="width:22%">Description of Goods</th>
                                <th style="width:8%">HSN/SAC</th>
                                <th style="width:8%">Quantity</th>
                                <th style="width:10%">Rate</th>
                                <th style="width:6%">Per</th>
                                <th style="width:8%">SGST %</th>
                                <th style="width:8%">CGST %</th>
                                <th style="width:8%">IGST %</th>
                                <th style="width:12%">Amount</th>
                                <th style="width:6%"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td class="text-center">1</td>
                                <td><textarea class="form-control form-control-sm description" name="description[]" rows="1"></textarea></td>
                                <td><input type="text" class="form-control form-control-sm hsn" name="hsn[]"></td>
                                <td><input type="number" class="form-control form-control-sm quantity" name="quantity[]" min="0" oninput="calculateRow(this)"></td>
                                <td><input type="number" class="form-control form-control-sm rate" name="rate[]" min="0" step="0.01" oninput="calculateRow(this)"></td>
                                <td><input type="text" class="form-control form-control-sm per" name="per[]"></td>
                                <td><input type="number" class="form-control form-control-sm sgst" name="sgst[]" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
                                <td><input type="number" class="form-control form-control-sm cgst" name="cgst[]" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
                                <td><input type="number" class="form-control form-control-sm igst" name="igst[]" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
                                <td><input type="text" class="form-control form-control-sm amount" name="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>
                <button type="button" class="btn btn-outline-primary btn-sm mt-2" onclick="addRow()">
                    <i class="fas fa-plus mr-1"></i> Add Item
                </button>
            </div>
        </div>

        <!-- Tax Calculation & Totals -->
        <div class="card section-card">
            <div class="card-header bg-info-gradient">
                <i class="fas fa-calculator mr-2"></i> Tax Calculation & Totals
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="amountInWords">Grand Total in Words (INR)</label>
                            <textarea class="form-control" id="amountInWords" name="amount_in_words" rows="2" readonly></textarea>
                        </div>
                        <div class="form-group">
                            <label for="grandTotal">Grand Total</label>
                            <input type="text" class="form-control form-control-lg font-weight-bold text-success" id="grandTotal" name="total_amount" readonly>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="totals-section">
                            <h6 class="font-weight-bold text-primary mb-3"><i class="fas fa-receipt mr-2"></i>Tax Summary</h6>
                            <div class="form-group row align-items-center">
                                <label class="col-md-4 col-form-label">Taxable Value</label>
                                <div class="col-md-8">
                                    <input type="text" class="form-control" id="totalAmount" name="taxable_value" readonly>
                                </div>
                            </div>
                            <div class="form-group row align-items-center">
                                <label class="col-md-4 col-form-label">SGST</label>
                                <div class="col-md-8">
                                    <input type="number" class="form-control" id="sgst" name="sgst_total" readonly>
                                </div>
                            </div>
                            <div class="form-group row align-items-center">
                                <label class="col-md-4 col-form-label">CGST</label>
                                <div class="col-md-8">
                                    <input type="number" class="form-control" id="cgst" name="cgst_total" readonly>
                                </div>
                            </div>
                            <div class="form-group row align-items-center">
                                <label class="col-md-4 col-form-label">IGST</label>
                                <div class="col-md-8">
                                    <input type="number" class="form-control" id="igst" name="igst_total" readonly>
                                </div>
                            </div>
                            <hr>
                            <div class="form-group row align-items-center mb-0">
                                <label class="col-md-4 col-form-label font-weight-bold">Total Tax</label>
                                <div class="col-md-8">
                                    <input type="number" class="form-control font-weight-bold" id="totalTax" name="total_tax_amount" readonly>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Bank Details & Declaration -->
        <div class="card section-card">
            <div class="card-header bg-secondary-gradient">
                <i class="fas fa-university mr-2"></i> Bank Details & Declaration
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="bank-info">
                            <h6><i class="fas fa-landmark mr-2"></i>Company's Bank Details</h6>
                            <p><strong>A/c Holder:</strong> UMBREY ENGINEERING PVT LTD</p>
                            <p><strong>Bank Name:</strong> ICICI BANK C/A</p>
                            <p><strong>A/c No:</strong> 193505000015</p>
                            <p><strong>Branch & IFS Code:</strong> PEENYA BRANCH & ICIC0001935</p>
                            <p class="mt-3"><strong>Company's PAN:</strong> AAACU2461N</p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="border rounded p-3 h-100">
                            <h6 class="font-weight-bold text-muted mb-3"><i class="fas fa-file-signature mr-2"></i>Declaration</h6>
                            <p class="text-muted" style="font-size: 0.85rem;">
                                We declare that this invoice shows the actual price of the goods described and that all particulars are true and correct.
                            </p>
                            <hr>
                            <div class="text-right mt-4">
                                <p class="font-weight-bold mb-1">For Umbrey Engineering PVT LTD</p>
                                <br><br>
                                <p class="text-muted mb-0">Authorised Signatory</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="card section-card">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <a href="{{ route('superadmin.invoice.invoicedetails') }}" class="btn btn-secondary">
                        <i class="fas fa-arrow-left mr-1"></i> Back to List
                    </a>
                    <div>
                        <button type="reset" class="btn btn-danger mr-2" onclick="resetForm()">
                            <i class="fas fa-times mr-1"></i> Clear
                        </button>
                        <button type="submit" class="btn btn-success" id="submitBtn">
                            <span class="spinner-border spinner-border-sm d-none" role="status"></span>
                            <span class="btn-text"><i class="fas fa-save mr-1"></i> Save Invoice</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </form>
@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    // Initialize selectpicker
    $('.selectpicker').selectpicker();

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

    // Generate Invoice Number
    $.ajax({
        url: '{{ route('superadmin.invoice.generate') }}',
        type: 'GET',
        success: function(response) {
            $('#invoiceNo').val(response.invoice_no);
        },
        error: function() {
            Swal.fire('Error', 'Failed to generate Invoice ID', 'error');
        }
    });

    // Company select change
    $('#companyNameSelect').on('change', function() {
        let companyId = $(this).val();
        if (!companyId) {
            $('#cCompanyAddress').val('');
            $('#cCompanyGst').val('');
            $('#cCompanyEmail').val('');
            $('#cCompanyPhone').val('');
            return;
        }
        $.get("{{ url('superadmin/customer-vendor') }}/" + companyId, function(data) {
            if (data.success) {
                $('#cCompanyAddress').val(data.company.billing_address || '');
                $('#cCompanyGst').val(data.company.gst || '');
                $('#cCompanyEmail').val(data.company.email || '');
                $('#cCompanyPhone').val(data.company.mobile || '');
            }
        });
    });

    // Sales Order select change
    const salesOrders = @json($sales_orders);
    $('#orderNoSelect').on('change', function() {
        const selectedOrderId = $(this).val();
        const order = salesOrders.find(o => o.id == selectedOrderId);
        if (!order) return;

        $('#referenceDate').val(order.sales_order_date);
        $('#companyNameSelect').val(order.company_name);
        $('.selectpicker').selectpicker('refresh');
        $('#companyNameSelect').trigger('change');

        const tbody = $('#invoiceTable tbody');
        tbody.empty();

        (order.items || []).forEach((item, index) => {
            const row = `
                <tr>
                    <td class="text-center">${index + 1}</td>
                    <td><textarea class="form-control form-control-sm description" name="description[]" rows="1">${item.material_code ? item.material_code + '-' : ''}${item.material_description || ''}</textarea></td>
                    <td><input type="text" class="form-control form-control-sm hsn" name="hsn[]" value="${item.hsn_code || ''}"></td>
                    <td><input type="number" class="form-control form-control-sm quantity" name="quantity[]" value="${item.quantity || 0}" min="0" oninput="calculateRow(this)"></td>
                    <td><input type="number" class="form-control form-control-sm rate" name="rate[]" value="${item.unit_rate || 0}" min="0" step="0.01" oninput="calculateRow(this)"></td>
                    <td><input type="text" class="form-control form-control-sm per" name="per[]" value="${item.uom || ''}"></td>
                    <td><input type="number" class="form-control form-control-sm sgst" name="sgst[]" value="${item.sgst || 0}" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
                    <td><input type="number" class="form-control form-control-sm cgst" name="cgst[]" value="${item.cgst || 0}" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
                    <td><input type="number" class="form-control form-control-sm igst" name="igst[]" value="${item.igst || 0}" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
                    <td><input type="text" class="form-control form-control-sm amount" name="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.append(row);
        });

        // Calculate all rows
        $('#invoiceTable tbody tr').each(function() {
            const qtyInput = $(this).find('input.quantity')[0];
            if (qtyInput) calculateRow(qtyInput);
        });

        updateTotal();
    });

    // Form submit with loading
    $('#invoiceForm').on('submit', function() {
        const $btn = $('#submitBtn');
        $btn.prop('disabled', true);
        $btn.find('.spinner-border').removeClass('d-none');
        $btn.find('.btn-text').text('Saving...');
    });
});

// Add Row
function addRow() {
    const table = document.getElementById("invoiceTable").getElementsByTagName("tbody")[0];
    const rowCount = table.rows.length;
    const newRow = table.insertRow(rowCount);

    newRow.innerHTML = `
        <td class="text-center">${rowCount + 1}</td>
        <td><textarea class="form-control form-control-sm description" name="description[]" rows="1"></textarea></td>
        <td><input type="text" class="form-control form-control-sm hsn" name="hsn[]"></td>
        <td><input type="number" class="form-control form-control-sm quantity" name="quantity[]" min="0" oninput="calculateRow(this)"></td>
        <td><input type="number" class="form-control form-control-sm rate" name="rate[]" min="0" step="0.01" oninput="calculateRow(this)"></td>
        <td><input type="text" class="form-control form-control-sm per" name="per[]"></td>
        <td><input type="number" class="form-control form-control-sm sgst" name="sgst[]" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
        <td><input type="number" class="form-control form-control-sm cgst" name="cgst[]" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
        <td><input type="number" class="form-control form-control-sm igst" name="igst[]" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
        <td><input type="text" class="form-control form-control-sm amount" name="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>
    `;
}

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

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

// Calculate Row
function calculateRow(element) {
    const row = element.closest("tr");
    const quantity = parseFloat(row.querySelector(".quantity").value) || 0;
    const rate = parseFloat(row.querySelector(".rate").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 baseAmount = quantity * rate;
    const totalTax = baseAmount * (sgst + cgst + igst) / 100;
    const amount = baseAmount + totalTax;
    row.querySelector(".amount").value = amount.toFixed(2);

    updateTotal();
}

// Update Totals
function updateTotal() {
    let taxableTotal = 0, totalAmount = 0, totalSgst = 0, totalCgst = 0, totalIgst = 0, totalTax = 0;

    document.querySelectorAll("#invoiceTable tbody tr").forEach(row => {
        const quantity = parseFloat(row.querySelector(".quantity").value) || 0;
        const rate = parseFloat(row.querySelector(".rate").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 baseAmount = quantity * rate;
        taxableTotal += baseAmount;
        totalAmount += baseAmount + (baseAmount * (sgst + cgst + igst) / 100);
        totalSgst += baseAmount * (sgst / 100);
        totalCgst += baseAmount * (cgst / 100);
        totalIgst += baseAmount * (igst / 100);
        totalTax += (baseAmount * (sgst + cgst + igst) / 100);
    });

    document.getElementById("totalAmount").value = taxableTotal.toFixed(2);
    document.getElementById("sgst").value = totalSgst.toFixed(2);
    document.getElementById("cgst").value = totalCgst.toFixed(2);
    document.getElementById("igst").value = totalIgst.toFixed(2);
    document.getElementById("totalTax").value = totalTax.toFixed(2);

    const roundUpAmount = Math.ceil(totalAmount) - totalAmount;
    const grandTotal = totalAmount + roundUpAmount;
    document.getElementById('grandTotal').value = grandTotal.toFixed(2);
    document.getElementById('amountInWords').value = numberToWords(Math.round(grandTotal)) + ' Rupees Only';
}

// 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) {
            location.reload();
        }
    });
}

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