<?php

namespace App\Helpers;

use App\Models\ServiceTicket;

class WhatsAppHelper
{
    /**
     * Format nomor WA Indonesia ke format internasional (628xxx).
     * Input bisa: 08xxx, +628xxx, 628xxx, 8xxx
     */
    public static function normalizeNumber(string $number): string
    {
        // Hapus semua karakter selain digit
        $digits = preg_replace('/\D/', '', $number);

        if (str_starts_with($digits, '62')) {
            return $digits;
        }

        if (str_starts_with($digits, '0')) {
            return '62' . substr($digits, 1);
        }

        // Anggap sudah tanpa leading zero (misal: 812xxx)
        return '62' . $digits;
    }

    /**
     * Buat URL klik-untuk-kirim WA.
     *
     * @param  string  $number  Nomor WA (format apapun)
     * @param  string  $message Teks pesan
     * @return string  URL https://wa.me/...
     */
    public static function buildUrl(string $number, string $message): string
    {
        $normalized = self::normalizeNumber($number);
        $encoded    = rawurlencode($message);

        return "https://wa.me/{$normalized}?text={$encoded}";
    }

    /**
     * Buat URL WA khusus notifikasi Nota Servis.
     * Pesan sudah terformat rapi dengan info tiket + link nota.
     */
    public static function notaUrl(ServiceTicket $ticket, string $notaLink): string
    {
        $customer = $ticket->customer;

        $statusText = match ($ticket->status) {
            'Pending'   => 'sedang menunggu antrian',
            'Checking'  => 'sedang dalam proses pengecekan unit',
            'Repairing' => 'sedang dalam pengerjaan',
            'Ready'     => 'sudah *SIAP DIAMBIL* ✅',
            'Picked Up' => 'sudah diambil / selesai',
            'Cancelled' => 'dibatalkan ❌',
            default     => $ticket->status,
        };

        $lines = [
            "Halo *{$customer->name}* 👋",
            "",
            "Berikut informasi servis perangkat Anda di *Service Center*:",
            "",
            "📋 No. Tiket : *{$ticket->ticket_code}*",
            "💻 Perangkat : {$ticket->brand} {$ticket->model} ({$ticket->device_type})",
            "📌 Status     : {$statusText}",
        ];

        if ($ticket->status === 'Ready') {
            $lines[] = "";
            $lines[] = "Silakan datang untuk mengambil perangkat Anda. 🙏";
        }

        if ($ticket->status === 'Picked Up' && $ticket->picked_up_at) {
            $lines[] = "";
            $lines[] = "Terima kasih telah mempercayakan servis kepada kami! 🙏";
        }

        $lines[] = "";
        $lines[] = "🔗 Lihat Nota Digital:";
        $lines[] = $notaLink;

        $message = implode("\n", $lines);

        return self::buildUrl($customer->whatsapp, $message);
    }
}
