@extends('layouts.admin')

@section('title', $isEdit ? 'Edit Draft Invoice' : 'Buat Invoice')

@section('content')
@php
    $canIssue = auth()->user()?->isAdmin();
@endphp
<div class="max-w-6xl mx-auto space-y-5" x-data="invoiceForm(@js($prefillItems))">
    <div class="flex flex-col lg:flex-row lg:items-center justify-between gap-3">
        <div>
            <a href="{{ $isEdit ? route('admin.invoices.show', $invoice) : route('admin.invoices.index') }}" class="inline-flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-800 mb-2 transition">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                </svg>
                {{ $isEdit ? 'Kembali ke detail invoice' : 'Kembali ke daftar invoice' }}
            </a>
            <h1 class="text-xl font-bold text-gray-900">{{ $isEdit ? 'Edit Draft Invoice' : 'Buat Invoice Baru' }}</h1>
            <p class="text-sm text-gray-500 mt-0.5">{{ $invoice->source_type === 'service' ? 'Invoice akan menarik referensi dari tiket service.' : 'Isi item manual dan terbitkan saat siap.' }}</p>
        </div>
        <a href="{{ route('admin.customers.create') }}" class="inline-flex items-center gap-1.5 rounded-xl border border-gray-300 px-4 py-2.5 text-sm font-semibold text-gray-700 hover:bg-gray-50 transition self-start">Tambah Pelanggan</a>
    </div>

    <form method="POST" action="{{ $isEdit ? route('admin.invoices.update', $invoice) : route('admin.invoices.store') }}" class="space-y-5" @submit="prepareSignature()">
        @csrf
        @if($isEdit)
        @method('PATCH')
        @endif

        <input type="hidden" name="source_type" value="{{ $invoice->source_type }}">
        @if($invoice->source_type === 'service')
        <input type="hidden" name="source_id" value="{{ $invoice->source_id }}">
        @endif
        <input type="hidden" name="signature_data" x-model="signatureData">
        <input type="hidden" name="signature_drawn" :value="hasDrawn ? 1 : 0">

        @if($serviceTicket)
        <div class="rounded-2xl border border-emerald-200 bg-emerald-50 p-4">
            <p class="text-xs font-semibold uppercase tracking-wide text-emerald-700">Sumber Invoice</p>
            <p class="mt-1 text-sm text-emerald-800">Tiket {{ $serviceTicket->ticket_code }} • {{ $serviceTicket->customer->name }} • {{ $serviceTicket->brand }} {{ $serviceTicket->model }}</p>
            <p class="mt-1 text-xs text-emerald-700">Status tiket: {{ $serviceTicket->status }}</p>
        </div>
        @endif

        <div class="grid grid-cols-1 xl:grid-cols-3 gap-5">
            <div class="xl:col-span-2 space-y-5">
                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
                    <h2 class="text-sm font-semibold text-gray-800 mb-4">Header Invoice</h2>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="md:col-span-2">
                            <label class="block text-sm font-semibold text-gray-700 mb-1.5">Pelanggan <span class="text-red-500">*</span></label>
                            <select name="customer_id" class="w-full rounded-xl border px-4 py-2.5 text-sm {{ $errors->has('customer_id') ? 'border-red-400 bg-red-50' : 'border-gray-200' }} focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent" @if($serviceTicket) disabled @endif>
                                <option value="">Pilih pelanggan</option>
                                @foreach($customers as $customer)
                                <option value="{{ $customer->id }}" @selected((string) $selectedCustomerId === (string) $customer->id)>
                                    {{ $customer->name }}{{ $customer->whatsapp ? ' • ' . $customer->whatsapp : '' }}
                                </option>
                                @endforeach
                            </select>
                            @if($serviceTicket)
                            <input type="hidden" name="customer_id" value="{{ $selectedCustomerId }}">
                            @endif
                            @error('customer_id')<p class="mt-1 text-xs text-red-500">{{ $message }}</p>@enderror
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-1.5">Tanggal Invoice <span class="text-red-500">*</span></label>
                            <input type="date" name="invoice_date" value="{{ old('invoice_date', optional($invoice->invoice_date)->format('Y-m-d') ?: now()->toDateString()) }}" class="w-full rounded-xl border px-4 py-2.5 text-sm {{ $errors->has('invoice_date') ? 'border-red-400 bg-red-50' : 'border-gray-200' }} focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                            @error('invoice_date')<p class="mt-1 text-xs text-red-500">{{ $message }}</p>@enderror
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-gray-700 mb-1.5">Jatuh Tempo</label>
                            <input type="date" name="due_date" value="{{ old('due_date', optional($invoice->due_date)->format('Y-m-d') ?: optional($invoice->invoice_date)->format('Y-m-d') ?: now()->toDateString()) }}" class="w-full rounded-xl border px-4 py-2.5 text-sm {{ $errors->has('due_date') ? 'border-red-400 bg-red-50' : 'border-gray-200' }} focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                            @error('due_date')<p class="mt-1 text-xs text-red-500">{{ $message }}</p>@enderror
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 space-y-4">
                    <div class="flex items-center justify-between gap-3">
                        <h2 class="text-sm font-semibold text-gray-800">Item Invoice</h2>
                        <button type="button" @click="addItem()" class="inline-flex items-center gap-1.5 rounded-lg bg-brand-50 text-brand-700 border border-brand-200 px-3 py-1.5 text-xs font-semibold hover:bg-brand-100 transition">Tambah Item</button>
                    </div>

                    <template x-for="(item, index) in items" :key="index">
                        <div class="rounded-2xl border border-gray-200 p-4 space-y-3 bg-gray-50/60">
                            <div class="grid grid-cols-1 md:grid-cols-6 gap-3">
                                <div class="md:col-span-2">
                                    <label class="block text-xs font-semibold uppercase tracking-wide text-gray-500 mb-1">Jenis Item</label>
                                    <select :name="`items[${index}][item_type]`" x-model="item.item_type" class="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                                        <option value="service">Service</option>
                                        <option value="product">Produk</option>
                                        <option value="diagnostic_fee">Biaya Diagnosa</option>
                                        <option value="cancellation_fee">Biaya Batal</option>
                                        <option value="manual">Manual</option>
                                        <option value="other">Lainnya</option>
                                    </select>
                                </div>
                                <div class="md:col-span-4">
                                    <label class="block text-xs font-semibold uppercase tracking-wide text-gray-500 mb-1">Deskripsi</label>
                                    <input type="text" :name="`items[${index}][description]`" x-model="item.description" class="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                                </div>
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wide text-gray-500 mb-1">Qty</label>
                                    <input type="number" min="0.01" step="0.01" :name="`items[${index}][qty]`" x-model.number="item.qty" class="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                                </div>
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wide text-gray-500 mb-1">Satuan</label>
                                    <input type="text" :name="`items[${index}][unit]`" x-model="item.unit" class="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                                </div>
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wide text-gray-500 mb-1">Harga</label>
                                    <input type="number" min="0" step="0.01" :name="`items[${index}][unit_price]`" x-model.number="item.unit_price" class="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                                </div>
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wide text-gray-500 mb-1">Diskon</label>
                                    <input type="number" min="0" step="0.01" :name="`items[${index}][discount_amount]`" x-model.number="item.discount_amount" class="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                                </div>
                                <div>
                                    <label class="block text-xs font-semibold uppercase tracking-wide text-gray-500 mb-1">Pajak</label>
                                    <input type="number" min="0" step="0.01" :name="`items[${index}][tax_amount]`" x-model.number="item.tax_amount" class="w-full rounded-xl border border-gray-200 px-3 py-2.5 text-sm bg-white focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                                </div>
                                <div class="flex items-end justify-between md:col-span-6 gap-3">
                                    <div class="text-sm text-gray-600">Line Total: <span class="font-semibold text-gray-900" x-text="formatMoney(lineTotal(item))"></span></div>
                                    <button type="button" @click="removeItem(index)" x-show="items.length > 1" class="text-xs font-semibold text-rose-600 hover:text-rose-700">Hapus Item</button>
                                </div>
                            </div>
                        </div>
                    </template>
                    @error('items')<p class="text-xs text-red-500">{{ $message }}</p>@enderror
                </div>

                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 grid grid-cols-1 md:grid-cols-2 gap-5">
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-1.5">Catatan Invoice</label>
                        <textarea name="public_note" rows="4" class="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">{{ old('public_note', $invoice->public_note) }}</textarea>
                        <p class="mt-1 text-xs text-gray-400">Tampil pada invoice customer.</p>
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-gray-700 mb-1.5">Catatan Internal</label>
                        <textarea name="internal_note" rows="4" class="w-full rounded-xl border border-gray-200 px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent">{{ old('internal_note', $invoice->internal_note) }}</textarea>
                        <p class="mt-1 text-xs text-gray-400">Hanya terlihat oleh admin dan kasir.</p>
                    </div>
                </div>
            </div>

            <div class="space-y-5">
                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5">
                    <h2 class="text-sm font-semibold text-gray-800 mb-4">Ringkasan</h2>
                    <dl class="space-y-2 text-sm">
                        <div class="flex justify-between gap-3"><dt class="text-gray-500">Subtotal</dt><dd class="font-semibold text-gray-900" x-text="formatMoney(subtotal())"></dd></div>
                        <div class="flex justify-between gap-3"><dt class="text-gray-500">Diskon</dt><dd class="font-semibold text-gray-900" x-text="formatMoney(totalDiscount())"></dd></div>
                        <div class="flex justify-between gap-3"><dt class="text-gray-500">Pajak</dt><dd class="font-semibold text-gray-900" x-text="formatMoney(totalTax())"></dd></div>
                        <div class="border-t border-gray-100 pt-3 flex justify-between gap-3"><dt class="text-gray-900 font-semibold">Grand Total</dt><dd class="font-bold text-lg text-brand-700" x-text="formatMoney(grandTotal())"></dd></div>
                    </dl>
                </div>

                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 space-y-4">
                    <div class="flex items-center justify-between gap-3">
                        <h2 class="text-sm font-semibold text-gray-800">Tanda Tangan Penerbit</h2>
                        <button type="button" @click="clearSignature()" class="text-xs font-semibold text-gray-500 hover:text-gray-700">Bersihkan</button>
                    </div>
                    <div class="rounded-2xl border border-dashed border-gray-300 bg-gray-50 p-3">
                        <canvas x-ref="signatureCanvas" class="w-full h-48 bg-white rounded-xl border border-gray-200 touch-none"></canvas>
                    </div>
                    @if($invoice->signature_path)
                    <div>
                        <p class="text-xs text-gray-400 mb-2">Tanda tangan tersimpan saat ini</p>
                        <img src="{{ asset('storage/' . $invoice->signature_path) }}" alt="Signature" class="h-20 rounded-lg border border-gray-200 bg-white p-1">
                    </div>
                    @endif
                    @error('signature_data')<p class="text-xs text-red-500">{{ $message }}</p>@enderror
                    <p class="text-xs text-gray-400">Wajib saat menerbitkan invoice.</p>
                </div>

                <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 flex flex-col gap-3">
                    <button type="submit" name="submit_action" value="draft" class="w-full rounded-xl border border-gray-300 text-gray-700 text-sm font-semibold px-4 py-3 hover:bg-gray-50 transition">
                        {{ $isEdit ? 'Update Draft' : 'Simpan Draft' }}
                    </button>
                    <button type="submit" name="submit_action" value="review" class="w-full rounded-xl bg-amber-600 hover:bg-amber-700 text-white text-sm font-semibold px-4 py-3 transition shadow-sm">
                        {{ $isEdit ? 'Update & Ajukan Review' : 'Ajukan Review Admin' }}
                    </button>
                    @if($canIssue)
                    <button type="submit" name="submit_action" value="issue" class="w-full rounded-xl bg-brand-600 hover:bg-brand-700 text-white text-sm font-semibold px-4 py-3 transition shadow-sm">
                        {{ $isEdit ? 'Update dan Terbitkan' : 'Terbitkan Invoice' }}
                    </button>
                    @endif
                </div>
            </div>
        </div>
    </form>
</div>
@endsection

@push('scripts')
<script>
function invoiceForm(initialItems) {
    return {
        items: Array.isArray(initialItems) && initialItems.length ? initialItems.map(item => ({
            item_type: item.item_type ?? 'manual',
            description: item.description ?? '',
            qty: Number(item.qty ?? 1),
            unit: item.unit ?? 'pcs',
            unit_price: Number(item.unit_price ?? 0),
            discount_amount: Number(item.discount_amount ?? 0),
            tax_amount: Number(item.tax_amount ?? 0),
        })) : [{ item_type: 'manual', description: '', qty: 1, unit: 'pcs', unit_price: 0, discount_amount: 0, tax_amount: 0 }],
        signaturePadReady: false,
        isDrawing: false,
        hasDrawn: false,
        signatureData: '',
        ctx: null,
        addItem() {
            this.items.push({ item_type: 'manual', description: '', qty: 1, unit: 'pcs', unit_price: 0, discount_amount: 0, tax_amount: 0 });
        },
        removeItem(index) {
            if (this.items.length > 1) {
                this.items.splice(index, 1);
            }
        },
        lineTotal(item) {
            return Math.max((Number(item.qty) * Number(item.unit_price)) - Number(item.discount_amount) + Number(item.tax_amount), 0);
        },
        subtotal() {
            return this.items.reduce((sum, item) => sum + (Number(item.qty) * Number(item.unit_price)), 0);
        },
        totalDiscount() {
            return this.items.reduce((sum, item) => sum + Number(item.discount_amount), 0);
        },
        totalTax() {
            return this.items.reduce((sum, item) => sum + Number(item.tax_amount), 0);
        },
        grandTotal() {
            return this.items.reduce((sum, item) => sum + this.lineTotal(item), 0);
        },
        formatMoney(value) {
            return 'Rp ' + Number(value || 0).toLocaleString('id-ID');
        },
        prepareSignature() {
            if (this.ctx && this.hasDrawn) {
                this.signatureData = this.$refs.signatureCanvas.toDataURL('image/png');
            } else {
                this.signatureData = '';
            }
        },
        clearSignature() {
            if (!this.ctx) return;
            this.ctx.clearRect(0, 0, this.$refs.signatureCanvas.width, this.$refs.signatureCanvas.height);
            this.signatureData = '';
            this.hasDrawn = false;
        },
        resizeCanvas() {
            const canvas = this.$refs.signatureCanvas;
            const ratio = Math.max(window.devicePixelRatio || 1, 1);
            const rect = canvas.getBoundingClientRect();
            canvas.width = rect.width * ratio;
            canvas.height = rect.height * ratio;
            this.ctx = canvas.getContext('2d');
            this.ctx.scale(ratio, ratio);
            this.ctx.lineWidth = 2;
            this.ctx.lineCap = 'round';
            this.ctx.strokeStyle = '#111827';
        },
        pointFromEvent(event) {
            const rect = this.$refs.signatureCanvas.getBoundingClientRect();
            const source = event.touches ? event.touches[0] : event;
            return { x: source.clientX - rect.left, y: source.clientY - rect.top };
        },
        startDraw(event) {
            this.isDrawing = true;
            this.hasDrawn = true;
            const point = this.pointFromEvent(event);
            this.ctx.beginPath();
            this.ctx.moveTo(point.x, point.y);
        },
        draw(event) {
            if (!this.isDrawing) return;
            event.preventDefault();
            const point = this.pointFromEvent(event);
            this.ctx.lineTo(point.x, point.y);
            this.ctx.stroke();
        },
        stopDraw() {
            this.isDrawing = false;
        },
        init() {
            this.$nextTick(() => {
                this.resizeCanvas();
                const canvas = this.$refs.signatureCanvas;
                canvas.addEventListener('mousedown', event => this.startDraw(event));
                canvas.addEventListener('mousemove', event => this.draw(event));
                window.addEventListener('mouseup', () => this.stopDraw());
                canvas.addEventListener('mouseleave', () => this.stopDraw());
                canvas.addEventListener('touchstart', event => this.startDraw(event), { passive: true });
                canvas.addEventListener('touchmove', event => this.draw(event), { passive: false });
                canvas.addEventListener('touchend', () => this.stopDraw());
                window.addEventListener('resize', () => this.resizeCanvas());
            });
        }
    }
}
</script>
@endpush