<?php
/*
	Usage :

	require_once(APPPATH . 'third_party/OutputSMS/OutputSMS.php');
	OutputSMS("+919843047765", "Test SMS from OutputBooks : ", "COM10", "115200");

*/
if (!function_exists('OutputSMSExe'))
{
	function OutputSMSExe($toNo="", $message="", $portNo="", $baudRate="")
	{
		if (empty($toNo))
		{
			return;
		}

		if (empty($message))
		{
			$message = "Test SMS from OutputBooks : " . date("d/m/Y h:i:s A l");
		}

		$cmd = '"' . APPPATH . 'third_party\\OutputSMS\\OutputSMS.exe" "' . $toNo . '" "' . $message . '"';

		if (!empty($portNo))
		{
			$cmd .= " " . $portNo;
		}

		if (!empty($baudRate))
		{
			$cmd .= " " . $baudRate;
		}

		exec($cmd, $output, $return_var);

		if (!empty($output) && !empty($output[0]) && strpos($output[0], "ERROR") >= 0)
		{
			return $output[0];
		}

		if (!empty($return_var) && $return_var)
		{
			return $return_var;
		}

		return true;
	}
}

if (!function_exists('OutputSMSPhp'))
{
	function OutputSMSPhp($toNo="", $message="", $portNo="", $baudRate="")
	{
		if (empty($toNo))
		{
			return;
		}

		if (empty($message))
		{
			$message = "Test SMS from OutputBooks : " . date("d/m/Y h:i:s A l");
		}

		require_once(APPPATH . 'third_party/OutputSMS/php_serial.class.php');

		// try
		// {
			$serial = new phpSerial;
			$serial->deviceSet($portNo);
			$serial->confBaudRate($baudRate);

			// Then we need to open it
			$serial->deviceOpen();

			// To write into
			$serial->sendMessage('AT+CMGF=1\n\r');
			/*
			if (is_array($toNo))
			{
				foreach($toNo as $val)
				{
					$serial->sendMessage('AT+CMSS=3,"' . $val . '"');
				}
			}
			else
			{
				$serial->sendMessage('AT+CMGS="' . $toNo . '"\n\r');
			}
			*/
			$serial->sendMessage('AT+CMGS="' . $toNo . '"\n\r');
			$serial->sendMessage($message . '\n\r');
			$serial->sendMessage(chr(26));

			//wait for modem to send message
			sleep(7);
			$read = $serial->readPort();
			$serial->deviceClose();
		/*
		}
		catch(Exception $e)
		{
			return $e->getMessage();
		}
		*/

		return true;
	}
}

if (!function_exists('OBOutputSMS'))
{
	function OBOutputSMS($toNo="", $message="", $settings=null, $log="cId:")
	{
		if (empty($settings["url"]) || empty($settings["data"]))
		{
			return;
		}

        if (is_array($message))
        {
            $replacer = array(
				"%OB_TO_NO%" => $toNo,
				"%OB_MESSAGE%" => json_encode($message[0])
			);
        }
        else
        {
            $replacer = array(
				"%OB_TO_NO%" => $toNo,
				"%OB_MESSAGE%" => $message
			);
        }

		$data = array();

		foreach($settings["data"] as $key => $val)
		{
			if (empty($data[$val["method"]]))
			{
				$data[$val["method"]] = array();
			}

			if (!empty($val["urlencoded"]))
			{
				$replacer["%OB_MESSAGE%"] = urlencode($replacer["%OB_MESSAGE%"]);
			}

			$val["value"] = str_replace(array_keys($replacer), array_values($replacer), $val["value"]);

			/*
			if ($val["method"] == "get")
			{
				$get .= $val["key"] . "=" . str_replace(array_keys($replacer), array_values($replacer), $val["val"]) . "&";
			}
			*/

			$data[$val["method"]][$val["key"]] = $val["value"];
		}

		@file_put_contents(FCPATH . "temp/sms.log", gmdate("d/m/Y H:i:s") . "\t" . $log . "\t" . $toNo . "\t" . $message . PHP_EOL, FILE_APPEND);

		if ($settings["url"] == "EXE")
		{
			return OutputSMSExe($toNo, $message, $data["head"]["portNo"], $data["head"]["baudRate"]);
		}
		else if ($settings["url"] == "PHP")
		{
			return OutputSMSPhp($toNo, $message, $data["head"]["portNo"], $data["head"]["baudRate"]);
		}
		else if ($settings["url"] == "API")
		{
			if (!empty($data["head"]["portNo"]) && file_exists(APPPATH . "third_party/OutputSMS/SMS_" . $data["head"]["portNo"] . ".php"))
			{
				$className = "SMS_" . $data["head"]["portNo"];
				if (!class_exists($className))
				{
					require_once(APPPATH . "third_party/OutputSMS/" . $className . ".php");
				}

				// $data["head"]["clientId"]
				// $data["head"]["apiKey"]
				// $data["head"]["senderId"]

				if (class_exists($className))
				{
					$smsGateWay = new $className($data);
					return $smsGateWay->send($toNo, $message);
				}
/*
				if (class_exists($className) && defined("SMS_CLIENT_ID") && defined("SMS_API_KEY") && defined("SMS_SENDER_ID"))
				{
					$smsGateWay = new $className(SMS_CLIENT_ID, SMS_API_KEY, SMS_SENDER_ID);
					return $smsGateWay->send($toNo, $message);
				}
*/
			}
		}
		else if (!empty($settings["url"]))
		{
			$CI = & get_instance();
			$CI->load->library("curl");

			$curlOpt = array(
				CURLOPT_BUFFERSIZE => 10,
				CURLOPT_FOLLOWLOCATION => true,
				CURLOPT_POSTREDIR => 7,
				CURLOPT_RETURNTRANSFER => TRUE,
				CURLOPT_FAILONERROR => false,
//				CURLOPT_HTTP200ALIASES => array(400)
			);
			// defined("OB_PROXY") OR define("OB_PROXY","http://192.168.2.1:3128");
			if (defined("OB_PROXY"))
			{
				// 61 =
				// 10004 = 
				$curlOpt[CURLOPT_HTTPPROXYTUNNEL] = TRUE;
				$curlOpt[CURLOPT_PROXY] = OB_PROXY;
			}

			$getQuery = empty($data["get"]) ? "" : http_build_query($data["get"], "", "&");

			if (!empty($data["curl"]))
			{
				foreach($data["curl"] as $header => $content)
				{
					$curlOpt[$header] = $content;
				}
			}

			if (!empty($data["head"]))
			{
				foreach($data["head"] as $header => $content)
				{
					$CI->curl->http_header($header, $content);
				}
			}

			// $result = $CI->curl->simple_post($settings["url"] . ($getQuery ? "?" . $getQuery : ""), empty($data["post"]) ? array() : $data["post"], $curlOpt);

			if(!empty($data["post"]))
			{
				$isJsonFound = false;
				foreach($data["post"] as $key => $val)
				{
					$jsVal = json_decode($val, TRUE);
					if(empty($key)&& is_array($jsVal))
					{ //For whatsapp notification,message stored as json 
						unset($data["post"][$key]);
						foreach($jsVal as $jkey => $jval)
						{
							$data["post"][$jkey] = $jval;
						}
					}
					else
					{
						$data["post"][$key] = $jsVal ? $jsVal : $val;
					}
					if($jsVal)
					{
						$isJsonFound = true;
					}
				}

				if ($isJsonFound)
				{
					$curlOpt[CURLOPT_HTTPHEADER][] = "Content-Type: application/json-patch+json";
					$CI->curl->http_header("Content-Type", "application/json-patch+json");
					$data["post"] = json_encode($data["post"]);
				}

				$result = $CI->curl->simple_post($settings["url"] . ($getQuery ? "?" . $getQuery : ""), $data["post"], $curlOpt);
			}
			else
			{
				// $CI->curl->options($curlOpt);
				$result = $CI->curl->simple_get($settings["url"] . ($getQuery ? "?" . $getQuery : ""), array(), $curlOpt);
				// $result = file_get_contents($settings["url"] . ($getQuery ? "?" . $getQuery : ""));
			}

			@file_put_contents(FCPATH . "temp/sms.log", gmdate("d/m/Y H:i:s") . "\t" . $log . "\t" . print_R($result, TRUE) . PHP_EOL, FILE_APPEND);
			@file_put_contents(FCPATH . "temp/sms.log", "--------------------------------------------------" . PHP_EOL, FILE_APPEND);

			return $result;
		}
	}
}

