<!doctype html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Form Pemeriksaan {{ $order->invoice_no }}</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 text-slate-900">
<main class="mx-auto min-h-screen max-w-md bg-slate-100 px-4 pb-8 pt-5">
    <header class="rounded-2xl bg-white p-5 shadow-sm">
        <div class="text-sm text-slate-500">Form pemeriksaan barang</div>
        <h1 class="mt-1 text-2xl font-semibold">{{ $order->invoice_no }}</h1>
        <div class="mt-3 grid grid-cols-2 gap-3 text-sm">
            <div class="rounded-md bg-slate-50 p-3">
                <div class="text-slate-500">Pelanggan</div>
                <div class="font-medium">{{ $order->customer?->name ?? 'Walk-in' }}</div>
            </div>
            <div class="rounded-md bg-slate-50 p-3">
                <div class="text-slate-500">Status</div>
                <div class="font-medium">{{ $order->status }}</div>
            </div>
        </div>
    </header>

    <form method="post" action="{{ route('digital-forms.store', $order) }}" enctype="multipart/form-data" class="mt-4 space-y-4" id="inspection-form">
        @csrf

        <section class="rounded-2xl bg-white p-5 shadow-sm">
            <h2 class="font-semibold">Foto Evidence</h2>
            <p class="mt-1 text-sm text-slate-500">Ambil beberapa foto kondisi barang per nota. Foto akan dikompres di HP sebelum dikirim.</p>
            <label class="mt-4 flex cursor-pointer items-center justify-center rounded-xl border-2 border-dashed border-slate-300 bg-slate-50 px-4 py-8 text-center text-sm font-medium text-slate-700">
                <span>Tambah Foto</span>
                <input id="evidence-input" name="evidence_files[]" type="file" accept="image/*" capture="environment" multiple class="sr-only">
            </label>
            <div id="evidence-hidden"></div>
            <div id="evidence-preview" class="mt-4 grid grid-cols-3 gap-3"></div>
        </section>

        <section class="rounded-2xl bg-white p-5 shadow-sm">
            <h2 class="font-semibold">Checklist Kondisi</h2>
            <div class="mt-4 grid gap-3 text-sm">
                @foreach ([
                    'ada_noda' => 'Ada noda terlihat',
                    'ada_robek' => 'Ada robek / bolong',
                    'warna_luntur' => 'Warna berpotensi luntur',
                    'kancing_resleting' => 'Kancing / resleting perlu perhatian',
                    'barang_berharga' => 'Ada barang tertinggal',
                    'jumlah_belum_final' => 'Jumlah/berat belum final',
                ] as $key => $label)
                    <label class="flex items-center justify-between rounded-lg border px-3 py-3">
                        <span>{{ $label }}</span>
                        <input type="checkbox" name="checklist[{{ $key }}]" value="1" class="h-5 w-5 rounded border-slate-300">
                    </label>
                @endforeach
            </div>
        </section>

        <section class="rounded-2xl bg-white p-5 shadow-sm">
            <h2 class="font-semibold">Keterangan Kondisi</h2>
            <textarea name="general_note" rows="5" placeholder="Contoh: 2 kemeja ada noda di kerah, 1 celana robek kecil di saku kanan, customer sudah menyetujui kondisi awal." class="mt-3 w-full rounded-xl border px-3 py-3 text-sm">{{ old('general_note') }}</textarea>
        </section>

        <section class="rounded-2xl bg-white p-5 shadow-sm">
            <div class="flex items-center justify-between gap-3">
                <h2 class="font-semibold">Tanda Tangan Pelanggan</h2>
                <button type="button" id="clear-signature" class="rounded-md border px-3 py-1.5 text-xs">Hapus</button>
            </div>
            <div class="mt-3 overflow-hidden rounded-xl border bg-white">
                <canvas id="signature-pad" class="block h-48 w-full touch-none"></canvas>
            </div>
            <input type="hidden" name="signature_data" id="signature-data">
            <p class="mt-2 text-xs text-slate-500">Dengan tanda tangan ini pelanggan menyetujui catatan kondisi awal barang.</p>
        </section>

        <div class="sticky bottom-0 -mx-4 bg-slate-100/95 px-4 py-3 backdrop-blur">
            <button class="w-full rounded-xl bg-slate-900 px-4 py-3 font-semibold text-white">Simpan Form Pemeriksaan</button>
            <a href="{{ route('orders.show', $order) }}" class="mt-2 block rounded-xl border bg-white px-4 py-3 text-center text-sm font-medium">Kembali ke Order</a>
        </div>
    </form>
</main>

<script>
const input = document.getElementById('evidence-input');
const preview = document.getElementById('evidence-preview');
const hidden = document.getElementById('evidence-hidden');
const maxEdge = 1600;

input.addEventListener('change', async (event) => {
    preview.innerHTML = '';
    hidden.innerHTML = '';

    for (const file of Array.from(event.target.files).slice(0, 12)) {
        const dataUrl = await compressImage(file);
        const img = document.createElement('img');
        img.src = dataUrl;
        img.className = 'aspect-square w-full rounded-lg object-cover';
        preview.appendChild(img);

        const field = document.createElement('input');
        field.type = 'hidden';
        field.name = 'evidence_images[]';
        field.value = dataUrl;
        hidden.appendChild(field);
    }

    input.removeAttribute('name');
});

function compressImage(file) {
    return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = () => {
            const image = new Image();
            image.onload = () => {
                const scale = Math.min(1, maxEdge / Math.max(image.width, image.height));
                const canvas = document.createElement('canvas');
                canvas.width = Math.round(image.width * scale);
                canvas.height = Math.round(image.height * scale);
                const ctx = canvas.getContext('2d');
                ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
                resolve(canvas.toDataURL('image/jpeg', 0.72));
            };
            image.src = reader.result;
        };
        reader.readAsDataURL(file);
    });
}

const canvas = document.getElementById('signature-pad');
const signatureData = document.getElementById('signature-data');
const clearButton = document.getElementById('clear-signature');
const form = document.getElementById('inspection-form');
const ctx = canvas.getContext('2d');
let drawing = false;
let signed = false;

function resizeCanvas() {
    const ratio = window.devicePixelRatio || 1;
    const rect = canvas.getBoundingClientRect();
    canvas.width = rect.width * ratio;
    canvas.height = rect.height * ratio;
    ctx.scale(ratio, ratio);
    ctx.lineWidth = 2.4;
    ctx.lineCap = 'round';
    ctx.strokeStyle = '#0f172a';
}

function point(event) {
    const rect = canvas.getBoundingClientRect();
    const touch = event.touches?.[0] || event;
    return { x: touch.clientX - rect.left, y: touch.clientY - rect.top };
}

canvas.addEventListener('pointerdown', (event) => {
    drawing = true;
    signed = true;
    const p = point(event);
    ctx.beginPath();
    ctx.moveTo(p.x, p.y);
});
canvas.addEventListener('pointermove', (event) => {
    if (!drawing) return;
    const p = point(event);
    ctx.lineTo(p.x, p.y);
    ctx.stroke();
});
window.addEventListener('pointerup', () => drawing = false);
clearButton.addEventListener('click', () => {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    signatureData.value = '';
    signed = false;
});
form.addEventListener('submit', () => {
    if (signed) {
        signatureData.value = canvas.toDataURL('image/png');
    }
});
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
</script>
</body>
</html>
