<?php

namespace App\Core\Services;

use App\Models\SmsConfiguration;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * SMS Service
 * Handles SMS sending through different providers
 */
class SmsService
{
    protected $config;

    public function __construct()
    {
        $this->config = SmsConfiguration::where('is_active', true)->first();
    }

    /**
     * Send SMS message
     */
    public function send(string $to, string $message): array
    {
        if (! $this->config) {
            return [
                'success' => false,
                'message' => 'SMS configuration not found. Please configure SMS settings first.',
            ];
        }

        $provider = $this->config->provider;

        try {
            return match ($provider) {
                'twilio' => $this->sendViaTwilio($to, $message),
                'nexmo' => $this->sendViaNexmo($to, $message),
                'messagebird' => $this->sendViaMessagebird($to, $message),
                'custom' => $this->sendViaCustom($to, $message),
                default => [
                    'success' => false,
                    'message' => "Unsupported SMS provider: {$provider}",
                ],
            };
        } catch (\Exception $e) {
            Log::error('SMS sending failed: '.$e->getMessage());

            return [
                'success' => false,
                'message' => 'Failed to send SMS: '.$e->getMessage(),
            ];
        }
    }

    /**
     * Send SMS via Twilio
     */
    protected function sendViaTwilio(string $to, string $message): array
    {
        $accountSid = env('TWILIO_ACCOUNT_SID', $this->config->api_key);
        $authToken = env('TWILIO_AUTH_TOKEN', $this->config->api_secret);
        $from = env('TWILIO_FROM_NUMBER', $this->config->sender_id);

        if (! $accountSid || ! $authToken || ! $from) {
            return [
                'success' => false,
                'message' => 'Twilio credentials are not configured.',
            ];
        }

        try {
            $response = Http::withBasicAuth($accountSid, $authToken)
                ->asForm()
                ->post("https://api.twilio.com/2010-04-01/Accounts/{$accountSid}/Messages.json", [
                    'From' => $from,
                    'To' => $to,
                    'Body' => $message,
                ]);

            if ($response->successful()) {
                return [
                    'success' => true,
                    'message' => 'SMS sent successfully',
                    'sid' => $response->json('sid'),
                ];
            }

            return [
                'success' => false,
                'message' => $response->json('message', 'Failed to send SMS'),
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Twilio error: '.$e->getMessage(),
            ];
        }
    }

    /**
     * Send SMS via Nexmo (Vonage)
     */
    protected function sendViaNexmo(string $to, string $message): array
    {
        $apiKey = env('NEXMO_API_KEY', $this->config->api_key);
        $apiSecret = env('NEXMO_API_SECRET', $this->config->api_secret);
        $from = env('NEXMO_FROM', $this->config->sender_id);

        if (! $apiKey || ! $apiSecret || ! $from) {
            return [
                'success' => false,
                'message' => 'Nexmo credentials are not configured.',
            ];
        }

        try {
            $response = Http::post('https://rest.nexmo.com/sms/json', [
                'api_key' => $apiKey,
                'api_secret' => $apiSecret,
                'from' => $from,
                'to' => $to,
                'text' => $message,
            ]);

            $data = $response->json();

            if (isset($data['messages'][0]['status']) && $data['messages'][0]['status'] == '0') {
                return [
                    'success' => true,
                    'message' => 'SMS sent successfully',
                    'message_id' => $data['messages'][0]['message-id'] ?? null,
                ];
            }

            return [
                'success' => false,
                'message' => $data['messages'][0]['error-text'] ?? 'Failed to send SMS',
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Nexmo error: '.$e->getMessage(),
            ];
        }
    }

    /**
     * Send SMS via MessageBird
     */
    protected function sendViaMessagebird(string $to, string $message): array
    {
        $apiKey = env('MESSAGEBIRD_API_KEY', $this->config->api_key);
        $originator = env('MESSAGEBIRD_ORIGINATOR', $this->config->sender_id);

        if (! $apiKey || ! $originator) {
            return [
                'success' => false,
                'message' => 'MessageBird credentials are not configured.',
            ];
        }

        try {
            $response = Http::withHeaders([
                'Authorization' => "AccessKey {$apiKey}",
            ])->post('https://rest.messagebird.com/messages', [
                'originator' => $originator,
                'recipients' => [$to],
                'body' => $message,
            ]);

            if ($response->successful()) {
                return [
                    'success' => true,
                    'message' => 'SMS sent successfully',
                    'id' => $response->json('id'),
                ];
            }

            return [
                'success' => false,
                'message' => $response->json('errors.0.description', 'Failed to send SMS'),
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'MessageBird error: '.$e->getMessage(),
            ];
        }
    }

    /**
     * Send SMS via Custom provider
     */
    protected function sendViaCustom(string $to, string $message): array
    {
        $config = $this->config->config ?? [];
        $apiUrl = $config['api_url'] ?? env('CUSTOM_SMS_API_URL');
        $apiKey = env('CUSTOM_SMS_API_KEY', $this->config->api_key);
        $apiSecret = env('CUSTOM_SMS_API_SECRET', $this->config->api_secret);

        if (! $apiUrl) {
            return [
                'success' => false,
                'message' => 'Custom SMS API URL is not configured.',
            ];
        }

        try {
            $headers = [];
            if ($apiKey) {
                $headers['Authorization'] = "Bearer {$apiKey}";
            }

            $payload = array_merge([
                'to' => $to,
                'message' => $message,
            ], $config['payload'] ?? []);

            $response = Http::withHeaders($headers)->post($apiUrl, $payload);

            if ($response->successful()) {
                return [
                    'success' => true,
                    'message' => 'SMS sent successfully',
                ];
            }

            return [
                'success' => false,
                'message' => 'Failed to send SMS: '.$response->body(),
            ];
        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Custom SMS error: '.$e->getMessage(),
            ];
        }
    }
}
