<?php

namespace App\Services;

use App\Helpers\WhatsAppHelper;
use App\Models\ServiceTicket;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * Service class untuk mengirimkan pesan WhatsApp via Fonnte API.
 *
 * Dokumentasi Fonnte: https://fonnte.com/docs
 * Endpoint : POST https://api.fonnte.com/send
 * Header   : Authorization: <token>
 * Body     : target (nomor WA), message (teks), countryCode (62)
 *
 * Alternatif API WA yang bisa digunakan:
 *  - Fonnte (https://fonnte.com) — sederhana, bayar per pesan, cocok untuk UMKM
 *  - WA Gateway / WAblas — hosting mandiri
 *  - Wabiz, Zenziva, Qiscus — berbayar, enterprise
 */
class WhatsAppService
{
    private readonly string $token;
    private readonly bool   $enabled;

    public function __construct()
    {
        $this->token   = config('services.fonnte.token', '');
        $this->enabled = config('services.fonnte.enabled', false);
    }

    /**
     * Kirim notifikasi otomatis berdasarkan status tiket baru.
     *
     * Hanya berjalan saat status = 'Ready' atau 'Picked Up'.
     * Jika Fonnte belum dikonfigurasi, tulis ke Log saja (simulasi).
     */
    public function notifyStatusChange(ServiceTicket $ticket): void
    {
        if (! in_array($ticket->status, ['Ready', 'Picked Up'])) {
            return;
        }

        $customer = $ticket->customer;

        // Nomor WA customer harus ada
        if (empty($customer?->whatsapp)) {
            Log::warning("WhatsApp: Tiket {$ticket->ticket_code} — customer tidak punya nomor WA.");
            return;
        }

        $notaUrl = route('nota.show', $ticket->ticket_code);
        $message = $this->buildMessage($ticket, $notaUrl);
        $target  = WhatsAppHelper::normalizeNumber($customer->whatsapp);

        // ── Mode simulasi (Fonnte belum dikonfigurasi) ────────
        if (! $this->enabled || $this->token === '') {
            Log::channel('stack')->info('WhatsApp [SIMULASI]', [
                'ticket'  => $ticket->ticket_code,
                'status'  => $ticket->status,
                'target'  => $target,
                'message' => $message,
            ]);
            return;
        }

        // ── Kirim ke Fonnte API ───────────────────────────────
        try {
            $response = Http::withHeaders([
                'Authorization' => $this->token,
            ])->post('https://api.fonnte.com/send', [
                'target'      => $target,
                'message'     => $message,
                'countryCode' => '62',
            ]);

            if ($response->successful() && ($response->json('status') === true)) {
                Log::info("WhatsApp terkirim: tiket {$ticket->ticket_code} → {$target}");
            } else {
                Log::error('WhatsApp gagal kirim', [
                    'ticket'   => $ticket->ticket_code,
                    'target'   => $target,
                    'status'   => $response->status(),
                    'response' => $response->json(),
                ]);
            }
        } catch (\Throwable $e) {
            // Jangan sampai error WA menghentikan proses utama
            Log::error("WhatsApp exception: {$e->getMessage()}", [
                'ticket' => $ticket->ticket_code,
            ]);
        }
    }

    /**
     * Buat teks pesan sesuai status tiket.
     */
    private function buildMessage(ServiceTicket $ticket, string $notaUrl): string
    {
        $name   = $ticket->customer->name;
        $code   = $ticket->ticket_code;
        $device = "{$ticket->brand} {$ticket->model} ({$ticket->device_type})";

        if ($ticket->status === 'Ready') {
            return implode("\n", [
                "Halo *{$name}* 👋",
                "",
                "Kabar baik! Perangkat Anda sudah selesai diperbaiki dan *SIAP DIAMBIL* ✅",
                "",
                "📋 No. Tiket : *{$code}*",
                "💻 Perangkat : {$device}",
                "📌 Status     : Siap Diambil",
                "",
                "Silakan datang ke Service Center untuk mengambil perangkat Anda.",
                "Harap tunjukkan nomor tiket kepada petugas. 🙏",
                "",
                "🔗 Nota Digital:",
                $notaUrl,
            ]);
        }

        // Status: Picked Up
        return implode("\n", [
            "Halo *{$name}* 👋",
            "",
            "Terima kasih! Perangkat Anda telah berhasil *diambil / selesai*. 🎉",
            "",
            "📋 No. Tiket : *{$code}*",
            "💻 Perangkat : {$device}",
            "📌 Status     : Sudah Diambil",
            "",
            "Terima kasih telah mempercayakan servis perangkat Anda kepada kami.",
            "Semoga perangkat Anda berfungsi dengan baik! 🙏",
            "",
            "🔗 Simpan Nota Digital Anda:",
            $notaUrl,
        ]);
    }
}
