<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;

class SmsService
{
    private $apiKey;
    private $baseUrl;

    public function __construct()
    {
        // You might want to move these to your .env file
        $this->apiKey = "bBuH1o8jfTrtyAGs4svfohzL2vAGzN8N";
        $this->baseUrl = "https://bulksms.zamtel.co.zm/api/v2.1/action/send";
    }

    /**
     * Send SMS to a single recipient
     */
    public function sendSms($phoneNumber, $message, $senderId = "Immiafinance")
    {
        try {
            // Format phone number (ensure it starts with 260)
            $formattedNumber = $this->formatPhoneNumber($phoneNumber);
            
            if (!$formattedNumber) {
                Log::error('Invalid phone number format', ['phone' => $phoneNumber]);
                return false;
            }

            $url = "{$this->baseUrl}/api_key/{$this->apiKey}/contacts/{$formattedNumber}/senderId/{$senderId}/message/" . urlencode($message);

            // Log the API request for debugging
            Log::info('SMS API Request', [
                'url' => $url,
                'phone' => $formattedNumber,
                'sender_id' => $senderId
            ]);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 120);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            $result = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            $response = json_decode($result, true);
            
            Log::info('SMS API Response', [
                'phone' => $formattedNumber,
                'response' => $response,
                'http_code' => $httpCode,
                'sender_id' => $senderId
            ]);

            if (isset($response['success']) && ($response['success'] === 1 || $response['success'] === true)) {
                return true;
            }

            return false;

        } catch (\Exception $e) {
            Log::error('SMS sending failed', [
                'phone' => $phoneNumber,
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }

    /**
     * Format phone number to Zambian format (260XXXXXXXXX)
     * Corrected version to properly handle 260 prefix
     */
    private function formatPhoneNumber($phoneNumber)
    {
        // Remove any non-digit characters
        $cleanNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
        
        // If number starts with 0, replace with 260
        if (substr($cleanNumber, 0, 1) === '0') {
            return '260' . substr($cleanNumber, 1);
        }
        
        // If number starts with 26 but not 260, add 0
        if (substr($cleanNumber, 0, 2) === '26' && substr($cleanNumber, 0, 3) !== '260') {
            return '260' . substr($cleanNumber, 2);
        }
        
        // If number starts with 260, return as is
        if (substr($cleanNumber, 0, 3) === '260') {
            return $cleanNumber;
        }
        
        // If number is 9 digits, assume it's Zambian and add 260
        if (strlen($cleanNumber) === 9) {
            return '260' . $cleanNumber;
        }

        // If number is 10 digits and starts with 0, remove 0 and add 260
        if (strlen($cleanNumber) === 10 && substr($cleanNumber, 0, 1) === '0') {
            return '260' . substr($cleanNumber, 1);
        }

        Log::warning('Unable to format phone number', [
            'original' => $phoneNumber,
            'cleaned' => $cleanNumber
        ]);
        
        return false;
    }

    /**
     * Send SMS to multiple recipients
     */
    public function sendBulkSms($phoneNumbers, $message, $senderId = "IMMIAFIN")
    {
        try {
            $formattedNumbers = [];
            
            foreach ($phoneNumbers as $phoneNumber) {
                $formatted = $this->formatPhoneNumber($phoneNumber);
                if ($formatted) {
                    $formattedNumbers[] = $formatted;
                } else {
                    Log::warning('Invalid phone number in bulk SMS', ['phone' => $phoneNumber]);
                }
            }

            if (empty($formattedNumbers)) {
                Log::error('No valid phone numbers for bulk SMS');
                return false;
            }

            $contactsList = implode(',', $formattedNumbers);
            $url = "{$this->baseUrl}/api_key/{$this->apiKey}/contacts/{$contactsList}/senderId/{$senderId}/message/" . urlencode($message);

            Log::info('Bulk SMS API Request', [
                'recipient_count' => count($formattedNumbers),
                'formatted_numbers' => $formattedNumbers,
                'sender_id' => $senderId
            ]);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 120);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            $result = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            $response = json_decode($result, true);
            
            Log::info('Bulk SMS API Response', [
                'recipient_count' => count($formattedNumbers),
                'response' => $response,
                'http_code' => $httpCode
            ]);

            if (isset($response['success']) && ($response['success'] === 1 || $response['success'] === true)) {
                return true;
            }

            return false;

        } catch (\Exception $e) {
            Log::error('Bulk SMS sending failed', [
                'error' => $e->getMessage()
            ]);
            return false;
        }
    }
}