<?php

namespace App\Http\Controllers;

use App\Helpers\WhatsAppHelper;
use App\Mail\NotaServiceMail;
use App\Models\ServiceTicket;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Mail;

class NotaController extends Controller
{
    // ── HTML view (publik) ────────────────────────────────────

    public function show(string $ticketCode)
    {
        $ticket = $this->findTicket($ticketCode);

        $waUrl = $ticket->customer->whatsapp
            ? WhatsAppHelper::notaUrl($ticket, route('nota.show', $ticket->ticket_code))
            : null;

        return view('nota.show', compact('ticket', 'waUrl'));
    }

    // ── Download PDF ──────────────────────────────────────────

    public function pdf(string $ticketCode)
    {
        $ticket = $this->findTicket($ticketCode);

        $pdf = Pdf::loadView('nota.pdf', compact('ticket'))
            ->setPaper('a4', 'portrait');

        return $pdf->download("Nota-{$ticket->ticket_code}.pdf");
    }

    // ── Kirim email ke pelanggan (simulasi via MAIL_MAILER=log) ──

    public function sendEmail(string $ticketCode)
    {
        $ticket = $this->findTicket($ticketCode);

        if (! $ticket->customer->email) {
            return back()->with('error', 'Pelanggan tidak memiliki alamat email.');
        }

        Mail::to($ticket->customer->email)
            ->send(new NotaServiceMail($ticket));

        return back()->with('success', "Email nota berhasil dikirim ke {$ticket->customer->email}.");
    }

    // ── Private helper ────────────────────────────────────────

    private function findTicket(string $ticketCode): ServiceTicket
    {
        $ticket = ServiceTicket::where('ticket_code', strtoupper($ticketCode))
            ->with([
                'customer',
                'asset',
                'diagnosisTechnician',
                'finalCheckTechnician',
                'repairApprover',
                'logs' => fn ($q) => $q->with('user')->orderBy('created_at'),
            ])
            ->firstOrFail();

        $logsDesc = $ticket->logs->sortByDesc('created_at')->values();

        $diagnosisLog = $logsDesc->first(fn ($log) => str_contains(strtolower($log->note), 'diagnosa'));
        $finalQcLog = $logsDesc->first(fn ($log) => str_contains(strtolower($log->note), 'final quality check'));
        $pickupLog = $logsDesc->first(fn ($log) => str_contains(strtolower($log->note), 'pickup dari customer dikonfirmasi kurir'));
        $deliveryLog = $logsDesc->first(fn ($log) => str_contains(strtolower($log->note), 'delivery ke customer selesai') || str_contains(strtolower($log->note), 'delivery pembatalan ke customer selesai'));
        $anyTechnicianLog = $logsDesc->first(fn ($log) => $log->user?->role === 'technician');

        $diagnosisTechName = $ticket->diagnosisTechnician?->name
            ?? $diagnosisLog?->user?->name
            ?? $anyTechnicianLog?->user?->name;

        $finalQcTechName = $ticket->finalCheckTechnician?->name
            ?? $finalQcLog?->user?->name
            ?? $diagnosisTechName;

        $ticket->setAttribute('diagnosis_technician_name', $diagnosisTechName);
        $ticket->setAttribute('final_qc_technician_name', $finalQcTechName);
        $ticket->setAttribute('pickup_courier_name', $pickupLog?->user?->name);
        $ticket->setAttribute('delivery_courier_name', $deliveryLog?->user?->name);

        return $ticket;
    }
}

