<?php

namespace Core\Librerias;

class SMS
{
    private $_user, $_pass, $_timeout;
    private $api;

    function __construct(string $username, string $password, int $timeout = 30)
    {
        $this->_user = $username;
        $this->_pass = $password;
        $this->_timeout = $timeout;
        $this->api = constant('SMS_API');
    }

    public function obtenerCreditos(): int
    {
        if ($this->_user == '' || $this->_pass == '') return -1;
        return (int) $this->conexion("{$this->api}get.asp?user={$this->_user}&password={$this->_pass}&get=credits");
    }

    public function obtenerEstatus()
    {
        if ($this->_user == '' || $this->_pass == '') return -1;
        return $this->conexion("{$this->api}get.asp?user={$this->_user}&password={$this->_pass}&get=status");
    }

    public function enviarMensaje(string $number, string $msg)
    {
        if ($this->_user == '' || $this->_pass == '') return -1;
        $number = '0' . extraer_numero_de_cadena($number);
        $msg = str_replace('+', '%20', $msg);
        $msg = str_replace(' ', '%20', $msg);
        $msg = str_replace('//', '/', $msg);
        //$msg = mb_strcut($msg, 0, 160,"UTF-8");
       
        $url=$this->api.'?phonenumber='.$number.'&Text='.$msg.'&user='.constant('SMS_USER').'&password='.constant('SMS_PASSWORD');
        return $this->conexion("{$url}");
    }

    private function conexion(string $url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->_timeout);
        $d = curl_exec($ch);
        curl_close($ch);
        return $d;
    }
}
