<?php
defined("BASEPATH") OR exit("No direct script access allowed");

class SMS_NettyFish
{

	public $gateway = "NettyFish";

	private $url = "https://sms.nettyfish.com/vendorsms/pushsms.aspx";

	public $clientId = "";

	public $apiKey = "";

	public $sender_id = "";

	public $proxy = "";

	public function __construct($clientId="", $apiKey="", $sender_id="")
	{
		$this->CI =& get_instance();

		$this->clientId = $clientId;
		$this->apiKey = $apiKey;
		$this->sender_id = $sender_id;
	}

	public function send($toNo="", $message="", $sender_id="")
	{
		if (empty($toNo) || empty($message))
		{
			throw new Exception("Required data missing.");
			return false;
		}

		$this->CI->load->library("curl");

		$postData = array(
			"apikey" => $this->apiKey,
            "clientid" => $this->clientId,
            "msisdn" => $toNo,
            "sid" => empty($sender_id) ? $this->sender_id : $sender_id,
            "msg" => $message,
            "fl" => "0",
            "gwid" => 2	// Transactional SMS
		);

		$curlOpt = array(
			CURLOPT_BUFFERSIZE => 10,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_POSTREDIR => 7
		);

		if (defined("OB_PROXY"))
		{
			$curlOpt[CURLOPT_HTTPPROXYTUNNEL] = TRUE;
			$curlOpt[CURLOPT_PROXY] = OB_PROXY;
		}

		$result = $this->CI->curl->simple_post($this->url, $postData, $curlOpt);

		try
		{
			$result = json_decode($result, true);

			if (!empty($result["ErrorCode"]))
			{
				throw new Exception($result["ErrorMessage"]);

				// $result["JobId"];
				// $result["MessageData"];

				return false;
			}

			$this->message = $result["ErrorMessage"];
			return true;
		}
		catch(Exception $ex)
		{
			throw $ex;
			return false;
		}

        return true;
	}
/*
	private function postRequest($url, $_data)
	{
		// convert variables array to string:
		$data = array(); 
		while(list($n,$v) = each($_data))
		{
			$data[] = "$n=$v";
		}
		$data = implode("&", $data);
		// format --> test1=a&test2=b etc.
		// parse the given URL
		$url = parse_url($url);
		if ($url["scheme"] != "http")
		{
			$this->message = "Only HTTP request are supported !";
			return false;
		}

		// extract host and path:
		$host = $url["host"];
		$path = $url["path"];
		// open a socket connection on port 80
		$fp = fsockopen($host, 80);
		// send the request headers:
		fputs($fp, "POST $path HTTP/1.1\r\n");
		fputs($fp, "Host: $host\r\n");
		fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
		fputs($fp, "Content-length: ". strlen($data) ."\r\n");
		fputs($fp, "Connection: close\r\n\r\n");
		fputs($fp, $data);
		$result = "";
		
		while(!feof($fp))
		{
			// receive the results of the request
			$result .= fgets($fp, 128);
		}
		// close the socket connection:
		fclose($fp);
		// split the result header from the content
		$result = explode("\r\n\r\n", $result, 2);
		$header = isset($result[0]) ? $result[0] : "";
		$content = isset($result[1]) ? $result[1] : "";

		// return as array:
		return array($header, $content);
    }
*/
}

