<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class FonnteService
{
    protected string $token;
    protected string $apiUrl = 'https://api.fonnte.com/send';

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

    /**
     * Kirim pesan WhatsApp via Fonnte API.
     *
     * @param  string  $target  Nomor tujuan format internasional (628xxx)
     * @param  string  $message Isi pesan
     * @return array   ['success' => bool, 'message' => string]
     */
    public function send(string $target, string $message): array
    {
        if (empty($this->token)) {
            Log::warning('FonnteService: FONNTE_TOKEN belum dikonfigurasi.');
            return [
                'success' => false,
                'message' => 'Token Fonnte belum dikonfigurasi.',
            ];
        }

        try {
            $response = Http::timeout(15)
                ->withHeaders([
                    'Authorization' => $this->token,
                ])
                ->asForm()
                ->post($this->apiUrl, [
                    'target'  => $target,
                    'message' => $message,
                ]);
            $body = $response->json();

            if ($response->successful() && isset($body['status']) && $body['status'] === true) {
                return [
                    'success' => true,
                    'message' => 'Pesan berhasil dikirim.',
                ];
            }

            // Ambil pesan error dari API jika ada
            $errMsg = $body['reason'] ?? $body['detail'] ?? 'Gagal mengirim pesan.';
            Log::warning('FonnteService: Gagal kirim ke ' . $target . ' — ' . $errMsg);

            return [
                'success' => false,
                'message' => $errMsg,
            ];

        } catch (\Illuminate\Http\Client\ConnectionException $e) {
            Log::error('FonnteService: Connection error — ' . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Koneksi ke Fonnte API gagal: ' . $e->getMessage(),
            ];
        } catch (\Throwable $e) {
            Log::error('FonnteService: Unexpected error — ' . $e->getMessage());
            return [
                'success' => false,
                'message' => 'Terjadi kesalahan: ' . $e->getMessage(),
            ];
        }
    }

    /**
     * Format nomor WA ke format internasional (628xxx)
     */
    public static function formatNomor(string $noWa): string
    {
        $clean = preg_replace('/[^0-9]/', '', $noWa);
        if (str_starts_with($clean, '0')) {
            $clean = '62' . substr($clean, 1);
        }
        return $clean;
    }
}
