@extends('layouts.app')

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

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h4>Create New Invoice</h4>
                </div>
                <div class="card-body">
                    <form action="{{ route('invoices.store') }}" method="POST" id="invoice-form">
                        @csrf

                        <div class="row mb-4">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <label for="customer_id" class="form-label">Customer *</label>
                                        <button type="button" class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#createCustomerModal">+ New</button>
                                    </div>
                                    <select class="form-select" id="customer_id" name="customer_id" required>
                                        <option value="">Select Customer</option>
                                        @foreach($customers as $customer)
                                            <option value="{{ $customer->id }}">{{ $customer->name }}</option>
                                        @endforeach
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="invoice_date" class="form-label">Invoice Date *</label>
                                    <input type="date" class="form-control" id="invoice_date" name="invoice_date" value="{{ now()->toDateString() }}" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="due_date" class="form-label">Due Date</label>
                                    <input type="date" class="form-control" id="due_date" name="due_date">
                                </div>
                            </div>
                        </div>

                        <div class="row mb-4">
                            <div class="col-md-12">
                                <h5>Invoice Items</h5>
                                <table class="table table-bordered" id="items-table">
                                    <thead>
                                        <tr>
                                            <th>Product</th>
                                            <th>Quantity</th>
                                            <th>Unit Price</th>
                                            <th>Subtotal</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody id="items-body">
                                        <tr class="item-row">
                                            <td>
                                                <select class="form-select product-select" name="items[0][product_id]" required>
                                                    <option value="">Select Product</option>
                                                    @foreach($products as $product)
                                                        <option value="{{ $product->id }}" data-price="{{ $product->sale_price }}">{{ $product->name }} ({{ $product->current_stock }})</option>
                                                    @endforeach
                                                </select>
                                            </td>
                                            <td>
                                                <input type="number" class="form-control quantity" name="items[0][quantity]" min="1" value="1" required>
                                            </td>
                                            <td>
                                                <input type="number" class="form-control unit-price" name="items[0][unit_price]" step="0.01" min="0" required>
                                            </td>
                                            <td class="subtotal">0.00</td>
                                            <td>
                                                <button type="button" class="btn btn-danger btn-sm remove-item">Remove</button>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                                <button type="button" class="btn btn-success btn-sm" id="add-item">Add Item</button>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="notes" class="form-label">Notes</label>
                                    <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                                </div>
                            </div>
                            <div class="col-md-6 text-end">
                                <h4>Total: <span id="total-amount">0.00</span></h4>
                            </div>
                        </div>

                        <div class="d-flex justify-content-between mt-4">
                            <a href="{{ route('invoices.index') }}" class="btn btn-secondary">Cancel</a>
                            <button type="submit" class="btn btn-primary">Create Invoice</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Create Customer Modal -->
<div class="modal fade" id="createCustomerModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create New Customer</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createCustomerForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="modal_name" class="form-label">Name *</label>
                        <input type="text" class="form-control" id="modal_name" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label for="modal_email" class="form-label">Email</label>
                        <input type="email" class="form-control" id="modal_email" name="email">
                    </div>
                    <div class="mb-3">
                        <label for="modal_phone" class="form-label">Phone</label>
                        <input type="text" class="form-control" id="modal_phone" name="phone">
                    </div>
                    <div class="mb-3">
                        <label for="modal_address" class="form-label">Address</label>
                        <textarea class="form-control" id="modal_address" name="address" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Customer</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // Quick customer creation
    document.getElementById('createCustomerForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        const data = Object.fromEntries(formData);

        try {
            const response = await fetch('{{ route("customers.quick-store") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                // Add new customer to dropdown
                const select = document.getElementById('customer_id');
                const option = document.createElement('option');
                option.value = result.customer.id;
                option.textContent = result.customer.name;
                option.selected = true;
                select.appendChild(option);

                // Clear form and close modal
                document.getElementById('createCustomerForm').reset();
                bootstrap.Modal.getInstance(document.getElementById('createCustomerModal')).hide();
            }
        } catch (error) {
            alert('Error creating customer: ' + error.message);
        }
    });
    let itemCount = 1;

    document.getElementById('add-item').addEventListener('click', function() {
        const tbody = document.getElementById('items-body');
        const newRow = document.createElement('tr');
        newRow.className = 'item-row';
        newRow.innerHTML = `
            <td>
                <select class="form-select product-select" name="items[${itemCount}][product_id]" required>
                    <option value="">Select Product</option>
                    @foreach($products as $product)
                        <option value="{{ $product->id }}" data-price="{{ $product->sale_price }}">{{ $product->name }} ({{ $product->current_stock }})</option>
                    @endforeach
                </select>
            </td>
            <td>
                <input type="number" class="form-control quantity" name="items[${itemCount}][quantity]" min="1" value="1" required>
            </td>
            <td>
                <input type="number" class="form-control unit-price" name="items[${itemCount}][unit_price]" step="0.01" min="0" required>
            </td>
            <td class="subtotal">0.00</td>
            <td>
                <button type="button" class="btn btn-danger btn-sm remove-item">Remove</button>
            </td>
        `;
        tbody.appendChild(newRow);
        itemCount++;
        attachEventListeners(newRow);
    });

    function attachEventListeners(row) {
        const productSelect = row.querySelector('.product-select');
        const quantityInput = row.querySelector('.quantity');
        const unitPriceInput = row.querySelector('.unit-price');
        const removeBtn = row.querySelector('.remove-item');

        productSelect.addEventListener('change', function() {
            const price = this.options[this.selectedIndex]?.dataset.price || 0;
            unitPriceInput.value = price;
            calculateSubtotal(row);
        });

        quantityInput.addEventListener('input', function() {
            calculateSubtotal(row);
        });

        unitPriceInput.addEventListener('input', function() {
            calculateSubtotal(row);
        });

        removeBtn.addEventListener('click', function() {
            if (document.querySelectorAll('.item-row').length > 1) {
                row.remove();
                calculateTotal();
            }
        });
    }

    function calculateSubtotal(row) {
        const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
        const unitPrice = parseFloat(row.querySelector('.unit-price').value) || 0;
        const subtotal = quantity * unitPrice;
        row.querySelector('.subtotal').textContent = subtotal.toFixed(2);
        calculateTotal();
    }

    function calculateTotal() {
        let total = 0;
        document.querySelectorAll('.item-row').forEach(row => {
            const quantity = parseFloat(row.querySelector('.quantity').value) || 0;
            const unitPrice = parseFloat(row.querySelector('.unit-price').value) || 0;
            total += quantity * unitPrice;
        });
        document.getElementById('total-amount').textContent = total.toFixed(2);
    }

    document.querySelectorAll('.item-row').forEach(row => {
        attachEventListeners(row);
    });

    // Quick customer creation
    document.getElementById('createCustomerForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        const data = Object.fromEntries(formData);

        try {
            const response = await fetch('{{ route("customers.quick-store") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.success) {
                // Add new customer to dropdown
                const select = document.getElementById('customer_id');
                const option = document.createElement('option');
                option.value = result.customer.id;
                option.textContent = result.customer.name;
                option.selected = true;
                select.appendChild(option);

                // Clear form and close modal
                document.getElementById('createCustomerForm').reset();
                bootstrap.Modal.getInstance(document.getElementById('createCustomerModal')).hide();
            }
        } catch (error) {
            alert('Error creating customer: ' + error.message);
        }
    });
</script>
@endsection
