@csrf

<div class="row mb-3">
    <div class="col-md-6">
        <label for="date" class="form-label">Date</label>
        <input type="date" class="form-control" id="date" name="date" value="{{ old('date', (isset($quotation) && $quotation->date) ? \Illuminate\Support\Carbon::parse($quotation->date)->format('Y-m-d') : '') }}">
    </div>
    <div class="col-md-6">
        <label for="bill_to" class="form-label">Bill To</label>
        <input type="text" class="form-control" id="bill_to" name="bill_to" value="{{ old('bill_to', $quotation->bill_to ?? '') }}">
    </div>
</div>

<div class="row mb-3">
    <div class="col-md-6">
        <label for="company_name" class="form-label">Company Name</label>
        @php
            $customersList = $customers ?? \App\Models\Customer::pluck('name')->unique()->values();
        @endphp
        <select class="form-control" id="company_name" name="company_name">
            <option value="">-- Select Company --</option>
            @foreach($customersList as $cust)
                <option value="{{ $cust }}" {{ (old('company_name', $quotation->company_name ?? '') == $cust) ? 'selected' : '' }}>{{ $cust }}</option>
            @endforeach
        </select>
    </div>
    <div class="col-md-3">
        <label for="mobile" class="form-label">Mobile</label>
        <input type="text" class="form-control" id="mobile" name="mobile" value="{{ old('mobile', $quotation->mobile ?? '') }}">
    </div>
    <div class="col-md-3">
        <label for="email" class="form-label">E-mail</label>
        <input type="email" class="form-control" id="email" name="email" value="{{ old('email', $quotation->email ?? '') }}">
    </div>
</div>

<hr>
<h5>Items</h5>
<table class="table table-bordered" id="items-table">
    <thead>
        <tr>
            <th>Description</th>
            <th>Qty</th>
            <th>Rate</th>
            <th>Amount</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @php
            $oldItems = old('items', []);
            $existingItems = isset($quotation) ? $quotation->items : collect([]);
        @endphp
        @if(count($oldItems) > 0)
            @foreach($oldItems['description'] as $idx => $desc)
                <tr>
                    <td><input type="text" name="items[description][]" class="form-control" value="{{ $desc }}"></td>
                    <td><input type="number" name="items[qty][]" class="form-control qty" value="{{ $oldItems['qty'][$idx] ?? 0 }}"></td>
                    <td><input type="number" step="0.01" name="items[rate][]" class="form-control rate" value="{{ $oldItems['rate'][$idx] ?? 0 }}"></td>
                    <td><input type="number" step="0.01" name="items[amount][]" class="form-control amount" readonly value="{{ ($oldItems['qty'][$idx] ?? 0) * ($oldItems['rate'][$idx] ?? 0) }}"></td>
                    <td><button type="button" class="btn btn-sm btn-danger remove-row">x</button></td>
                </tr>
            @endforeach
        @elseif(isset($quotation))
            @foreach($existingItems as $item)
                <tr>
                    <td><input type="text" name="items[description][]" class="form-control" value="{{ $item->description }}"></td>
                    <td><input type="number" name="items[qty][]" class="form-control qty" value="{{ $item->qty }}"></td>
                    <td><input type="number" step="0.01" name="items[rate][]" class="form-control rate" value="{{ $item->rate }}"></td>
                    <td><input type="number" step="0.01" name="items[amount][]" class="form-control amount" readonly value="{{ $item->amount }}"></td>
                    <td><button type="button" class="btn btn-sm btn-danger remove-row">x</button></td>
                </tr>
            @endforeach
        @else
            <tr>
                <td><input type="text" name="items[description][]" class="form-control"></td>
                <td><input type="number" name="items[qty][]" class="form-control qty" value="0"></td>
                <td><input type="number" step="0.01" name="items[rate][]" class="form-control rate" value="0"></td>
                <td><input type="number" step="0.01" name="items[amount][]" class="form-control amount" readonly value="0"></td>
                <td><button type="button" class="btn btn-sm btn-danger remove-row">x</button></td>
            </tr>
        @endif
    </tbody>
    <tfoot>
        <tr>
            <td colspan="3" class="text-end">Subtotal</td>
            <td><input type="number" step="0.01" id="subtotal" class="form-control" readonly value="{{ old('subtotal', $quotation->subtotal ?? 0) }}"></td>
            <td></td>
        </tr>
    </tfoot>
</table>
<button type="button" class="btn btn-sm btn-secondary" id="add-row">Add Item</button>

<hr>

<div class="row mb-3">
    <div class="col-md-12">
        <label for="note" class="form-label">Note</label>
        <textarea name="note" id="note" class="form-control" rows="3">{{ old('note', $quotation->note ?? '') }}</textarea>
    </div>
</div>

<div class="d-flex justify-content-between">
    <a href="{{ route('quotations.index') }}" class="btn btn-secondary">Cancel</a>
    <button type="submit" class="btn btn-primary">{{ isset($quotation) ? 'Update' : 'Create' }}</button>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        function calculateRow(row) {
            const qty = parseFloat(row.querySelector('.qty').value) || 0;
            const rate = parseFloat(row.querySelector('.rate').value) || 0;
            const amountInput = row.querySelector('.amount');
            const amount = qty * rate;
            amountInput.value = amount.toFixed(2);
            calculateSubtotal();
        }

        function calculateSubtotal() {
            let total = 0;
            document.querySelectorAll('#items-table tbody tr').forEach(function(r) {
                const amt = parseFloat(r.querySelector('.amount').value) || 0;
                total += amt;
            });
            document.getElementById('subtotal').value = total.toFixed(2);
        }

        document.getElementById('add-row').addEventListener('click', function() {
            const tbody = document.querySelector('#items-table tbody');
            const newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td><input type="text" name="items[description][]" class="form-control"></td>
                <td><input type="number" name="items[qty][]" class="form-control qty" value="0"></td>
                <td><input type="number" step="0.01" name="items[rate][]" class="form-control rate" value="0"></td>
                <td><input type="number" step="0.01" name="items[amount][]" class="form-control amount" readonly value="0"></td>
                <td><button type="button" class="btn btn-sm btn-danger remove-row">x</button></td>
            `;
            tbody.appendChild(newRow);
        });

        document.querySelector('#items-table').addEventListener('input', function(e) {
            if (e.target.classList.contains('qty') || e.target.classList.contains('rate')) {
                calculateRow(e.target.closest('tr'));
            }
        });

        document.querySelector('#items-table').addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-row')) {
                e.target.closest('tr').remove();
                calculateSubtotal();
            }
        });
    });
</script>
