@extends('layouts.dashboard.managerapp')

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

@section('content')

    <!-- Page Heading -->
    <x-layout.page-header title="UEPL / Tax Invoice Form" icon="file-invoice-dollar" iconColor="success" />
    @if (session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            {{ session('success') }}

        </div>
    @endif

    @if (session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            {{ session('error') }}

        </div>
    @endif

    @if ($errors->any())
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <strong>There were some issues with your submission:</strong>
            <ul class="mb-0">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>

        </div>
    @endif

    <!-- Content Row -->
    <div class="row quotation-page-content">
        <div class="col-lg-12">

            <!-- Project Planning Start -->
            <form id="Tax-Invoice-form" action="{{ route('manager.tax-invoice.store') }}" method="POST"
                enctype="multipart/form-data">
                @csrf
                <div class="tax-invoice-container">
                    <br>
                    <h1>Tax Invoice</h1><br><br>
                    <!-- Invoice Info Section -->
                    <div class="info-section">
                        <div class="row hidden">
                            <div class="col-md-6">
                                <div class="col-sm-3">
                                    <label for="irnNo">IRN Number <span class="required"
                                            title="required">*</span></label>
                                </div>
                                <div class="col-sm-8">
                                    <input type="text" id="irnNo">
                                </div>
                                <div class="col-sm-3">
                                    <label for="ackNo">Ack Number <span class="required"
                                            title="required">*</span></label>
                                </div>
                                <div class="col-sm-8">
                                    <input type="text" id="ackNo">
                                </div>
                                <div class="col-sm-3">
                                    <label for="ackDate">Ack Date <span class="required" title="required">*</span></label>
                                </div>
                                <div class="col-sm-6">
                                    <input type="date" id="ackDate">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <br><br>
                                <label for="qrCode">E-Invoice QR Code :</label>
                                <div id="qrCode"></div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <br>
                                <h3>UMBREY ENGINEERING PVT LTD</h3>
                                <p>No. 31, 2nd Phase, Peenya Industrial Area <br>
                                    Bengaluru 560 058, Karnataka, India<br>
                                    GSTN: 29AAACU2461N1ZY<br>
                                    PAN: AAACU2461N<br>
                                </p>
                            </div>
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="invoiceNo">Invoice ID <span class="required"
                                                title="required">*</span></label>
                                        <input type="text" id="invoiceNo" name="invoice_no" required readonly>
                                    </div>
                                    <div class="col-md-6">
                                        <label for="invoiceDate">Invoice Date <span class="required"
                                                title="required">*</span></label>
                                        <input type="date" id="invoiceDate" name="invoice_date" required>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="deliveryNote">Delivery Note</label>
                                        <input type="text" id="deliveryNote" name="delivery_note">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="termsPayment">Mode/Terms of Payment</label>
                                        <input type="text" id="termsPayment" name="terms_payment">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="ReferenceNo">Reference Number</label>
                                        <input type="text" id="ReferenceNo" name="reference_no">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="otherreference">Other Reference</label>
                                        <input type="text" id="otherreference" name="other_reference">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Buyer Info Section -->
                    <div class="address-section">
                        <div class="row">
                            <div class="col-md-6 c-address-section">
                                <h5>Buyer (Bill to)</h5>
                                <label for="companyNameSelect">Customer Details <span class="required"
                                        title="required">*</span></label>
                                <select id="companyNameSelect" name="company" required>
                                    <option value="">Select Company</option>
                                    @foreach ($companies as $company)
                                        <option value="{{ $company->id }}">{{ $company->company }}</option>
                                    @endforeach
                                </select>
                                <textarea id="cCompanyAddress" name="address" rows="2" placeholder="Address" required></textarea>
                                <input type="text" id="cCompanyGst" name="gst"
                                    placeholder="Enter valid GST number" required>
                                <input type="tel" id="cCompanyPhone" name="phone"
                                    placeholder="Enter 10-digit number" required>
                                <input type="email" id="cCompanyEmail" name="email" placeholder="Email" required>
                            </div>
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="buyersOrderNo">Buyer's Order Number</label>
                                        <input type="text" id="buyersOrderNo" name="buyer_order_no">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="referenceDate">Date</label>
                                        <input type="date" id="referenceDate" name="reference_date">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="dispatchthrough">Dispatched Through</label>
                                        <input type="text" id="dispatchthrough" name="dispatch_through">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="destination">Destination</label>
                                        <input type="text" id="destination" name="destination">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="vehicleNo">Motor Vehicle Number</label>
                                        <input type="text" id="vehicleNo" name="vehicle_no">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="termsDelivery">Terms of Delivery</label>
                                        <input type="text" id="termsDelivery" name="terms_of_delivery">
                                    </div>
                                </div>
                            </div>
                        </div>
                        <br><br>

                        <!-- Item Table Section -->
                        <table id="invoiceTable">
                            <thead>
                                <tr>
                                    <th>Sl. No</th>
                                    <th>Description of Goods</th>
                                    <th>HSN/SAC</th>
                                    <th>Quantity</th>
                                    <th>Rate</th>
                                    <th>Per</th>
                                    <th>SGST (%)</th>
                                    <th>CGST (%)</th>
                                    <th>IGST (%)</th>
                                    <th>Amount</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>1</td>
                                    <td>
                                        <textarea id="description" name="description[]" cols="30" rows="1" class="description" required></textarea>
                                    </td>
                                    <td><input type="text" class="hsn" name="hsn[]" required></td>
                                    <td><input type="number" class="quantity" name="quantity[]" required
                                            oninput="calculateRow(this)"></td>
                                    <td><input type="number" class="rate" name="rate[]" required
                                            oninput="calculateRow(this)"></td>
                                    <td><input type="text" class="per" name="per[]" required></td>
                                    <td><input type="number" class="sgst" name="sgst[]"
                                            oninput="calculateRow(this)"></td>
                                    <td><input type="number" class="cgst" name="cgst[]"
                                            oninput="calculateRow(this)"></td>
                                    <td><input type="number" class="igst" name="igst[]"
                                            oninput="calculateRow(this)"></td>
                                    <td><input type="text" class="amount" name="amount[]" readonly></td>
                                    <td><button class="btn btn-danger" type="button" onclick="deleteRow(this)"><i
                                                class="fa fa-trash"></i></button></td>
                                </tr>
                            </tbody>
                        </table>
                        <br>
                        <div class="row">
                            <div class="col-md-2">
                                <button type="button" class="add-btn" onclick="addRow()">Add Item</button>
                            </div>
                        </div>

                        <!-- Total Calculation Section -->
                        <div class="row total-fields">
                            <div class="col-md-6">
                                <br><br>
                                <div class="row">
                                    <div class="col-md-3">
                                        <label for="grandTotal">Total Amount</label>
                                    </div>
                                    <div class="col-md-9">
                                        <input type="text" id="grandTotal" name="total_amount" readonly>
                                    </div>
                                </div>
                                <br>
                                <div class="row">
                                    <div class="col-md-3">
                                        <label for="amountInWords">Amount in Words</label>
                                    </div>
                                    <div class="col-md-9">
                                        <input type="text" id="amountInWords" name="amount_in_words" readonly>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h3>Total Calculation</h3>
                                <br>
                                <div class="row">
                                    <div class="col-md-4">
                                        <label for="totalAmount">Taxable Value</label>
                                    </div>
                                    <div class="col-md-8">
                                        <input type="text" id="totalAmount" name="taxable_value" readonly>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4">
                                        <label for="sgst">SGST</label>
                                    </div>
                                    <div class="col-md-8">
                                        <input type="number" id="sgst" name="sgst" readonly>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4">
                                        <label for="cgst">CGST</label>
                                    </div>
                                    <div class="col-md-8">
                                        <input type="number" id="cgst" name="cgst" readonly>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4">
                                        <label for="igst">IGST</label>
                                    </div>
                                    <div class="col-md-8">
                                        <input type="number" id="igst" name="igst" readonly>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4">
                                        <h5 for="totalTax">Total Tax Amount</h5>
                                    </div>
                                    <div class="col-md-8">
                                        <input type="number" id="totalTax" name="total_tax_amount" readonly>
                                    </div>
                                </div><br><br>
                                <!-- <label for="grandTotal">Total Amount</label>
                                                    <input type="number" id="grandTotal" readonly> -->
                            </div>
                        </div>

                        <!-- Bank Details Section -->
                        <div class="row">
                            <div class="col-md-6">
                                <br><br><br><br><br><br><br><br>
                                <p>Company's PAN : AAACU2461N</p>
                                <!-- <label for="companyspan">Company's PAN</label>
                                                    <input type="text" id="companyspan" readonly> -->
                            </div>
                            <div class="col-md-6">
                                <br>
                                <h6>Company's Bank Details</h6>
                                <p>A/c Holder: UMBREY ENGINEERING PVT LTD</p>
                                <p>Bank Name: ICICI BANK C/A</p>
                                <p>A/c: 193505000015</p>
                                <p>Branch & IFS Code: PEENYA BRANCH & ICIC0001935</p>
                                <p>SWIFT Code:</p>
                            </div>
                        </div>

                        <!-- Declaration Section -->
                        <div class="row">
                            <div class="col-md-6">
                                <h6>Declaration:</h6>
                                <p>We declare that this invoice shows the actual price of the <br>
                                    goods described and that all particulars are true and correct.</p>
                            </div>
                            <div class="col-md-6">
                                <h5>For Umbrey Engineering PVT LTD,</h5>
                                <br><br>
                                <p>Authorised Signatory</p>
                            </div>
                        </div>

                        <!-- Print and Save Buttons -->
                        <div class="row">

                            <div class="col-md-2">
                                <button type="submit" class="save-btn">Save</button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            $.ajax({
                url: '{{ route('manager.invoice.generate') }}',
                type: 'GET',
                success: function(response) {
                    $('#invoiceNo').val(response.invoice_no);
                },
                error: function() {
                    alert("Failed to generate Invoice ID");
                }
            });
        });
    </script>
    <script>
        // Collect item table data
        const rows = document.querySelectorAll('#invoiceTable tbody tr');
        rows.forEach(row => {
            const item = {
                description: row.querySelector('.description').value,
                hsn: row.querySelector('.hsn').value,
                quantity: row.querySelector('.quantity').value,
                rate: row.querySelector('.rate').value,
                per: row.querySelector('.per').value,
                sgst: row.querySelector('.sgst').value,
                cgst: row.querySelector('.cgst').value,
                igst: row.querySelector('.igst').value,
                amount: row.querySelector('.amount').value
            };
            formData.items.push(item);
        });

        // Add a new row in the invoice table
        function addRow() {
            const table = document.getElementById("invoiceTable").getElementsByTagName("tbody")[0];
            const rowCount = table.rows.length;
            const newRow = table.insertRow(rowCount);

            newRow.innerHTML = `
        <td>${rowCount + 1}</td>
        <td><textarea id="description" cols="30" rows="1" class="description" name="description[]" required></textarea></td>
        <td><input type="text" class="hsn" name="hsn[]" required></td>
        <td><input type="number" class="quantity" name="quantity[]" required min="0" oninput="calculateRow(this)"></td>
        <td><input type="number" class="rate" name="rate[]" required min="0" oninput="calculateRow(this)"></td>
        <td><input type="text" class="per" name="per[]" required></td>
        <td><input type="number" class="sgst" min="0" max="100" name="sgst[]" oninput="calculateRow(this)"></td>
        <td><input type="number" class="cgst" min="0" max="100" name="cgst[]" oninput="calculateRow(this)"></td>
        <td><input type="number" class="igst" min="0" max="100" name="igst[]" oninput="calculateRow(this)"></td>
        <td><input type="text" class="amount" name="amount[]" readonly></td>
        <td><button class="btn btn-danger" type="button" onclick="deleteRow(this)"><i class="fa fa-trash"></i></button></td>
    `;
        }

        // Delete a row in the invoice table
        function deleteRow(button) {
            const row = button.parentNode.parentNode;
            row.parentNode.removeChild(row);
            updateTotal();
        }

        // Calculate row-wise total and update total calculations
        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 total calculation based on all rows
        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("grandTotal").value = Math.round(totalAmount).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; // Round to next whole number
            // Final grand total with round-up
            const grandTotal = totalAmount + roundUpAmount;
            document.getElementById('grandTotal').value = grandTotal.toFixed(2);
            updateGrandTotalInWords();

        }

        // Convert number to words (simplified version for demo)
        function convertNumberToWords(num) {
            const ones = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"];
            const teens = ["", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
                "Nineteen"
            ];
            const tens = ["", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
            const higherUnits = ["", "Thousand", "Lakh", "Crore"];

            if (isNaN(num) || num === 0) return 'Zero';

            let word = '';

            function processHundred(number) {
                let result = '';
                if (number > 99) {
                    result += ones[Math.floor(number / 100)] + ' Hundred ';
                    number %= 100;
                }
                if (number > 10 && number < 20) {
                    result += teens[number - 10] + ' ';
                } else {
                    result += tens[Math.floor(number / 10)] + ' ';
                    result += ones[number % 10] + ' ';
                }
                return result.trim();
            }

            // Process the number in pairs for Indian format (thousands, lakhs, crores)
            const crorePart = Math.floor(num / 10000000);
            const lakhPart = Math.floor((num % 10000000) / 100000);
            const thousandPart = Math.floor((num % 100000) / 1000);
            const hundredPart = num % 1000;

            if (crorePart > 0) {
                word += processHundred(crorePart) + ' Crore ';
            }
            if (lakhPart > 0) {
                word += processHundred(lakhPart) + ' Lakh ';
            }
            if (thousandPart > 0) {
                word += processHundred(thousandPart) + ' Thousand ';
            }
            if (hundredPart > 0) {
                word += processHundred(hundredPart) + ' Only';
            }

            return word.trim();
        }

        // Function to update the 'GT-in-letters' field
        function updateGrandTotalInWords() {
            const grandTotal = parseFloat(document.getElementById('grandTotal').value) || 0;
            document.getElementById('amountInWords').value = convertNumberToWords(grandTotal);
        }
    </script>
    <!-- Place this before your custom JS script -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
    $(function() {
        $('#companyNameSelect').on('change', function() {
            let companyId = $(this).val();
            if (!companyId) {
                $('#cCompanyAddress').val('');
                $('#cCompanyGst').val('');
                $('#cCompanyEmail').val('');
                $('#cCompanyPhone').val('');
                return;
            }
            $.get("{{ url('manager/customer-vendor') }}/" + companyId, function(data) {
                if (data.success) {
                    $('#cCompanyAddress').val(data.company.address || '');
                    $('#cCompanyGst').val(data.company.gst || '');
                    $('#cCompanyEmail').val(data.company.email || '');
                    $('#cCompanyPhone').val(data.company.mobile || '');
                } else {
                    $('#cCompanyAddress').val('');
                    $('#cCompanyGst').val('');
                    $('#cCompanyEmail').val('');
                    $('#cCompanyPhone').val('');
                }
            });
        });
    });
</script>
@endsection
