<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\ServiceAsset;
use App\Models\ServiceLog;
use App\Models\ServiceTicket;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class ServiceTicketController extends Controller
{
    /**
     * Tampilkan form buat tiket baru.
     */
    public function create(): View
    {
        $deviceTypes = ServiceTicket::DEVICE_TYPES;

        return view('tickets.create', compact('deviceTypes'));
    }

    /**
     * Simpan tiket baru ke database.
     * intake_type = 'walkin'  → data lengkap, status Pending
     * intake_type = 'courier' → data minimal, status Pickup Requested
     */
    public function store(Request $request): RedirectResponse
    {
        $intakeType = $request->input('intake_type', 'walkin');

        if ($intakeType === 'courier') {
            // ── Validasi minimal untuk pickup request ──────────────
            $validated = $request->validate([
                'customer_name'     => ['required', 'string', 'max:255'],
                'customer_whatsapp' => ['required', 'string', 'max:20'],
                'customer_address'  => ['required', 'string', 'max:1000'],
                'pickup_note'       => ['nullable', 'string', 'max:1000'],
            ]);

            DB::transaction(function () use ($validated) {
                $customer = Customer::firstOrCreate(
                    [
                        'name'     => $validated['customer_name'],
                        'whatsapp' => $validated['customer_whatsapp'],
                    ],
                    [
                        'address' => $validated['customer_address'],
                    ]
                );

                // Update alamat jika customer sudah ada tapi belum ada alamat
                if (empty($customer->address) && ! empty($validated['customer_address'])) {
                    $customer->update(['address' => $validated['customer_address']]);
                }

                $ticket = ServiceTicket::create([
                    'customer_id' => $customer->id,
                    'status'      => 'Pickup Requested',
                    'pickup_note' => $validated['pickup_note'] ?? null,
                ]);

                ServiceLog::create([
                    'ticket_id' => $ticket->id,
                    'user_id'   => auth()->id() ?? 1,
                    'note'      => 'Permintaan pickup oleh kurir dicatat. Status: Pickup Requested.',
                ]);

                session()->flash('ticket_code', $ticket->ticket_code);
                session()->flash('ticket_id',   $ticket->id);
            });

            return redirect()->route('tickets.success');
        }

        // ── Validasi lengkap untuk walk-in ──────────────────────
        $validated = $request->validate([
            // Customer
            'customer_name'    => ['required', 'string', 'max:255'],
            'customer_whatsapp'=> ['nullable', 'string', 'max:20'],
            'customer_email'   => ['nullable', 'email', 'max:255'],
            'customer_address' => ['nullable', 'string', 'max:1000'],

            // Device
            'device_type'      => ['required', 'in:' . implode(',', ServiceTicket::DEVICE_TYPES)],
            'brand'            => ['required', 'string', 'max:100'],
            'model'            => ['required', 'string', 'max:100'],
            'serial_number'    => ['nullable', 'string', 'max:100'],
            'problem_desc'     => ['required', 'string', 'max:2000'],

            // Assets (keduanya opsional, tapi jika ada harus valid)
            'photo_entry'        => ['nullable', 'image', 'max:5120'],  // max 5 MB
            'sig_entry'          => ['nullable', 'string'],             // base64 PNG dari canvas

            // Kelengkapan & kondisi
            'accessories'        => ['nullable', 'array'],
            'accessories.*'      => ['string', 'max:100'],
            'accessories_other'  => ['nullable', 'string', 'max:255'],
            'physical_condition' => ['nullable', 'string', 'max:1000'],
            'device_password'    => ['nullable', 'string', 'max:100'],
        ]);

        DB::transaction(function () use ($validated, $request) {
            // 1. Buat atau temukan customer berdasarkan nama + WA
            $customer = Customer::firstOrCreate(
                [
                    'name'     => $validated['customer_name'],
                    'whatsapp' => $validated['customer_whatsapp'] ?? null,
                ],
                [
                    'email'   => $validated['customer_email']   ?? null,
                    'address' => $validated['customer_address'] ?? null,
                ]
            );

            // 2. Buat tiket
            $ticket = ServiceTicket::create([
                'customer_id'   => $customer->id,
                'device_type'   => $validated['device_type'],
                'brand'         => $validated['brand'],
                'model'         => $validated['model'],
                'serial_number' => $validated['serial_number'] ?? null,
                'problem_desc'  => $validated['problem_desc'],
                'status'        => 'Pending',
            ]);

            // 3. Proses aset (foto & tanda tangan)
            $photoPath = null;
            $sigPath   = null;

            // Simpan foto dari kamera
            if ($request->hasFile('photo_entry')) {
                $photoPath = $request->file('photo_entry')
                    ->store("tickets/{$ticket->id}/entry", 'public');
            }

            // Konversi base64 → file PNG
            if (!empty($validated['sig_entry'])) {
                $sigPath = $this->saveBase64Signature(
                    $validated['sig_entry'],
                    "tickets/{$ticket->id}/entry",
                    'signature_entry'
                );
            }

            // 3b. Gabungkan daftar aksesori
            $accessories = $validated['accessories'] ?? [];
            if (!empty($request->input('accessories_other'))) {
                $accessories[] = 'Lain-lain: ' . trim($request->input('accessories_other'));
            }

            if ($photoPath || $sigPath || $accessories || !empty($validated['physical_condition']) || !empty($validated['device_password'])) {
                ServiceAsset::create([
                    'ticket_id'          => $ticket->id,
                    'photo_entry'        => $photoPath,
                    'sig_entry'          => $sigPath,
                    'accessories'        => $accessories ?: null,
                    'physical_condition' => $validated['physical_condition'] ?? null,
                    'device_password'    => $validated['device_password']    ?? null,
                ]);
            }

            // 4. Catat log awal
            ServiceLog::create([
                'ticket_id' => $ticket->id,
                'user_id'   => auth()->id() ?? 1,   // fallback ke user 1 jika belum ada auth
                'note'      => 'Tiket dibuat. Status: Pending.',
            ]);

            // Simpan ticket_code ke session untuk ditampilkan
            session()->flash('ticket_code', $ticket->ticket_code);
            session()->flash('ticket_id',   $ticket->id);
        });

        return redirect()->route('tickets.success');
    }

    /**
     * Halaman konfirmasi setelah tiket berhasil dibuat.
     */
    public function success(): View
    {
        $ticketCode = session('ticket_code');
        $ticketId   = session('ticket_id');

        abort_if(!$ticketCode, 404);

        $ticket = ServiceTicket::with(['customer', 'asset'])
            ->findOrFail($ticketId);

        return view('tickets.success', compact('ticket'));
    }

    /**
     * Halaman detail tiket (target URL QR Code).
     */
    public function show(ServiceTicket $ticket): View
    {
        $ticket->load(['customer', 'asset', 'logs.user']);

        $qrUrl = route('tickets.show', $ticket->id);

        return view('tickets.show', compact('ticket', 'qrUrl'));
    }

    /**
     * Halaman cetak label (50mm × 30mm).
     */
    public function label(ServiceTicket $ticket): View
    {
        $ticket->load('customer');

        $qrUrl = route('tickets.show', $ticket->id);

        return view('tickets.label', compact('ticket', 'qrUrl'));
    }

    // ─────────────────────── Private Helpers ───────────────────────

    /**
     * Dekode string base64 (format data:image/png;base64,…) dan simpan sebagai .png.
     * Mengembalikan path relatif di disk "public".
     */
    private function saveBase64Signature(string $base64, string $directory, string $filename): string
    {
        // Hilangkan header data URI jika ada
        $data = preg_replace('/^data:image\/\w+;base64,/', '', $base64);
        $data = base64_decode($data);

        $path = "{$directory}/{$filename}.png";

        Storage::disk('public')->put($path, $data);

        return $path;
    }
}
