<?php

class HostpinacleGateway implements SmsGatewayInterface
{
    private $apiKey;
    private $senderID;
    private $username;
    private $endpoint;
    private $password;

    public function init(array $config): void
    {
        $this->apiKey = $config['apiKey'];
        $this->senderID = $config['senderID'];
        $this->username = $config['username'];
        $this->password = $config['password'];
        $this->endpoint = "https://sms.biznr.co.ke/SMSApi/";
    }

    public function send($recipient, string $message, string $name='', bool $group=false)
    { 
        if (empty($recipient)) {
            throw new RuntimeException('Phone Number is required');
            return false;
        }

        if (empty($message)) {
            throw new RuntimeException('Message is required');
            return false;
        }
        
        $postData = [
            'userid' => $this->username,
            'password' => $this->password,
            'senderid' => $this->senderID,
            'sendMethod' => 'quick',
            'msgType' => 'text',
            'output' => 'json',
            'duplicatecheck' => 'true',
            'msg'=> $message,
            'mobile'=> SmsUtils::formatPhone($recipient),
        ];

        $response = SmsUtils::sendPOSTSMS($postData);

        // Removed any logging here. Only the service/controller should handle logging.

        if ($response) {
            if (isset($response) && $response['status'] == 'success' && $response['statusCode'] === "200") {
                $this->getBalance();                
            }
        }
    
        return $response;
    }

    public function sendBulk(array $recipients): bool
    { 
        $fileName = "bulk_messages_" . date('YmdHis') . ".txt";

        try {
            $filePath = SmsUtils::createTxtFile($recipients, $fileName);
        } catch (RuntimeException $e) {
            error_log($e->getMessage());
            return false;
        }

        if (!file_exists($filePath)) {
            error_log("File does not exist: " . $filePath);
            return false;
        }

        $postData = [
            'userid' => $this->username,
            'password' => $this->password,
            'senderid' => $this->senderID,
            'sendMethod' => 'bulkupload',
            'msgType' => 'text',
            'output' => 'json',
            'duplicatecheck' => 'true',
            'file' => new CURLFile($filePath, 'text/plain', $fileName)
        ];

        $result = SmsUtils::sendPOSTSMS($postData);
        unlink($filePath);

        // Removed any logging here. Only the service/controller should handle logging.

        if ($result && isset($result['status']) && $result['status'] === 'success') {
            return true;
        } else {
            error_log("API Response: " . print_r($result, true));
        }

        return false;
    }

    public function getBalance(): float
    {
        $request = "account/readstatus?userid=" . urlencode($this->username) .
            "&password=" . $this->password .
            "&output=" . 'json';
            
            
        $postData = [
            'userid' => $this->username,
            'password' => $this->password,
            'output'=> 'json',
        ];

        $smsResponse = SmsUtils::sendPOSTSMS($postData, 'account/readstatus');

        $smsBalance = isset($smsResponse['response']['account']['smsBalance']) ? $smsResponse['response']['account']['smsBalance'] : null;

        if ($smsBalance !== null) {
            $ci     = &get_instance();
            $ci->load->model("smssettings_m");

            $array = array(            
                array(
                    'field_names' => 'celcom_balance',
                    'field_values' => $smsBalance
                )
            );

            $ci->smssettings_m->update_celcom($array);
        } else {
            throw new RuntimeException('SMS balance information is unavailable.');
        }     

       return true;
    }
}