<?php

namespace App\Services\Sms;

use App\Services\Trading\TradingSettingsService;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;

class SmsAfrikasTalking implements SmsProvider
{
    public function send(?string $phoneNumber, string $message): bool
    {
        if (! $this->smsNotificationsEnabled() || ! $phoneNumber) {
            return false;
        }

        $username = config('services.africastalking.username');
        $apiKey = config('services.africastalking.api_key');
        $from = config('services.africastalking.from');

        if (! $username || ! $apiKey) {
            Log::warning('Africa\'s Talking SMS skip: missing configuration.');

            return false;
        }

        $phoneNumber = $this->normalizePhoneNumber($phoneNumber);

        try {
            $response = Http::withHeaders([
                'apiKey' => $apiKey,
                'Content-Type' => 'application/x-www-form-urlencoded',
                'Accept' => 'application/json',
            ])->asForm()->post('https://api.africastalking.com/version1/messaging', [
                'username' => $username,
                'to' => $phoneNumber,
                'message' => $message,
                'from' => $from,
            ]);

            if ($response->successful()) {
                return true;
            }

            Log::error('Africa\'s Talking SMS failed.', [
                'status' => $response->status(),
                'response' => $response->json(),
            ]);

            return false;
        } catch (\Exception $e) {
            Log::error('Africa\'s Talking SMS exception: '.$e->getMessage());

            return false;
        }
    }

    protected function normalizePhoneNumber(string $phoneNumber): string
    {
        $phone = preg_replace('/[^\d+]/', '', $phoneNumber);
        if (preg_match('/^0(7|1)\d{8}$/', $phone)) {
            $phone = '+254'.substr($phone, 1);
        }
        if (! str_starts_with($phone, '+')) {
            $phone = '+'.$phone;
        }

        return $phone;
    }

    public function sendShortMessage(?string $phoneNumber, string $message): void
    {
        $this->send($phoneNumber, $message);
    }

    protected function smsNotificationsEnabled(): bool
    {
        try {
            return app(TradingSettingsService::class)->smsNotificationsEnabled();
        } catch (Throwable) {
            return true;
        }
    }
}
