<?php
class SmsGateway {
    private $conn;

    // Pass the database connection when starting the class
    public function __construct($db_connection) {
        $this->conn = $db_connection;
    }

    // 1. THE MAIN FUNCTION: The rest of your software only calls this one function
    public function send($phone, $message) {
        try {
            // Step A: Ask the database "Which SMS provider is currently active?"
            $query = "SELECT provider_name, config_data FROM system_integrations WHERE module_type = 'sms' AND is_enabled = 1 LIMIT 1";
            $result = $this->conn->query($query);

            if (!$result || $result->num_rows === 0) {
                throw new Exception("No active SMS provider found in the database.");
            }

            $row = $result->fetch_assoc();
            $provider = $row['provider_name'];
            $config = json_decode($row['config_data'], true); // Unpack the JSON blob

            // Step B: Route the message to the correct "Adapter" based on the provider name
            switch ($provider) {
                case 'Arkesel':
                    return $this->sendViaArkesel($config, $phone, $message);
                case 'Hubtel':
                    return $this->sendViaHubtel($config, $phone, $message);
                case 'Twilio':
                    return $this->sendViaTwilio($config, $phone, $message);
                default:
                    throw new Exception("Unknown SMS Provider: " . $provider);
            }

        } catch (Exception $e) {
            // Log the error to your system logs here so admins know an SMS failed
            error_log("SMS Gateway Error: " . $e->getMessage());
            return false;
        }
    }

    // ----------------------------------------------------------------------
    // 2. THE ADAPTERS: Isolated scripts for each provider's unique rules
    // ----------------------------------------------------------------------

    private function sendViaArkesel($config, $phone, $message) {
        $url = $config['destination_url'] ?: 'https://sms.arkesel.com/api/v2/sms/send';
        
        $payload = [
            'sender' => $config['sender_id'],
            'message' => $message,
            'recipients' => [$phone]
        ];

        // Format the cURL request specifically for Arkesel's API rules
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'api-key: ' . $config['api_key'],
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return ($http_code == 200); // Return true if successful
    }

    private function sendViaHubtel($config, $phone, $message) {
        $url = $config['destination_url'] ?: 'https://smsc.hubtel.com/v1/messages/send';
        
        // Hubtel usually uses a ClientID:ClientSecret formatted as a base64 Basic Auth token
        // Let's assume the user pasted "ClientId:ClientSecret" into the API key field
        $auth_token = base64_encode($config['api_key']); 

        $url_with_params = $url . '?' . http_build_query([
            'From' => $config['sender_id'],
            'To' => $phone,
            'Content' => $message
        ]);

        $ch = curl_init($url_with_params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Basic ' . $auth_token
        ]);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return ($http_code == 200 || $http_code == 201);
    }

    private function sendViaTwilio($config, $phone, $message) {
        // Twilio requires Account SID and Auth Token, usually passed as the API Key in our simple UI
        // And they use a specific URL structure containing the Account SID.
        // For a true Twilio integration, you might want to adjust the UI to accept SID and Auth Token explicitly.
        
        // Example structure for Twilio:
        // URL: https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages.json
        
        // (Implementation details would go here based on Twilio's specific HTTP POST rules)
        
        return true; 
    }
}
?>