<?php

namespace App\Services;

use App\CentralLogics\SMS_module;
use App\Traits\SmsGateway as AppSmsGateway;

class OutboundSmsService
{
    public function send(string $phone, string $message): array
    {
        $gateway = null;

        try {
            $gateway = $this->resolveGatewayName();
            $response = AppSmsGateway::sendCustomMessage($phone, $message);

            if ($response === 'not_found' || $response === 'unsupported_custom_message') {
                $fallbackResponse = SMS_module::sendCustomMessage($phone, $message);

                if ($fallbackResponse !== 'not_found') {
                    $response = $fallbackResponse;
                    $gateway = $gateway ?: $this->resolveGatewayNameFromSmsModule();
                }
            }

            return [
                'response' => (string) $response,
                'gateway' => $gateway,
                'error' => null,
            ];
        } catch (\Throwable $throwable) {
            return [
                'response' => 'exception',
                'gateway' => $gateway,
                'error' => $throwable->getMessage(),
            ];
        }
    }

    private function resolveGatewayName(): ?string
    {
        $providers = [
            'twilio',
            'nexmo',
            '2factor',
            'msg91',
            'releans',
            'hubtel',
            'paradox',
            'signal_wire',
            '019_sms',
            'viatech',
            'global_sms',
            'akandit_sms',
            'sms_to',
            'alphanet_sms',
        ];

        foreach ($providers as $provider) {
            $config = AppSmsGateway::get_settings($provider);
            if ((int) data_get($config, 'status') === 1) {
                return $provider;
            }
        }

        return null;
    }

    private function resolveGatewayNameFromSmsModule(): ?string
    {
        $providers = ['twilio', 'nexmo', '2factor', 'msg91', 'alphanet_sms'];

        foreach ($providers as $provider) {
            $config = SMS_module::get_settings($provider);
            if ((int) data_get($config, 'status') === 1) {
                return $provider;
            }
        }

        return null;
    }
}
