@extends('layouts.courier')
@section('title', 'Form Delivery — ' . $ticket->ticket_code)

@push('head')
{{-- SignaturePad.js --}}
<script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>
@endpush

@section('content')
<div class="py-2 max-w-md mx-auto" x-data="handoverForm()">

    {{-- Header --}}
    <div class="mb-5">
        <a href="{{ route('courier.delivery') }}"
           class="inline-flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700 mb-3">
            <svg class="w-3.5 h-3.5" 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>
            Kembali ke Daftar Delivery
        </a>
        <h1 class="text-xl font-bold text-gray-800">Form Delivery</h1>
        <p class="text-sm text-gray-500 mt-0.5">Tiket <span class="font-mono font-semibold text-gray-700">{{ $ticket->ticket_code }}</span></p>
    </div>

    {{-- Ticket summary --}}
    <div class="rounded-2xl bg-white border border-gray-200 shadow-sm p-4 mb-5">
        <div class="grid grid-cols-2 gap-3 text-sm">
            <div>
                <p class="text-xs text-gray-400 font-medium mb-0.5">Pelanggan</p>
                <p class="font-semibold text-gray-800">{{ $ticket->customer->name }}</p>
                <p class="text-xs text-gray-500">{{ $ticket->customer->whatsapp }}</p>
            </div>
            <div>
                <p class="text-xs text-gray-400 font-medium mb-0.5">Perangkat</p>
                <p class="font-semibold text-gray-800">{{ $ticket->brand }} {{ $ticket->model }}</p>
                <p class="text-xs text-gray-500">{{ $ticket->device_type }}</p>
            </div>
        </div>
    </div>

    {{-- Invoice info card --}}
    @if(isset($issuedInvoice))
    <div class="rounded-2xl border {{ $ticket->status === 'Cancelled' ? 'border-orange-200 bg-orange-50' : 'border-emerald-200 bg-emerald-50' }} p-4 mb-5">
        <div class="flex items-start gap-3">
            <svg class="w-5 h-5 flex-shrink-0 mt-0.5 {{ $ticket->status === 'Cancelled' ? 'text-orange-500' : 'text-emerald-600' }}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            <div class="min-w-0">
                <p class="text-xs font-semibold {{ $ticket->status === 'Cancelled' ? 'text-orange-700' : 'text-emerald-700' }} uppercase tracking-wide mb-1">
                    {{ $ticket->status === 'Cancelled' ? 'Invoice Pembatalan Telah Diterbitkan' : 'Invoice Telah Diterbitkan' }}
                </p>
                <p class="text-sm font-semibold text-gray-800">{{ $issuedInvoice->invoice_number }}</p>
                <p class="text-xs text-gray-600 mt-0.5">
                    Total: <span class="font-semibold">Rp {{ number_format((float) $issuedInvoice->grand_total, 0, ',', '.') }}</span>
                    &nbsp;·&nbsp;
                    Pembayaran:
                    <span class="font-semibold {{ $issuedInvoice->payment_status === 'paid' ? 'text-emerald-700' : 'text-amber-600' }}">
                        {{ $issuedInvoice->payment_status === 'paid' ? 'Lunas' : ($issuedInvoice->payment_status === 'partial' ? 'Sebagian' : 'Belum Lunas') }}
                    </span>
                </p>
                <a href="{{ route('admin.invoices.show', $issuedInvoice->id) }}"
                   class="inline-flex items-center gap-1 mt-1.5 text-xs font-medium text-brand-600 hover:underline">
                    Lihat Invoice ↗
                </a>
            </div>
        </div>
    </div>
    @endif

    {{-- Form --}}
    <form method="POST" action="{{ route('handover.store', $ticket) }}"
          enctype="multipart/form-data"
          @submit.prevent="handleSubmit($el)">
        @csrf

        {{-- 1. Nama penerima --}}
        <div class="rounded-2xl bg-white border border-gray-200 shadow-sm p-4 mb-4">
            <h2 class="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
                <span class="flex-shrink-0 w-6 h-6 bg-brand-600 text-white text-xs font-bold
                             rounded-full flex items-center justify-center">1</span>
                Nama Penerima Barang
            </h2>
            <input type="text" name="recipient_name" id="recipient_name" required
                   value="{{ old('recipient_name') }}"
                   placeholder="Nama lengkap orang yang mengambil"
                   class="w-full rounded-xl border border-gray-300 px-4 py-3 text-sm
                          focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-transparent
                          placeholder-gray-400">
            @error('recipient_name')
                <p class="mt-1.5 text-xs text-red-600">{{ $message }}</p>
            @enderror
        </div>

        {{-- 2. Foto kondisi akhir --}}
        <div class="rounded-2xl bg-white border border-gray-200 shadow-sm p-4 mb-4">
            <h2 class="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
                <span class="flex-shrink-0 w-6 h-6 bg-brand-600 text-white text-xs font-bold
                             rounded-full flex items-center justify-center">2</span>
                Foto Kondisi Akhir Barang
                <span class="text-xs text-gray-400 font-normal">(opsional)</span>
            </h2>

            <label for="photo_exit"
                   class="block rounded-xl border-2 border-dashed border-gray-300 hover:border-brand-400
                          cursor-pointer transition overflow-hidden">
                <input type="file" name="photo_exit" id="photo_exit"
                       accept="image/*" capture="environment"
                       class="hidden"
                       @change="previewPhoto($event)">
                <div x-show="!photoPreview" class="flex flex-col items-center gap-2 py-8 text-gray-400">
                    <svg class="w-10 h-10" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                              d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2
                                 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2
                                 2H5a2 2 0 01-2-2V9z"/>
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
                              d="M15 13a3 3 0 11-6 0 3 3 0 016 0z"/>
                    </svg>
                    <p class="text-sm">Ketuk untuk ambil foto / pilih dari galeri</p>
                </div>
                <div x-show="photoPreview" x-cloak class="relative">
                    <img :src="photoPreview" alt="Preview foto akhir"
                         class="w-full max-h-64 object-contain bg-black">
                    <div class="absolute bottom-2 right-2 bg-black/60 text-white text-xs px-2 py-1 rounded-full">
                        Ketuk untuk ganti
                    </div>
                </div>
            </label>
            @error('photo_exit')
                <p class="mt-1.5 text-xs text-red-600">{{ $message }}</p>
            @enderror
        </div>

        {{-- 3. Tanda tangan --}}
        <div class="rounded-2xl bg-white border border-gray-200 shadow-sm p-4 mb-5">
            <h2 class="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
                <span class="flex-shrink-0 w-6 h-6 bg-brand-600 text-white text-xs font-bold
                             rounded-full flex items-center justify-center">3</span>
                Tanda Tangan Pengambil
            </h2>

            <p class="text-xs text-gray-400 mb-3">Tanda tangani di area bawah ini menggunakan jari</p>

            {{-- Canvas wrapper --}}
            <div class="relative rounded-xl border-2 border-gray-300 bg-gray-50 overflow-hidden"
                 style="touch-action: none;">
                <canvas id="sig-canvas"
                        class="w-full block"
                        style="height: 160px;"></canvas>

                {{-- Placeholder text --}}
                <div id="sig-placeholder"
                     class="absolute inset-0 flex items-center justify-center pointer-events-none">
                    <p class="text-gray-300 text-sm select-none">Tanda tangani di sini</p>
                </div>
            </div>

            <div class="flex gap-2 mt-2">
                <button type="button" @click="undoSig()"
                        class="text-xs text-gray-600 border border-gray-300 rounded-lg px-3 py-1.5
                               hover:bg-gray-50 transition">Undo</button>
                <button type="button" @click="clearSig()"
                        class="text-xs text-red-600 border border-red-200 rounded-lg px-3 py-1.5
                               hover:bg-red-50 transition">Bersihkan</button>
                <span x-show="sigEmpty"
                      class="text-xs text-red-500 flex items-center ml-1">Wajib diisi</span>
            </div>

            {{-- Hidden input untuk base64 --}}
            <input type="hidden" name="sig_exit" id="sig_exit">
            @error('sig_exit')
                <p class="mt-1.5 text-xs text-red-600">{{ $message }}</p>
            @enderror
        </div>

        {{-- Submit --}}
        <button type="submit"
                :disabled="submitting"
                :class="submitting ? 'opacity-60 cursor-wait' : 'hover:bg-brand-700 active:bg-brand-800'"
                class="w-full flex items-center justify-center gap-2 bg-brand-600 text-white
                       font-semibold text-sm rounded-xl px-4 py-4 transition shadow-md">
            <template x-if="!submitting">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
            </template>
            <template x-if="submitting">
                <svg class="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/>
                </svg>
            </template>
            <span x-text="submitting ? 'Memproses…' : 'Selesaikan Delivery'"></span>
        </button>

    </form>
</div>
@endsection

@push('scripts')
<script>
function handoverForm() {
    return {
        photoPreview: null,
        signaturePad: null,
        sigEmpty: false,
        submitting: false,

        init() {
            const canvas = document.getElementById('sig-canvas');

            // Retina / high-DPI fix
            const ratio = Math.max(window.devicePixelRatio || 1, 1);
            canvas.width  = canvas.offsetWidth  * ratio;
            canvas.height = canvas.offsetHeight * ratio;
            canvas.getContext('2d').scale(ratio, ratio);

            this.signaturePad = new SignaturePad(canvas, {
                minWidth: 1,
                maxWidth: 2.5,
                penColor: '#1e3a5f',
            });

            this.signaturePad.addEventListener('beginStroke', () => {
                document.getElementById('sig-placeholder').style.display = 'none';
                this.sigEmpty = false;
            });
        },

        previewPhoto(event) {
            const file = event.target.files[0];
            if (!file) return;
            const reader = new FileReader();
            reader.onload = (e) => { this.photoPreview = e.target.result; };
            reader.readAsDataURL(file);
        },

        undoSig() {
            const data = this.signaturePad.toData();
            if (data.length) {
                data.pop();
                this.signaturePad.fromData(data);
            }
            if (this.signaturePad.isEmpty()) {
                document.getElementById('sig-placeholder').style.display = '';
            }
        },

        clearSig() {
            this.signaturePad.clear();
            document.getElementById('sig-placeholder').style.display = '';
        },

        handleSubmit(form) {
            if (this.signaturePad.isEmpty()) {
                this.sigEmpty = true;
                return;
            }

            document.getElementById('sig_exit').value = this.signaturePad.toDataURL('image/png');
            this.submitting = true;
            form.submit();
        },
    }
}
</script>
@endpush
