<?php

namespace App\Channels;

use Illuminate\Http\Client\Response;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class WhatsAppChannel
{
    /**
     * Send the given notification.
     *
     * @param  mixed  $notifiable
     * @param  \Illuminate\Notifications\Notification  $notification
     * @return \Illuminate\Http\Client\Response|null
     */
    public function send($notifiable, Notification $notification): ?Response
    {
        if (!method_exists($notification, 'toWhatsApp')) {
            return null;
        }

        /** @var array{phone: string, message: string} $data */
        $data = $notification->toWhatsApp($notifiable);

        if (empty($data['phone']) || empty($data['message'])) {
            Log::warning('WhatsApp notification tidak bisa dikirim: nomor HP atau pesan kosong');
            return null;
        }

        try {
            $response = Http::withHeaders([
                'Authorization' => config('services.fonnte.token'),
            ])->post('https://api.fonnte.com/send', [
                'target' => $this->formatPhoneNumber($data['phone']),
                'message' => $data['message'],
                'countryCode' => '62',  // Indonesia
            ]);

            if ($response->successful()) {
                Log::info('WhatsApp berhasil dikirim ke: ' . $data['phone']);
            } else {
                Log::error('Gagal kirim WhatsApp: ' . $response->body());
            }

            return $response;
        } catch (\Exception $e) {
            Log::error('Error kirim WhatsApp: ' . $e->getMessage());
            // Jangan throw exception, biar email tetap terkirim
            return null;
        }
    }

    /**
     * Format phone number to international format.
     *
     * @param  string  $phone
     * @return string
     */
    private function formatPhoneNumber(string $phone): string
    {
        // Remove non-numeric characters
        $phone = preg_replace('/[^0-9]/', '', $phone);

        // Convert 08xx to 628xx
        if (substr($phone, 0, 1) === '0') {
            $phone = '62' . substr($phone, 1);
        }

        // Add 62 if not exists
        if (substr($phone, 0, 2) !== '62') {
            $phone = '62' . $phone;
        }

        return $phone;
    }
}
