<?php

namespace App\Services;

use App\Models\Setting;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Exception;

class SmsService
{
    /**
     * Send SMS to a recipient using the default gateway configured in settings.
     */
    public static function sendSms(string $phone, string $message, ?int $orderId = null): array
    {
        $gateway = Setting::getValue('default_sms_gateway', 'bulksmsbd');
        
        // Ensure recipient phone is formatted correctly (e.g. 017XXXXXXXX or +88017XXXXXXXX)
        $phone = self::formatPhoneNumber($phone);

        $result = [
            'success' => false,
            'message' => 'Unknown gateway status'
        ];

        try {
            if ($gateway === 'bulksmsbd') {
                $result = self::sendBulkSmsBd($phone, $message);
            } elseif ($gateway === 'greenweb') {
                $result = self::sendGreenweb($phone, $message);
            } elseif ($gateway === 'sslwireless') {
                $result = self::sendSslWireless($phone, $message);
            } else {
                $result = [
                    'success' => false,
                    'message' => 'Invalid default SMS gateway configured: ' . $gateway
                ];
            }
        } catch (Exception $e) {
            Log::error('SMS sending failed: ' . $e->getMessage());
            $result = [
                'success' => false,
                'message' => 'SMS gateway exception: ' . $e->getMessage()
            ];
        }

        // Database log tracking
        try {
            \App\Models\NotificationLog::create([
                'order_id' => $orderId,
                'type' => 'sms',
                'channel' => $gateway,
                'recipient' => $phone,
                'message_preview' => substr($message, 0, 500),
                'status' => $result['success'] ? 'sent' : 'failed',
                'error_message' => $result['success'] ? null : $result['message'],
            ]);
        } catch (Exception $dbEx) {
            Log::error('Failed to log SMS to notification_logs: ' . $dbEx->getMessage());
        }

        return $result;
    }

    /**
     * Format phone number to standard format (removing spaces, symbols).
     */
    private static function formatPhoneNumber(string $phone): string
    {
        $phone = preg_replace('/[^0-9]/', '', $phone);
        
        // If it starts with 880, we keep it. If it starts with 0, prepended with 880.
        if (str_starts_with($phone, '0')) {
            $phone = '88' . $phone;
        }
        
        return $phone;
    }

    /**
     * Send via BulkSMSBD.
     */
    private static function sendBulkSmsBd(string $phone, string $message): array
    {
        $apiKey = Setting::getValue('bulksmsbd_api_key');
        $senderId = Setting::getValue('bulksmsbd_sender_id');

        if (!$apiKey || !$senderId) {
            return [
                'success' => false,
                'message' => 'BulkSMSBD credentials or Sender ID not configured.'
            ];
        }

        $url = 'https://bulksmsbd.net/api/smsapi';
        
        $response = Http::get($url, [
            'api_key' => $apiKey,
            'type' => 'text',
            'number' => $phone,
            'senderid' => $senderId,
            'message' => $message,
        ]);

        if ($response->successful()) {
            $result = $response->json();
            // BulkSMSBD success response has status_code 200
            if (isset($result['response_code']) && $result['response_code'] == 200) {
                return [
                    'success' => true,
                    'message' => 'SMS sent via BulkSMSBD: ' . ($result['success_message'] ?? 'Success')
                ];
            }
            return [
                'success' => false,
                'message' => 'BulkSMSBD responded with error: ' . ($result['error_message'] ?? 'Unknown API Error')
            ];
        }

        return ['success' => false, 'message' => 'Failed to connect to BulkSMSBD gateway.'];
    }

    /**
     * Send via Greenweb.
     */
    private static function sendGreenweb(string $phone, string $message): array
    {
        $token = Setting::getValue('greenweb_token');

        if (!$token) {
            return [
                'success' => false,
                'message' => 'Greenweb SMS token is not configured.'
            ];
        }

        $url = 'https://api.greenweb.com.bd/api.php';

        $response = Http::get($url, [
            'token' => $token,
            'to' => $phone,
            'message' => $message,
        ]);

        if ($response->successful()) {
            $body = $response->body();
            // Greenweb typically returns response codes or simple string success indicator
            if (str_contains($body, 'Ok') || str_contains($body, 'Sent')) {
                return [
                    'success' => true,
                    'message' => 'SMS sent via Greenweb.'
                ];
            }
            return [
                'success' => false,
                'message' => 'Greenweb error: ' . $body
            ];
        }

        return ['success' => false, 'message' => 'Failed to connect to Greenweb gateway.'];
    }

    /**
     * Send via SSL Wireless.
     */
    private static function sendSslWireless(string $phone, string $message): array
    {
        $token = Setting::getValue('sslwireless_token');
        $sid = Setting::getValue('sslwireless_sid');

        if (!$token || !$sid) {
            return [
                'success' => false,
                'message' => 'SSL Wireless API Token or SID not configured.'
            ];
        }

        $url = 'https://smsplus.sslwireless.com/api/v3/send-sms';
        
        $payload = [
            'api_token' => $token,
            'sid' => $sid,
            'msisdn' => $phone,
            'sms' => $message,
            'csms_id' => 'CSMS' . uniqid(),
        ];

        $response = Http::asJson()->post($url, $payload);

        if ($response->successful()) {
            $result = $response->json();
            if (isset($result['status']) && $result['status'] === 'SUCCESS') {
                return [
                    'success' => true,
                    'message' => 'SMS sent via SSL Wireless: ' . ($result['status_code'] ?? 'Success')
                ];
            }
            return [
                'success' => false,
                'message' => 'SSL Wireless error: ' . ($result['error_message'] ?? 'Unknown Error')
            ];
        }

        return ['success' => false, 'message' => 'Failed to connect to SSL Wireless gateway.'];
    }
}
