<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class SmsService
{
    /**
     * TQL Solved SMS API Configuration
     */
    protected $apiUrl = 'https://sms.tqlsolved.com/smsapi';
    protected $balanceUrl = 'https://sms.tqlsolved.com/smsbalance';
    
    /**
     * Send SMS
     *
     * @param string $to
     * @param string $message
     * @return array
     */
    public function sendSms($to, $message)
    {
        try {
            // Get credentials from config
            $username = config('services.sms.username');
            $password = config('services.sms.password');
            $gatewayId = config('services.sms.gateway_id');
            
            // Validate required parameters
            if (empty($username) || empty($password) || empty($gatewayId)) {
                return [
                    'success' => false,
                    'message' => 'SMS credentials are not configured properly'
                ];
            }
            
            // Prepare parameters
            $params = [
                'username' => $username,
                'password' => $password,
                'gatewayid' => $gatewayId,
                'to' => $this->formatPhoneNumber($to),
                'text' => $message
            ];
            
            // Send request via GET method
            $response = Http::timeout(30)->get($this->apiUrl, $params);
            
            // Log the response for debugging
            Log::info('SMS API Response:', [
                'to' => $to,
                'message' => $message,
                'response' => $response->body(),
                'status' => $response->status()
            ]);
            
            // Process response
            if ($response->successful()) {
                $responseBody = trim($response->body());
                
                // Check for success code
                if (strpos($responseBody, '1005') !== false) {
                    return [
                        'success' => true,
                        'code' => 1005,
                        'message' => 'Message sent successfully!',
                        'raw_response' => $responseBody
                    ];
                }
                
                // Check for specific error codes
                $errorCodes = [
                    '1000' => 'All fields are required',
                    '1001' => 'Customer email not found',
                    '1002' => 'Password is wrong',
                    '1003' => 'Gateway not found',
                    '1006' => 'Message sent failed',
                    '2000' => 'Insufficient balance'
                ];
                
                foreach ($errorCodes as $code => $errorMessage) {
                    if (strpos($responseBody, $code) !== false) {
                        return [
                            'success' => false,
                            'code' => (int)$code,
                            'message' => $errorMessage,
                            'raw_response' => $responseBody
                        ];
                    }
                }
                
                return [
                    'success' => false,
                    'code' => 0,
                    'message' => 'Unknown response from SMS gateway',
                    'raw_response' => $responseBody
                ];
            }
            
            return [
                'success' => false,
                'code' => $response->status(),
                'message' => 'Failed to connect to SMS gateway',
                'raw_response' => $response->body()
            ];
            
        } catch (\Exception $e) {
            Log::error('SMS Send Error:', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            
            return [
                'success' => false,
                'code' => 500,
                'message' => 'Internal server error: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Check SMS Balance
     *
     * @return array
     */
    public function checkBalance()
    {
        try {
            $username = config('services.sms.username');
            $password = config('services.sms.password');
            
            if (empty($username) || empty($password)) {
                return [
                    'success' => false,
                    'message' => 'SMS credentials are not configured'
                ];
            }
            
            $params = [
                'username' => $username,
                'password' => $password
            ];
            
            $response = Http::timeout(30)->get($this->balanceUrl, $params);
            
            if ($response->successful()) {
                $responseBody = trim($response->body());
                
                // Extract balance from response
                if (preg_match('/Total Balance\s+([\d.]+)/', $responseBody, $matches)) {
                    return [
                        'success' => true,
                        'balance' => (float)$matches[1],
                        'raw_response' => $responseBody
                    ];
                }
                
                // Check for error codes
                $errorCodes = [
                    '1000' => 'All fields are required',
                    '1001' => 'Customer email not found',
                    '1002' => 'Password is wrong'
                ];
                
                foreach ($errorCodes as $code => $errorMessage) {
                    if (strpos($responseBody, $code) !== false) {
                        return [
                            'success' => false,
                            'code' => (int)$code,
                            'message' => $errorMessage,
                            'raw_response' => $responseBody
                        ];
                    }
                }
                
                return [
                    'success' => false,
                    'message' => 'Unable to parse balance response',
                    'raw_response' => $responseBody
                ];
            }
            
            return [
                'success' => false,
                'code' => $response->status(),
                'message' => 'Failed to connect to balance API',
                'raw_response' => $response->body()
            ];
            
        } catch (\Exception $e) {
            Log::error('SMS Balance Check Error:', [
                'error' => $e->getMessage()
            ]);
            
            return [
                'success' => false,
                'message' => 'Error checking balance: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * Format phone number to Bangladesh format
     *
     * @param string $phone
     * @return string
     */
    protected function formatPhoneNumber($phone)
    {
        // Remove any non-digit characters
        $phone = preg_replace('/[^0-9]/', '', $phone);
        
        // If starts with 0, replace with 880
        if (substr($phone, 0, 1) == '0') {
            $phone = '880' . substr($phone, 1);
        }
        
        // If starts with 880, return as is
        if (substr($phone, 0, 3) == '880') {
            return $phone;
        }
        
        // If starts with country code, return as is
        if (strlen($phone) >= 11) {
            return $phone;
        }
        
        // Default: assume it's a valid number
        return $phone;
    }
    
    /**
     * Send SMS to multiple recipients
     *
     * @param array $recipients
     * @param string $message
     * @return array
     */
    public function sendBulkSms($recipients, $message)
    {
        $results = [];
        $successCount = 0;
        
        foreach ($recipients as $recipient) {
            $result = $this->sendSms($recipient, $message);
            $results[] = [
                'recipient' => $recipient,
                'result' => $result
            ];
            
            if ($result['success']) {
                $successCount++;
            }
        }
        
        return [
            'success' => $successCount > 0,
            'sent_count' => $successCount,
            'total_count' => count($recipients),
            'results' => $results
        ];
    }
}