<?php
namespace App\Services;

class SMSService
{

    const HASH_CODE = "NmM2ODQxMzQzMDdhMzIzNTRlNDc3YTQ3NDQ2MzRmNWE=";

    const HEADER = "ICTECH";

    public static function sendSms($mobileNumberArray, $template, $variables = [])
    {
        try {
            // Replace variables in template if provided
            if (!empty($variables)) {
                foreach ($variables as $key => $value) {
                    $template = str_replace('{' . $key . '}', $value, $template);
                }
            }
          
            $apiKey = "apikey=" . self::HASH_CODE;
            $message = "&message=" . urlencode($template);
            $sender = "&sender=" . self::HEADER;
        	$numbers = implode(',', $mobileNumberArray);
            $numbers = "&numbers=" . $numbers;

            $url = "https://api.textlocal.in/send/?";
            $data = $apiKey . $numbers . $message . $sender;

            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            if (curl_errno($ch)) {
                $error = curl_error($ch);
                curl_close($ch);
                throw new \Exception("CURL Error: " . $error);
            }
            
            curl_close($ch);

            // Log the response for debugging
            \Log::info('SMS Service Response', [
                'http_code' => $httpCode,
                'response' => $response,
                'template' => $template,
                'numbers' => $mobileNumberArray
            ]);

            return $response;
            
        } catch (\Exception $e) {
            \Log::error('SMS Service Error', [
                'error' => $e->getMessage(),
                'template' => $template ?? '',
                'numbers' => $mobileNumberArray ?? []
            ]);
            
            return json_encode([
                'status' => 'error',
                'error' => $e->getMessage(),
                'code' => 'SMS_SERVICE_ERROR'
            ]);
        }
    }

    /**
     * Common method for sending SMS announcements
     * @param string $header
     * @param string $message
     * @param array $mobileNumbers
     * @return string JSON response
     */
    public static function sendAnnouncement($header, $message, $mobileNumbers)
    {
        try {
            // Validate input
            if (empty($mobileNumbers) || !is_array($mobileNumbers)) {
                return json_encode([
                    'status' => 'error',
                    'message' => 'Mobile numbers array is required',
                    'code' => 'INVALID_MOBILE_NUMBERS'
                ]);
            }

            if (empty($message)) {
                return json_encode([
                    'status' => 'error',
                    'message' => 'Message content is required',
                    'code' => 'INVALID_MESSAGE'
                ]);
            }

            // Clean and validate mobile numbers
            $validMobileNumbers = [];
            foreach ($mobileNumbers as $number) {
                $cleanNumber = preg_replace('/[^0-9+]/', '', $number);
                if (!empty($cleanNumber)) {
                    $validMobileNumbers[] = $cleanNumber;
                }
            }

            if (empty($validMobileNumbers)) {
                return json_encode([
                    'status' => 'error',
                    'message' => 'No valid mobile numbers found',
                    'code' => 'NO_VALID_NUMBERS'
                ]);
            }

            // Use custom header if provided, otherwise use default
            $smsHeader = !empty($header) ? $header : self::HEADER;
          
            $apiKey = "apikey=" . self::HASH_CODE;
            $messageParam = "&message=" . urlencode($message);
            $sender = "&sender=" . $smsHeader;
        	$numbers = implode(',', $validMobileNumbers);
            $numbersParam = "&numbers=" . $numbers;

            $url = "https://api.textlocal.in/send/?";
            $data = $apiKey . $numbersParam . $messageParam . $sender;

            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 30);

            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            if (curl_errno($ch)) {
                $error = curl_error($ch);
                curl_close($ch);
                throw new \Exception("CURL Error: " . $error);
            }
            
            curl_close($ch);

            // Log the response for debugging
            \Log::info('SMS Announcement Response', [
                'header' => $smsHeader,
                'http_code' => $httpCode,
                'response' => $response,
                'message' => $message,
                'numbers_count' => count($validMobileNumbers),
                'numbers' => $validMobileNumbers
            ]);

            // Parse response and return structured data
            $responseData = json_decode($response, true);
            if ($responseData) {
                return json_encode([
                    'status' => 'success',
                    'message' => 'SMS sent successfully',
                    'data' => $responseData,
                    'sent_to_count' => count($validMobileNumbers)
                ]);
            } else {
                return json_encode([
                    'status' => 'success',
                    'message' => 'SMS sent successfully',
                    'response' => $response,
                    'sent_to_count' => count($validMobileNumbers)
                ]);
            }
            
        } catch (\Exception $e) {
            \Log::error('SMS Announcement Error', [
                'error' => $e->getMessage(),
                'header' => $header ?? '',
                'message' => $message ?? '',
                'numbers_count' => count($mobileNumbers ?? [])
            ]);
            
            return json_encode([
                'status' => 'error',
                'error' => $e->getMessage(),
                'code' => 'SMS_ANNOUNCEMENT_ERROR'
            ]);
        }
    }

}