@extends('layouts.app')

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

@section('content')
<h2 class="page-title">Create New Invoice</h2>

<div class="row">
    <div class="col-12">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white border-0 pt-4 pb-0">
                <h5 class="fw-bold mb-0 text-primary">Invoice Information</h5>
            </div>
            <div class="card-body p-4">
                <form action="{{ route('invoices.store') }}" method="POST" id="invoiceForm">
                    @csrf
                    
                    <!-- Invoice Meta Info -->
                    <div class="row g-4 mb-5">
                        <div class="col-md-3">
                            <div class="form-floating">
                                <input type="text" id="invoice_no" name="invoice_no" class="form-control fw-bold text-primary" value="{{ $invoiceNo }}" readonly placeholder="Invoice Number">
                                <label for="invoice_no">Invoice Number</label>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-floating">
                                <input type="date" id="invoice_date" name="invoice_date" class="form-control" value="{{ date('Y-m-d') }}" required>
                                <label for="invoice_date">Invoice Date</label>
                            </div>
                        </div>
                    </div>

                    <!-- Customer Selection -->
                    <h6 class="fw-bold text-muted mb-3 text-uppercase" style="font-size: 12px; letter-spacing: 1px;">Customer Details</h6>
                    <div class="row g-4 mb-5 bg-light p-3 rounded-3 mx-0">
                        <div class="col-md-4">
                            <div class="form-floating">
                                <select name="customer_id" id="customer_id" class="form-select bg-white" required>
                                    <option value="">-- Select Customer --</option>
                                    @foreach($customers as $customer)
                                        <option value="{{ $customer->id }}">{{ $customer->customer_name }} ({{ $customer->mobile }})</option>
                                    @endforeach
                                </select>
                                <label for="customer_id">Select Customer <span class="text-danger">*</span></label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-floating">
                                <input type="text" id="cust_mobile" class="form-control bg-white" readonly placeholder="Mobile Number">
                                <label for="cust_mobile">Mobile Number</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-floating">
                                <input type="text" id="cust_gst" class="form-control bg-white" readonly placeholder="GST Number">
                                <label for="cust_gst">GST Number</label>
                            </div>
                        </div>
                        <div class="col-md-12">
                            <div class="form-floating">
                                <textarea id="cust_address" class="form-control bg-white" style="height: 60px" readonly placeholder="Address"></textarea>
                                <label for="cust_address">Address</label>
                            </div>
                        </div>
                    </div>

                    <!-- Products Table -->
                    <h6 class="fw-bold text-muted mb-3 text-uppercase" style="font-size: 12px; letter-spacing: 1px;">Product Entry</h6>
                    <div class="table-responsive mb-4 rounded-3 border">
                        <table class="table table-borderless mb-0" id="productTable">
                            <thead class="bg-light border-bottom">
                                <tr>
                                    <th width="40%" class="text-uppercase" style="font-size: 12px;">Product Name</th>
                                    <th width="15%" class="text-uppercase" style="font-size: 12px;">Qty</th>
                                    <th width="20%" class="text-uppercase" style="font-size: 12px;">Rate (₹)</th>
                                    <th width="20%" class="text-uppercase" style="font-size: 12px;">Amount (₹)</th>
                                    <th width="5%"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><input type="text" name="products[0][product_name]" class="form-control" required placeholder="Enter item name"></td>
                                    <td><input type="number" name="products[0][qty]" class="form-control qty text-center" value="1" min="1" step="0.01" required></td>
                                    <td><input type="number" name="products[0][rate]" class="form-control rate text-end" value="0" min="0" step="0.01" required></td>
                                    <td><input type="number" name="products[0][amount]" class="form-control amount text-end fw-bold" value="0" readonly></td>
                                    <td class="text-center"><button type="button" class="btn btn-danger btn-sm rounded-circle remove-row" style="width:30px; height:30px; padding:0;"><i class="fas fa-times"></i></button></td>
                                </tr>
                            </tbody>
                            <tfoot class="bg-light">
                                <tr>
                                    <td colspan="5" class="py-3">
                                        <button type="button" class="btn btn-secondary btn-sm rounded-pill px-3 fw-bold" id="addRow"><i class="fas fa-plus me-1"></i> Add Another Row</button>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>

                    <!-- Totals Section -->
                    <div class="row justify-content-end">
                        <div class="col-lg-4 col-md-6">
                            <div class="bg-light p-4 rounded-3 border">
                                <div class="d-flex justify-content-between mb-3 align-items-center">
                                    <span class="text-muted fw-bold">Sub Total (₹)</span>
                                    <input type="number" name="subtotal" id="subtotal" class="form-control text-end w-50 fw-bold border-0 bg-transparent px-0" value="0" readonly>
                                </div>
                                <div class="d-flex justify-content-between mb-3 align-items-center">
                                    <span class="text-muted fw-bold">Discount (₹)</span>
                                    <input type="number" name="discount" id="discount" class="form-control text-end w-50" value="0" min="0" step="0.01">
                                </div>
                                <hr class="my-3 border-secondary">
                                <div class="d-flex justify-content-between align-items-center">
                                    <span class="fs-5 fw-bold text-dark">Grand Total</span>
                                    <input type="number" name="grand_total" id="grand_total" class="form-control text-end w-50 fs-5 fw-bold text-success border-0 bg-transparent px-0" value="0" readonly>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="d-flex justify-content-end gap-3 mt-5 border-top pt-4">
                        <a href="{{ route('invoices.index') }}" class="btn btn-light border px-4 fw-bold">Cancel</a>
                        <button type="submit" class="btn btn-primary px-5 fw-bold"><i class="fas fa-file-invoice me-2"></i> Create Invoice</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(document).ready(function() {
    // Fetch Customer Details via AJAX
    $('#customer_id').change(function() {
        let customerId = $(this).val();
        if(customerId) {
            $.get(`{{ url('api/customers') }}/${customerId}`, function(data) {
                $('#cust_mobile').val(data.mobile);
                $('#cust_gst').val(data.gst_number);
                
                let address = data.address1;
                if(data.address2) address += ', ' + data.address2;
                if(data.city) address += ', ' + data.city;
                if(data.state) address += ', ' + data.state;
                if(data.pincode) address += ' - ' + data.pincode;
                $('#cust_address').val(address);
            });
        } else {
            $('#cust_mobile, #cust_gst, #cust_address').val('');
        }
    });

    // Dynamic Rows
    let rowIdx = 1;
    $('#addRow').click(function() {
        let tr = `
        <tr>
            <td><input type="text" name="products[${rowIdx}][product_name]" class="form-control" required placeholder="Enter item name"></td>
            <td><input type="number" name="products[${rowIdx}][qty]" class="form-control qty text-center" value="1" min="1" step="0.01" required></td>
            <td><input type="number" name="products[${rowIdx}][rate]" class="form-control rate text-end" value="0" min="0" step="0.01" required></td>
            <td><input type="number" name="products[${rowIdx}][amount]" class="form-control amount text-end fw-bold" value="0" readonly></td>
            <td class="text-center"><button type="button" class="btn btn-danger btn-sm rounded-circle remove-row" style="width:30px; height:30px; padding:0;"><i class="fas fa-times"></i></button></td>
        </tr>`;
        $('#productTable tbody').append(tr);
        rowIdx++;
    });

    $(document).on('click', '.remove-row', function() {
        $(this).closest('tr').remove();
        calculateTotals();
    });

    // Calculations
    $(document).on('input', '.qty, .rate', function() {
        let tr = $(this).closest('tr');
        let qty = parseFloat(tr.find('.qty').val()) || 0;
        let rate = parseFloat(tr.find('.rate').val()) || 0;
        tr.find('.amount').val((qty * rate).toFixed(2));
        calculateTotals();
    });

    $('#discount').on('input', function() {
        calculateTotals();
    });

    function calculateTotals() {
        let subtotal = 0;
        $('.amount').each(function() {
            subtotal += parseFloat($(this).val()) || 0;
        });
        $('#subtotal').val(subtotal.toFixed(2));

        let discount = parseFloat($('#discount').val()) || 0;
        let grandTotal = subtotal - discount;
        $('#grand_total').val(grandTotal.toFixed(2));
    }
});
</script>
@endpush
