<?php

namespace App\Notifications;

use App\Models\Order;
use App\Services\WhatsAppGateway;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;

class LaundryProgressNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(private readonly Order $order)
    {
    }

    public function via(object $notifiable): array
    {
        return ['database'];
    }

    public function toArray(object $notifiable): array
    {
        return [
            'invoice_no' => $this->order->invoice_no,
            'status' => $this->order->status,
            'message' => $this->message(),
        ];
    }

    public function sendWhatsApp(WhatsAppGateway $gateway): void
    {
        $phone = $this->order->customer?->phone;

        if ($phone) {
            $gateway->send($phone, $this->message());
        }
    }

    private function message(): string
    {
        $order = $this->order->loadMissing(['customer', 'progressLogs']);
        $latestProgress = $order->progressLogs->sortByDesc('created_at')->first()?->progress_status;
        $trackingUrl = route('tracking.index');
        $balance = number_format((float) $order->balance_due, 0, ',', '.');

        return trim("Halo {$order->customer?->name}, update laundry Anda:\n"
            ."Nota: {$order->invoice_no}\n"
            .'Status: '.str_replace('_', ' ', $order->status)."\n"
            .'Progress: '.str_replace('_', ' ', $latestProgress ?: 'order diterima')."\n"
            ."Pembayaran: {$order->payment_status}, sisa Rp {$balance}\n"
            ."Tracking: {$trackingUrl}");
    }
}
