<?php

use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

if (! function_exists('sendSMS')) {
    /**
     * Send a sms
     */
    function sendSMS(string|int $phone, string|int $message): bool
    {
        try {
            $response = Http::timeout(config('services.sms.timeout'))
                ->connectTimeout(config('services.sms.connect_timeout'))
                ->retry(
                    times: 3,
                    sleepMilliseconds: 50,
                    throw: false,
                    when: function (Throwable $exception, PendingRequest $request): bool {
                        if ($exception instanceof ConnectionException) {
                            return true;
                        }

                        if ($exception instanceof RequestException) {
                            return $exception->response->serverError();
                        }

                        return false;
                    }
                )
                ->post(config('services.sms.url'), [
                    'phone' => '+993'.$phone,
                    'code' => $message,
                ]);

            if (! $response->successful()) {
                Log::error('SMS API request failed', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);

                return false;
            }

            return true;
        } catch (Throwable $exception) {
            Log::error('SMS API exception', [
                'message' => $exception->getMessage(),
            ]);

            return false;
        }
    }
}

if (! function_exists('unmask_phone')) {
    /**
     * Unmask Turkmenistan phone number from TM code +993 6X XX XX XX to 6xxxxxxx
     */
    function unmask_phone(string $phone): string
    {
        $digits = preg_replace('/\D+/', '', $phone);

        if (str_starts_with($digits, '993')) {
            $digits = substr($digits, 3);
        }

        if (preg_match('/^6\d{7}$/', $digits)) {
            return $digits;
        }

        return '';
    }
}

if (! function_exists('format_phone')) {
    /**
     * Format an 8-digit TM mobile number for display (+993 6X XX XX XX).
     */
    function format_phone(string $phone): string
    {
        if (! preg_match('/^6\d{7}$/', $phone)) {
            return $phone;
        }

        return sprintf(
            '+993 %s %s %s %s',
            substr($phone, 0, 2),
            substr($phone, 2, 2),
            substr($phone, 4, 2),
            substr($phone, 6, 2),
        );
    }
}
