@extends('layouts.admin')

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

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet">
@endpush

@section('content')
<div class="p-6 lg:p-8">
    <!-- Page Header -->
    <div class="flex justify-between items-center mb-6">
        <div>
            <h1 class="text-xl sm:text-2xl lg:text-3xl font-bold text-gray-800">Create New Invoice</h1>
            <p class="text-sm text-gray-600">Generate a professional invoice for merchant settlement.</p>
        </div>
        <div>
<a href="{{ route('finance.settlements.invoices.index') }}" class="bg-white text-gray-700 px-4 py-2 rounded-lg border shadow-sm hover:bg-gray-50">Back to Invoices</a>
        </div>
    </div>

<form action="{{ route('finance.settlements.invoices.store') }}" method="POST" id="invoiceForm">
        @csrf
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Left Column: Invoice Form -->
            <div class="lg:col-span-2 space-y-6">
                <div class="bg-white rounded-lg shadow-md p-6">
                    <h3 class="text-lg font-semibold mb-4 text-gray-900">Bill To</h3>
                    <label for="merchant_id" class="block text-xs sm:text-sm font-medium text-gray-700">Merchant</label>
                    <select name="merchant_id" id="merchant_id" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50" required>
                        <option value="">Select a merchant</option>
                        @foreach($merchants as $merchant)
                            <option value="{{ $merchant->id }}">{{ $merchant->name }} - {{ $merchant->email }}</option>
                        @endforeach
                    </select>
                </div>

                <div class="bg-white rounded-lg shadow-md p-6">
                    <h3 class="text-lg font-semibold mb-4 text-gray-900">Invoice Items</h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full">
                            <thead>
                                <tr>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Description</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Quantity</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Unit Price</th>
                                    <th class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase">Total</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody id="invoice-items" class="divide-y divide-gray-200">
                                <!-- JS will populate this -->
                            </tbody>
                        </table>
                    </div>
                    <button type="button" id="add-item" class="mt-4 bg-blue-100 text-blue-700 px-4 py-2 rounded-lg text-sm font-medium hover:bg-blue-200">Add Item</button>
                </div>
            </div>

            <!-- Right Column: Summary -->
            <div class="space-y-6">
                <div class="bg-white rounded-lg shadow-md p-6">
                    <h3 class="text-lg font-semibold mb-4 text-gray-900">Summary</h3>
                    <div class="space-y-3">
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-600">Subtotal</span>
                            <span id="summary-subtotal" class="text-sm font-medium text-gray-900">Rs. 0.00</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-600">Tax (%)</span>
                            <input type="number" id="tax-rate" name="tax_rate" class="w-20 rounded-md border-gray-300 shadow-sm text-right" value="0">
                        </div>
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-600">Tax Amount</span>
                            <span id="summary-tax" class="text-sm font-medium text-gray-900">Rs. 0.00</span>
                        </div>
                        <div class="flex justify-between items-center">
                            <span class="text-sm text-gray-600">Discount (Rs.)</span>
                            <input type="number" id="discount-amount" name="discount_amount" class="w-24 rounded-md border-gray-300 shadow-sm text-right" value="0">
                        </div>
                        <div class="flex justify-between items-center border-t pt-3 mt-3">
                            <span class="text-base font-bold text-gray-900">Total</span>
                            <span id="summary-total" class="text-base font-bold text-gray-900">Rs. 0.00</span>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="space-y-4">
                        <div>
                            <label for="invoice_date" class="block text-xs sm:text-sm font-medium text-gray-700">Invoice Date</label>
                            <input type="text" id="invoice_date" name="invoice_date" class="mt-1 block w-full border border-gray-300 rounded-md px-2 sm:px-3 py-1.5 sm:py-2 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Select date">
                        </div>
                        <div>
                            <label for="due_date" class="block text-xs sm:text-sm font-medium text-gray-700">Due Date</label>
                            <input type="text" id="due_date" name="due_date" class="mt-1 block w-full border border-gray-300 rounded-md px-2 sm:px-3 py-1.5 sm:py-2 text-xs sm:text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="Select date">
                        </div>
                    </div>
                    <button type="submit" class="bg-blue-600 text-white px-3 sm:px-4 py-2 rounded-md text-xs sm:text-sm font-semibold hover:bg-blue-700 transition">Create Invoice</button>
                </div>
            </div>
        </div>
    </form>
</div>
@endsection

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        flatpickr('#invoice_date', { dateFormat: 'Y-m-d', defaultDate: 'today' });
        flatpickr('#due_date', { dateFormat: 'Y-m-d' });

        let itemIndex = 0;
        const itemsContainer = document.getElementById('invoice-items');

        function addItemRow() {
            const row = document.createElement('tr');
            row.className = 'border-b';
            row.innerHTML = `
                <td class="py-2"><input type="text" name="items[${itemIndex}][description]" class="w-full border-none focus:ring-0" placeholder="Item description" required></td>
                <td class="py-2"><input type="number" name="items[${itemIndex}][quantity]" class="w-16 border-none focus:ring-0 item-quantity" value="1" min="1"></td>
                <td class="py-2"><input type="number" name="items[${itemIndex}][unit_price]" class="w-24 border-none focus:ring-0 item-price" value="0.00" step="0.01"></td>
                <td class="py-2 item-total font-medium text-gray-800">Rs. 0.00</td>
                <td class="py-2"><button type="button" class="text-red-500 hover:text-red-700 remove-item"><i class="fas fa-trash"></i></button></td>
            `;
            itemsContainer.appendChild(row);
            itemIndex++;
        }

        function calculateTotals() {
            let subtotal = 0;
            document.querySelectorAll('#invoice-items tr').forEach(row => {
                const quantity = parseFloat(row.querySelector('.item-quantity').value) || 0;
                const price = parseFloat(row.querySelector('.item-price').value) || 0;
                const total = quantity * price;
                row.querySelector('.item-total').textContent = `Rs. ${total.toFixed(2)}`;
                subtotal += total;
            });

            const taxRate = parseFloat(document.getElementById('tax-rate').value) || 0;
            const discount = parseFloat(document.getElementById('discount-amount').value) || 0;
            const taxAmount = (subtotal * taxRate) / 100;
            const total = subtotal + taxAmount - discount;

            document.getElementById('summary-subtotal').textContent = `Rs. ${subtotal.toFixed(2)}`;
            document.getElementById('summary-tax').textContent = `Rs. ${taxAmount.toFixed(2)}`;
            document.getElementById('summary-total').textContent = `Rs. ${total.toFixed(2)}`;
        }

        document.getElementById('add-item').addEventListener('click', addItemRow);

        itemsContainer.addEventListener('click', function(e) {
            if (e.target.closest('.remove-item')) {
                e.target.closest('tr').remove();
                calculateTotals();
            }
        });

        document.getElementById('invoiceForm').addEventListener('input', function(e) {
            if (['item-quantity', 'item-price', 'tax-rate', 'discount-amount'].some(id => e.target.id === id || e.target.classList.contains(id))) {
                calculateTotals();
            }
        });

        addItemRow();
    });
</script>
@endpush


