@extends('layouts.admin')

@section('title', 'Edit Quotation')

@section('page-title', 'Edit Quotation')

@section('breadcrumbs')
    <a href="{{ route('admin.quotations.index') }}" class="hover:text-primary">Quotations</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <a href="{{ route('admin.quotations.show', $quotation) }}" class="hover:text-primary">{{ $quotation->quotation_number }}</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">Edit</span>
@endsection

@section('content')
<form method="POST" action="{{ route('admin.quotations.update', $quotation) }}" id="quotation-form" class="max-w-5xl mx-auto flex flex-col gap-6 pb-24">
    @csrf
    @method('PUT')

    <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
        <h3 class="text-lg font-bold text-[#111418] text-gray-900 mb-6">Quotation Header</h3>
        <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
            <div>
                <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Issue Date <span class="text-red-500">*</span></label>
                <input type="date" name="issue_date" value="{{ old('issue_date', $quotation->issue_date->format('Y-m-d')) }}" required class="w-full h-11 rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
            </div>
            <div>
                <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Expiry Date</label>
                <input type="date" name="expiry_date" value="{{ old('expiry_date', $quotation->expiry_date ? $quotation->expiry_date->format('Y-m-d') : '') }}" class="w-full h-11 rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
            </div>
            <div>
                <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Status</label>
                <select name="status" class="w-full h-11 rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
                    <option value="draft" {{ old('status', $quotation->status) == 'draft' ? 'selected' : '' }}>Draft</option>
                    <option value="sent" {{ old('status', $quotation->status) == 'sent' ? 'selected' : '' }}>Sent</option>
                    <option value="viewed" {{ old('status', $quotation->status) == 'viewed' ? 'selected' : '' }}>Viewed</option>
                    <option value="accepted" {{ old('status', $quotation->status) == 'accepted' ? 'selected' : '' }}>Accepted</option>
                    <option value="rejected" {{ old('status', $quotation->status) == 'rejected' ? 'selected' : '' }}>Rejected</option>
                    <option value="expired" {{ old('status', $quotation->status) == 'expired' ? 'selected' : '' }}>Expired</option>
                    <option value="converted" {{ old('status', $quotation->status) == 'converted' ? 'selected' : '' }}>Converted</option>
                </select>
            </div>
            <div>
                <label class="block text-sm font-medium text-[#111418] text-gray-900 mb-2">Currency</label>
                <select name="currency" class="w-full h-11 rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">
                    @foreach($currencies as $currency)
                        <option value="{{ $currency->code }}" {{ old('currency', $quotation->currency) == $currency->code ? 'selected' : '' }}>{{ $currency->code }} - {{ $currency->name }}</option>
                    @endforeach
                </select>
            </div>
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
        <div class="flex flex-col gap-1 w-full">
            <p class="text-xs font-semibold text-[#617589] uppercase tracking-wider">Customer <span class="text-red-500">*</span></p>
            <select name="customer_id" required class="w-full h-10 rounded-lg border border-[#dbe0e6] bg-white px-3 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900 mt-1">
                @foreach($customers as $customer)
                    <option value="{{ $customer->id }}" {{ old('customer_id', $quotation->customer_id) == $customer->id ? 'selected' : '' }}>{{ $customer->name }}</option>
                @endforeach
            </select>
        </div>
    </div>

    <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
        <h3 class="text-lg font-bold text-[#111418] text-gray-900 mb-6">Quotation Items</h3>
        <div class="overflow-x-auto">
            <table class="w-full text-left border-collapse" id="items-table">
                <thead>
                    <tr class="border-b border-[#e5e7eb]">
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider">Description</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right">Qty</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right">Rate</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right">Tax %</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right">Amount</th>
                        <th class="py-3 px-2 text-xs font-semibold text-[#617589] uppercase tracking-wider"></th>
                    </tr>
                </thead>
                <tbody class="text-sm" id="items-tbody"></tbody>
            </table>
        </div>
        <div class="flex gap-3 mt-4">
            <button type="button" onclick="addItemRow()" class="flex items-center gap-2 px-4 py-2 rounded-lg bg-primary/10 text-primary font-medium text-sm hover:bg-primary/20 transition-colors">
                <span class="material-symbols-outlined text-lg">add_circle</span> Add New Line
            </button>
        </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div class="flex flex-col gap-6">
            <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
                <h3 class="text-sm font-bold text-[#111418] text-gray-900 mb-4">Notes</h3>
                <textarea name="notes" rows="4" class="w-full rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">{{ old('notes', $quotation->notes) }}</textarea>
            </div>
            <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
                <h3 class="text-sm font-bold text-[#111418] text-gray-900 mb-4">Terms</h3>
                <textarea name="terms" rows="4" class="w-full rounded-lg border border-[#dbe0e6] bg-white px-3 py-2 text-sm outline-none focus:border-primary focus:ring-1 focus:ring-primary text-gray-900">{{ old('terms', $quotation->terms) }}</textarea>
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
            <div class="flex flex-col gap-3">
                <div class="flex justify-between items-center text-sm">
                    <span class="text-[#617589]">Subtotal</span>
                    <span class="font-medium text-[#111418] text-gray-900" id="subtotal">$0.00</span>
                </div>
                <div class="flex justify-between items-center text-sm">
                    <span class="text-[#617589]">Tax Amount</span>
                    <span class="font-medium text-[#111418] text-gray-900" id="tax-amount">$0.00</span>
                </div>
                <div class="flex justify-between items-center pt-4 mt-2 border-t border-[#e5e7eb]">
                    <span class="text-base font-bold text-[#111418] text-gray-900">Total</span>
                    <span class="text-2xl font-bold text-primary" id="total">$0.00</span>
                </div>
            </div>
        </div>
    </div>

    <div class="fixed bottom-0 left-0 right-0 bg-white border-t border-[#e5e7eb] p-4 z-20 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)]">
        <div class="max-w-5xl mx-auto flex justify-between items-center">
            <a href="{{ route('admin.quotations.show', $quotation) }}" class="px-6 py-2.5 rounded-lg border border-[#dbe0e6] text-[#617589] font-medium hover:bg-background-light transition-colors">Cancel</a>
            <button type="submit" class="px-8 py-2.5 rounded-lg bg-primary text-white font-bold hover:bg-blue-600 transition-all flex items-center gap-2">
                Update Quotation <span class="material-symbols-outlined text-lg">save</span>
            </button>
        </div>
    </div>
</form>

<script>
// Same script as invoice edit - load existing items
let itemIndex = 0;
function addItemRow(item = null) {
    const tbody = document.getElementById('items-tbody');
    const row = document.createElement('tr');
    row.className = 'group hover:bg-background-light/50 border-b border-[#f0f2f4]';
    row.dataset.index = itemIndex;
    row.innerHTML = `
        <td class="py-4 px-2 align-top">
            <input type="text" name="items[${itemIndex}][description]" value="${item?.description || ''}" required placeholder="Item name" class="w-full font-medium text-[#111418] text-gray-900 bg-transparent border border-[#e5e7eb] rounded px-2 py-1 focus:ring-1 focus:ring-primary focus:border-primary text-gray-900 mb-1">
        </td>
        <td class="py-4 px-2 align-top">
            <input type="number" name="items[${itemIndex}][quantity]" value="${item?.quantity || '1'}" required min="0.01" step="0.01" class="w-full text-right bg-transparent border border-[#e5e7eb] rounded px-2 py-1 focus:border-primary focus:ring-1 focus:ring-primary text-gray-900" onchange="calculateRow(${itemIndex})">
        </td>
        <td class="py-4 px-2 align-top">
            <input type="number" name="items[${itemIndex}][unit_price]" value="${item?.unit_price || '0'}" required min="0" step="0.01" class="w-full text-right bg-transparent border border-[#e5e7eb] rounded px-2 py-1 focus:border-primary focus:ring-1 focus:ring-primary text-gray-900" onchange="calculateRow(${itemIndex})">
        </td>
        <td class="py-4 px-2 align-top">
            <input type="number" name="items[${itemIndex}][tax_rate]" value="${item?.tax_rate || '0'}" min="0" max="100" step="0.01" class="w-full text-right bg-transparent border border-[#e5e7eb] rounded px-2 py-1 focus:border-primary focus:ring-1 focus:ring-primary text-gray-900" onchange="calculateRow(${itemIndex})">
        </td>
        <td class="py-4 px-2 align-top text-right font-medium text-[#111418] text-gray-900" id="amount-${itemIndex}">$0.00</td>
        <td class="py-4 px-2 align-top text-center">
            <button type="button" onclick="removeItemRow(${itemIndex})" class="text-red-400 hover:text-red-600 transition-opacity">
                <span class="material-symbols-outlined text-lg">delete</span>
            </button>
        </td>
    `;
    tbody.appendChild(row);
    itemIndex++;
    calculateTotals();
}
function removeItemRow(index) {
    const row = document.querySelector(`tr[data-index="${index}"]`);
    if (row) { row.remove(); calculateTotals(); }
}
function calculateRow(index) {
    const row = document.querySelector(`tr[data-index="${index}"]`);
    if (!row) return;
    const quantity = parseFloat(row.querySelector(`input[name="items[${index}][quantity]"]`).value) || 0;
    const unitPrice = parseFloat(row.querySelector(`input[name="items[${index}][unit_price]"]`).value) || 0;
    const taxRate = parseFloat(row.querySelector(`input[name="items[${index}][tax_rate]"]`).value) || 0;
    const subtotal = quantity * unitPrice;
    const taxAmount = subtotal * (taxRate / 100);
    const total = subtotal + taxAmount;
    document.getElementById(`amount-${index}`).textContent = '$' + total.toFixed(2);
    calculateTotals();
}
function calculateTotals() {
    let subtotal = 0, taxAmount = 0;
    document.querySelectorAll('tr[data-index]').forEach((row, index) => {
        const quantity = parseFloat(row.querySelector(`input[name="items[${index}][quantity]"]`)?.value) || 0;
        const unitPrice = parseFloat(row.querySelector(`input[name="items[${index}][unit_price]"]`)?.value) || 0;
        const taxRate = parseFloat(row.querySelector(`input[name="items[${index}][tax_rate]"]`)?.value) || 0;
        const itemSubtotal = quantity * unitPrice;
        const itemTax = itemSubtotal * (taxRate / 100);
        subtotal += itemSubtotal;
        taxAmount += itemTax;
    });
    const total = subtotal + taxAmount;
    document.getElementById('subtotal').textContent = '$' + subtotal.toFixed(2);
    document.getElementById('tax-amount').textContent = '$' + taxAmount.toFixed(2);
    document.getElementById('total').textContent = '$' + total.toFixed(2);
}
document.addEventListener('DOMContentLoaded', function() {
    @foreach($quotation->items as $item)
        addItemRow({
            description: '{{ addslashes($item->description) }}',
            quantity: {{ $item->quantity }},
            unit_price: {{ $item->unit_price }},
            tax_rate: {{ $item->tax_rate }}
        });
    @endforeach
});
</script>
@endsection



