@extends('layouts.dashboard.superadminapp')

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

@section('styles')
<link rel="stylesheet" href="{{ asset('css/modern-form-pattern.css') }}">
<style>
    /* Company Info Box - Custom for Invoice */
    .company-info-box {
        background: linear-gradient(135deg, var(--theme-primary) 0%, var(--theme-dark) 100%);
        color: #ffffff;
        padding: 1.5rem;
        border-radius: var(--radius-md);
        box-shadow: 0 4px 12px rgba(139, 92, 246, 0.3);
        margin-bottom: 1.5rem;
    }

    .company-info-box h6 {
        font-weight: 700;
        margin-bottom: 1rem;
        font-size: 1.125rem;
    }

    .company-info-box small {
        display: block;
        line-height: 1.6;
        opacity: 0.95;
    }

    /* Bank Info Box */
    .bank-info-box {
        background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%);
        border-radius: var(--radius-md);
        padding: 1.5rem;
        border: 2px solid #e5e7eb;
        height: 100%;
    }

    .bank-info-box h6 {
        color: var(--theme-primary);
        font-weight: 600;
        margin-bottom: 1rem;
    }

    .bank-info-box small {
        display: block;
        line-height: 1.8;
        color: #4b5563;
    }

    /* Declaration Box */
    .declaration-box {
        border: 2px solid #e5e7eb;
        border-radius: var(--radius-md);
        padding: 1.5rem;
        height: 100%;
        background: #ffffff;
    }

    .declaration-box h6 {
        color: #6b7280;
        font-weight: 600;
        margin-bottom: 1rem;
    }

    /* Summary Table - Custom for Invoice */
    .summary-table {
        background: linear-gradient(135deg, #faf5ff 0%, #f5f3ff 100%);
        border-radius: var(--radius-md);
        padding: 1rem;
        box-shadow: 0 2px 8px rgba(139, 92, 246, 0.1);
    }

    .summary-table .table {
        margin-bottom: 0;
    }

    .summary-table .table td {
        border: none;
        padding: 0.5rem 0.75rem;
    }

    .summary-table .grand-total {
        background: linear-gradient(135deg, var(--theme-primary) 0%, var(--theme-dark) 100%);
        color: #ffffff;
        font-weight: 700;
        border-radius: var(--radius);
        padding: 0.75rem !important;
    }

    .summary-table .grand-total input {
        background: transparent !important;
        color: #fff !important;
        border-color: rgba(255,255,255,0.3) !important;
    }
</style>
@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-file-invoice-dollar"></i>
            </div>
            <div class="header-title">
                <h1>Edit Tax Invoice</h1>
                <div class="header-subtitle">{{ $invoice->invoice_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>

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

        <!-- Invoice Details Section -->
        <div class="section-card">
            <div class="section-header">
                <i class="fas fa-file-invoice-dollar"></i>
                <h2>Invoice Details</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <div class="company-info-box">
                            <h6><i class="fas fa-building mr-2"></i>UMBREY ENGINEERING PVT LTD</h6>
                            <small>No. 31, 2nd Phase, Peenya Industrial Area</small>
                            <small>Bengaluru 560 058, Karnataka, India</small>
                            <small class="mt-2"><strong>GSTN:</strong> 29AAACU2461N1ZY | <strong>PAN:</strong> AAACU2461N</small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="row form-row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Invoice No <span class="required-star">*</span></label>
                                <input type="text" class="form-control" id="invoiceNo" name="invoice_no" value="{{ $invoice->invoice_no }}" readonly required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Invoice Date <span class="required-star">*</span></label>
                                <input type="date" class="form-control" id="invoiceDate" name="invoice_date" value="{{ $invoice->invoice_date }}" required>
                            </div>
                        </div>
                        <div class="row form-row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Delivery Note</label>
                                <input type="text" class="form-control" id="deliveryNote" name="delivery_note" value="{{ $invoice->delivery_note }}" placeholder="Delivery Note">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Mode/Terms of Payment</label>
                                <input type="text" class="form-control" id="termsPayment" name="terms_payment" value="{{ $invoice->terms_payment }}" placeholder="Payment Terms">
                            </div>
                        </div>
                        <div class="row form-row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Reference Number</label>
                                <input type="text" class="form-control" id="ReferenceNo" name="reference_no" value="{{ $invoice->reference_no }}" placeholder="Reference No">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Other Reference</label>
                                <input type="text" class="form-control" id="otherreference" name="other_reference" value="{{ $invoice->other_reference }}" placeholder="Other Reference">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Buyer Information Section -->
        <div class="section-card">
            <div class="section-header info">
                <i class="fas fa-user"></i>
                <h2>Buyer Information (Bill To)</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Customer <span class="required-star">*</span></label>
                        <select class="form-control" id="companyNameSelect" name="company" required>
                            <option value="">Select Customer</option>
                            @foreach ($companies as $company)
                                <option value="{{ $company->id }}" {{ $invoice->company_id == $company->id ? 'selected' : '' }}>{{ $company->company }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Address</label>
                        <textarea class="form-control" id="cCompanyAddress" name="address" rows="2" placeholder="Customer Address">{{ $invoice->address }}</textarea>
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-3 mb-3">
                        <label class="form-label">GST No</label>
                        <input type="text" class="form-control" id="cCompanyGst" name="gst" value="{{ $invoice->gst }}" placeholder="GSTIN">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Phone</label>
                        <input type="tel" class="form-control" id="cCompanyPhone" name="phone" value="{{ $invoice->phone }}" placeholder="Contact Number">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" id="cCompanyEmail" name="email" value="{{ $invoice->email }}" placeholder="Email Address">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Sales Order No</label>
                        <select class="form-control" id="orderNoSelect" name="order_no">
                            <option value="">Select Order</option>
                            @foreach($sales_orders as $order)
                                <option value="{{ $order->id }}" {{ $invoice->buyer_order_no == $order->sales_order_no ? 'selected' : '' }}>{{ $order->sales_order_no }}</option>
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <!-- Shipping Details Section -->
        <div class="section-card">
            <div class="section-header info">
                <i class="fas fa-shipping-fast"></i>
                <h2>Shipping & Dispatch Details</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Order Date</label>
                        <input type="date" class="form-control" id="referenceDate" name="reference_date" value="{{ $invoice->reference_date }}">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Dispatched Through</label>
                        <input type="text" class="form-control" id="dispatchthrough" name="dispatch_through" value="{{ $invoice->dispatch_through }}" placeholder="Dispatch Method">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Destination</label>
                        <input type="text" class="form-control" id="destination" name="destination" value="{{ $invoice->destination }}" placeholder="Destination">
                    </div>
                    <div class="col-md-3 mb-3">
                        <label class="form-label">Vehicle Number</label>
                        <input type="text" class="form-control" id="vehicleNo" name="vehicle_no" value="{{ $invoice->vehicle_no }}" placeholder="Vehicle No">
                    </div>
                </div>
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Terms of Delivery</label>
                        <input type="text" class="form-control" id="termsDelivery" name="terms_of_delivery" value="{{ $invoice->terms_of_delivery }}" placeholder="Delivery Terms">
                    </div>
                </div>
            </div>
        </div>

        <!-- Invoice Items Section -->
        <div class="section-card">
            <div class="section-header warning">
                <i class="fas fa-list"></i>
                <h2>Invoice Items</h2>
            </div>
            <div class="section-body">
                <div class="table-responsive">
                    <table id="invoiceTable" class="table table-modern table-bordered">
                        <thead>
                            <tr>
                                <th width="40">#</th>
                                <th>Description of Goods</th>
                                <th width="90">HSN/SAC</th>
                                <th width="80">Quantity</th>
                                <th width="90">Rate</th>
                                <th width="70">Per</th>
                                <th width="70">SGST %</th>
                                <th width="70">CGST %</th>
                                <th width="70">IGST %</th>
                                <th width="100">Amount</th>
                                <th width="40"></th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($invoice->items as $index => $item)
                            <tr>
                                <td class="text-center">{{ $index + 1 }}</td>
                                <td><textarea class="form-control description" name="description[]" rows="1">{{ $item->description }}</textarea></td>
                                <td><input type="text" class="form-control hsn" name="hsn[]" value="{{ $item->hsn }}"></td>
                                <td><input type="number" class="form-control quantity" name="quantity[]" value="{{ $item->quantity }}" min="0" oninput="calculateRow(this)"></td>
                                <td><input type="number" class="form-control rate" name="rate[]" value="{{ $item->rate }}" min="0" step="0.01" oninput="calculateRow(this)"></td>
                                <td><input type="text" class="form-control per" name="per[]" value="{{ $item->per }}"></td>
                                <td><input type="number" class="form-control sgst" name="sgst[]" value="{{ $item->sgst }}" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
                                <td><input type="number" class="form-control cgst" name="cgst[]" value="{{ $item->cgst }}" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
                                <td><input type="number" class="form-control igst" name="igst[]" value="{{ $item->igst }}" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
                                <td><input type="text" class="form-control amount" name="amount[]" value="{{ $item->amount }}" readonly></td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-danger btn-sm" onclick="deleteRow(this)" title="Delete">
                                        <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" onclick="addRow()">
                        <i class="fas fa-plus mr-1"></i> Add Item
                    </button>
                </div>
            </div>
        </div>

        <!-- Tax Calculation Section -->
        <div class="section-card">
            <div class="section-header success">
                <i class="fas fa-calculator"></i>
                <h2>Tax Calculation & Totals</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>
                        <textarea class="form-control" id="amountInWords" name="amount_in_words" rows="3" readonly>{{ $invoice->amount_in_words }}</textarea>
                    </div>
                    <div class="col-md-6">
                        <div class="summary-table">
                            <table class="table table-sm">
                                <tr>
                                    <td class="text-right font-weight-bold">Taxable Value:</td>
                                    <td width="150">
                                        <input type="text" id="totalAmount" name="taxable_value" value="{{ $invoice->taxable_value }}" readonly class="form-control form-control-sm text-right">
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-right">SGST:</td>
                                    <td>
                                        <input type="number" id="sgst" name="sgst" value="{{ $invoice->sgst }}" readonly class="form-control form-control-sm text-right">
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-right">CGST:</td>
                                    <td>
                                        <input type="number" id="cgst" name="cgst" value="{{ $invoice->cgst }}" readonly class="form-control form-control-sm text-right">
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-right">IGST:</td>
                                    <td>
                                        <input type="number" id="igst" name="igst" value="{{ $invoice->igst }}" readonly class="form-control form-control-sm text-right">
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-right">Total Tax:</td>
                                    <td>
                                        <input type="number" id="totalTax" name="total_tax_amount" value="{{ $invoice->total_tax_amount }}" readonly class="form-control form-control-sm text-right">
                                    </td>
                                </tr>
                                <tr class="grand-total">
                                    <td class="text-right font-weight-bold">Grand Total:</td>
                                    <td>
                                        <input type="text" id="grandTotal" name="total_amount" value="{{ $invoice->total_amount }}" readonly class="form-control form-control-sm text-right font-weight-bold">
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Bank Details & Declaration Section -->
        <div class="section-card">
            <div class="section-header secondary">
                <i class="fas fa-university"></i>
                <h2>Bank Details & Declaration</h2>
            </div>
            <div class="section-body">
                <div class="row form-row">
                    <div class="col-md-6 mb-3">
                        <div class="bank-info-box">
                            <h6><i class="fas fa-landmark mr-2"></i>Company's Bank Details</h6>
                            <small><strong>A/c Holder:</strong> UMBREY ENGINEERING PVT LTD</small>
                            <small><strong>Bank Name:</strong> ICICI BANK C/A</small>
                            <small><strong>A/c No:</strong> 193505000015</small>
                            <small><strong>Branch & IFS Code:</strong> PEENYA BRANCH & ICIC0001935</small>
                            <small class="mt-2"><strong>Company's PAN:</strong> AAACU2461N</small>
                        </div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="declaration-box">
                            <h6><i class="fas fa-file-signature mr-2"></i>Declaration</h6>
                            <small class="text-muted" style="line-height: 1.8;">
                                We declare that this invoice shows the actual price of the goods described and that all particulars are true and correct.
                            </small>
                            <hr class="my-3">
                            <div class="text-right">
                                <small class="font-weight-bold d-block">For Umbrey Engineering PVT LTD</small>
                                <div class="my-4"></div>
                                <small class="text-muted">Authorised Signatory</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Footer Actions -->
        <div class="footer-actions">
            <a href="{{ route('superadmin.invoice.invoicedetails') }}" 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 Invoice</span>
                </button>
            </div>
        </div>
    </form>
</div>
@endsection

@section('scripts')
<script>
$(document).ready(function() {
    // 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);

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

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

// 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 description" name="description[]" rows="1"></textarea></td>
        <td><input type="text" class="form-control hsn" name="hsn[]"></td>
        <td><input type="number" class="form-control quantity" name="quantity[]" min="0" oninput="calculateRow(this)"></td>
        <td><input type="number" class="form-control rate" name="rate[]" min="0" step="0.01" oninput="calculateRow(this)"></td>
        <td><input type="text" class="form-control per" name="per[]"></td>
        <td><input type="number" class="form-control sgst" name="sgst[]" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
        <td><input type="number" class="form-control cgst" name="cgst[]" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
        <td><input type="number" class="form-control igst" name="igst[]" min="0" max="100" step="0.01" oninput="calculateRow(this)"></td>
        <td><input type="text" class="form-control 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';
}

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