<?php
class SmsManager {
    private $db;
    private $provider;
    private $config;
    private $is_enabled;

    public function __construct($db_connection) {
        $this->db = $db_connection;
        $this->loadConfig();
    }

    /**
     * Pulls the live SMS configuration straight from your new database table.
     */
    private function loadConfig() {
        $stmt = $this->db->query("SELECT provider_name, is_enabled, config_data FROM system_integrations WHERE module_type = 'sms'");
        if ($stmt && $row = $stmt->fetch_assoc()) {
            $this->provider = $row['provider_name'];
            $this->is_enabled = ($row['is_enabled'] == 1);
            $this->config = json_decode($row['config_data'], true);
        } else {
            $this->is_enabled = false;
        }
    }

    /**
     * The single public method you will call from anywhere in your system.
     */
    public function sendSms($phone, $message) {
        if (!$this->is_enabled) {
            return ['status' => 'error', 'message' => 'SMS gateway is currently disabled in system settings.'];
        }

        // Format phone number to standard Ghanaian format if necessary (e.g., 024 -> 23324)
        $phone = $this->formatPhoneNumber($phone);

        // Route to the currently selected provider
        switch ($this->provider) {
            case 'Arkesel':
                return $this->sendArkesel($phone, $message);
            case 'Hubtel':
                return $this->sendHubtel($phone, $message);
            case 'SMSOnlineGH':
                return $this->sendSmsOnlineGh($phone, $message);
            default:
                return ['status' => 'error', 'message' => 'Unknown SMS provider configured.'];
        }
    }

    // --- ARKESEL INTEGRATION (v2 API) ---
    private function sendArkesel($phone, $message) {
        $api_key = $this->config['api_key'] ?? '';
        $sender_id = $this->config['sender_id'] ?? 'RIMAX';

        $url = 'https://sms.arkesel.com/api/v2/sms/send';
        $data = [
            'sender' => $sender_id,
            'message' => $message,
            'recipients' => [$phone]
        ];

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'api-key: ' . $api_key,
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return ($http_code == 200) 
            ? ['status' => 'success', 'response' => json_decode($response, true)] 
            : ['status' => 'error', 'message' => 'Arkesel API failed.'];
    }

    // --- HUBTEL INTEGRATION ---
    private function sendHubtel($phone, $message) {
        $client_id = $this->config['client_id'] ?? '';
        $client_secret = $this->config['client_secret'] ?? '';
        $sender_id = $this->config['sender_id'] ?? 'RIMAX';

        $url = "https://smsc.hubtel.com/v1/messages/send?clientid={$client_id}&clientsecret={$client_secret}&from={$sender_id}&to={$phone}&content=" . urlencode($message);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return ($http_code == 200 || $http_code == 201) 
            ? ['status' => 'success', 'response' => json_decode($response, true)] 
            : ['status' => 'error', 'message' => 'Hubtel API failed.'];
    }

    // --- SMSONLINEGH INTEGRATION ---
    private function sendSmsOnlineGh($phone, $message) {
        $username = $this->config['username'] ?? '';
        $api_key = $this->config['api_key'] ?? '';
        $sender_id = $this->config['sender_id'] ?? 'RIMAX';

        $url = "https://api.smsonlinegh.com/v4/message/sms/send";
        $url .= "?key=" . urlencode($api_key);
        $url .= "&text=" . urlencode($message);
        $url .= "&type=0"; // 0 for plain text
        $url .= "&sender=" . urlencode($sender_id);
        $url .= "&destinations=" . urlencode($phone);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return ($http_code == 200) 
            ? ['status' => 'success', 'response' => $response] 
            : ['status' => 'error', 'message' => 'SMSOnlineGH API failed.'];
    }

    // --- UTILITY: FORMAT PHONE FOR GHANA ---
    private function formatPhoneNumber($phone) {
        // Remove spaces and special characters
        $phone = preg_replace('/[^0-9]/', '', $phone);
        // If it starts with 0, replace with 233
        if (strpos($phone, '0') === 0 && strlen($phone) == 10) {
            $phone = '233' . substr($phone, 1);
        }
        return $phone;
    }
}
?>