<?php

namespace App\Services;

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

class SmsService
{
    public function send(string $phoneNumber, string $message): bool
    {
        $response = Http::post('https://v4.api.termii.com/api/sms/send', [
            'api_key' => config('services.termii.api_key'),
            'to' => $this->formatPhoneNumber($phoneNumber),
            'from' => config('services.termii.sender_id'),
            'sms' => $message,
            'type' => 'plain',
            'channel' => 'generic',
        ]);

        if (! $response->successful()) {
            Log::error('Termii SMS send failed', ['response' => $response->body()]);
        }

        return $response->successful();
    }

    private function formatPhoneNumber(string $phoneNumber): string
    {
        $phoneNumber = preg_replace('/\D/', '', $phoneNumber);

        if (str_starts_with($phoneNumber, '0')) {
            return '234'.substr($phoneNumber, 1);
        }

        return $phoneNumber;
    }
}