<?php
/**
 * Class for working with api.smses.ru
 *
 * @link http://api.smses.ru/
 * @author Dzmitri dimedr Salodki <dimedrby@gmail.com>
 * @version 1.0
 * @see http://api.smses.ru/info/documentation.php
 *
 * @copyright 2011-2012 ЗАО "Торговый Дом "Албес"
 */
class Smses {
    private $_apiUrl = 'http://api.smses.ru/';
    private $_login;
    private $_password;
    private $_phone;
    private $_text;
    private $_senderID;
    private $_partner;
    public $debug;

    /**
     * Smses constructor.
     *
     * @param string $login Login or API Login.
     * @param string $password Password or API Password.
     */
    public function __construct( $login, $password ) {
        $this->_login = $login;
        $this->_password = $password;
    }

    /**
     * Set partner id.
     * 
     * @param string $partnerID
     */
    public function setPartner( $partnerID ) {
        $this->_partner = ( int ) trim( $partnerID );
    } 

    /**
     * Return user information (balance, senders id, default sender id) in json.
     *
     * @return string Array in json.
     */
    public function userInfo() {
        $requestURI = $this->_apiUrl . 'api?action=authorization' . '&login=' . $this->_login
            . '&password=' . md5( $this->_password );
        return file_get_contents( $requestURI );
    }

    /**
     * Send message.
     *
     * @param string $phone Number of the recipient.
     * @param string $text Message text.
     * @param null $senderID Sender id.
     * @param null $partner Partner id.
     * @return string Array in json.
     */
    public function send( $phone, $text, $senderID = null, $partner = null ) {
        $this->_partner = $this->encode($partner);
        $this->_phone = $this->encode($phone);
        $this->_senderID = $this->encode($senderID);
        $this->_text = $this->encode($text);

        $requestURI = $this->_apiUrl . 'api?action=send_sms' . '&login=' . $this->_login
            . '&password=' . md5( $this->_password ) . '&phones=' . $this->_phone . '&text=' . $this->_text
            . '&sender=' . $this->_senderID . '&partner=TviTGFeSbo';
        
        if($this->debug)
        	$requestURI.='&debug=true';
       	
        return file_get_contents($requestURI);
    }

    /**
     * Return cost message to $phone with $text.
     * @warning Worked with only login and password, no api login and api password.
     *
     * @param string $phone Number of the recipient.
     * @param string $text Text message.
     * @return string Array in json.
     */
    public function getCost( $phone, $text ) {
        $requestURI = $this->_apiUrl . 'api?action=sms_cost' . '&login=' . $this->_login
            . '&password=' . md5( $this->_password ) . '&phones=' . $phone
            . '&text=' . $text;
        return file_get_contents( $requestURI );
    }
    
    private function encode($text)
    {
    	return urlencode(urldecode($text));
    }
}