<?php

namespace Vinteract\Notifications;

use Vinteract\Resources\Resource;
use Vinteract\API\Response;

use Exception;
use InvalidArgumentException;

class SMS extends Resource {
	
	/*
		Properties
	*/
	
	const SMS_URL = "https://verto-communication-server.herokuapp.com/sms";
	const VERIFY_HOST = false;
	const VERIFY_PEER = false;
	
	public $response;
	
	/*
		Constructor
	*/
	
	function __construct($params = []) {
		
		// Construct parent.
		
		parent::__construct();
		
		// Set data.
		
		$this->__set_data($params);
		
		// Required fields.
		
		$this->required = ["mobile_number", "message"];
		
	}
	
	/*
		Destructor
	*/
	
	function __destruct() {
		
	}
	
	/*
		Methods
	*/
	
    public function send($params = []) {
        
		// Set data.
		
		$this->__set_data($params);
		
		// Validate required fields before trying to send the SMS.
		
		$this->validate_required_fields();
		
		// Payload.
		
		$payload = json_encode([
			"mobileNumber" => $this->__get_data("mobile_number"),
			"message" => $this->__get_data("message"),
		]);
		
		if ($this->__get_data("premium_sms_branding")) {
			$this->messageMediaSend($this->__get_data("premium_sms_branding"), 'ALPHANUMERIC');
		} else {

			// Request.

			$ch = curl_init($this::SMS_URL);
		
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $this::VERIFY_HOST);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this::VERIFY_PEER);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
			curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json", "Content-Length: " . strlen($payload) ]);
			curl_setopt($ch, CURLOPT_POST, 1);
			
			$response = json_decode(curl_exec($ch), true);

			if ($response["success"]) {	
				$this->response = new Response([
					"code" => curl_getinfo($ch, CURLINFO_HTTP_CODE),
					"message" => $response["message"],
				]);
			}

			if ($response["error"]) {
				$this->messageMediaSend();
			}

		}
		
		// Return response.
		
		return $this->response;
		
    }

	private function messageMediaSend ($branding = '+61405096110', $source = 'INTERNATIONAL') 
	{

		$mobile = $this->__get_data("mobile_number");

		if (substr($mobile, 0, 2) === "04") {
			$mobile = $this->str_replace_first("04", "+614", $mobile);
		}

		$scheduled = $this->__get_data("send_at") != null ? $this->__get_data("send_at") : 0;

		$ch = curl_init();

		curl_setopt($ch, CURLOPT_URL, "https://api.messagemedia.com/v1/messages");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);

		curl_setopt($ch, CURLOPT_POST, TRUE);

		curl_setopt($ch, CURLOPT_POSTFIELDS, "{
			\"messages\": [
			{
				\"content\": \"" . $this->__get_data("message") . "\",
				\"destination_number\": \"" . $mobile . "\",
				\"delivery_report\": false,
				\"source_number\": \"" . $branding . "\",
				\"source_number_type\": \"" . $source . "\",
				\"scheduled\": \"" . $scheduled . "\",
			}
			]
		}");

		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			"Content-Type: application/json",
			"Accept: application/json",
			'Authorization: Basic ' . base64_encode("Ga9UfE4Hw4kxHjDWXsUr:affsMp9SgXhV9IMuFDRb9oHQG5XNev"),
		));

		$result = curl_exec($ch);

		if (curl_errno($ch)) {
			error_log('Curl Error During SMS sending');
			error_log(print_r(curl_error($ch), 1));
			return false;
		}

		$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

		curl_close($ch);

		// Success or error?

		if ($httpcode == 202) {
			$this->response = new Response([
				"code" => 200,
				"message" => "Message Media SMS sent successfully.",
			]);
		
		} else if ($httpcode == 400) {
			error_log("Message Media Bad Request");
			$this->response = new Response([
				"code" => $httpcode,
				"message" => "Message Media Bad Request.",
			]);
		} else if ($httpcode == 403) {
			error_log("Message Media Invalid Authentication Credentials");
			$this->response = new Response([
				"code" => $httpcode,
				"message" => "Message Media Invalid Authentication Credentials.",
			]);
		} else {
			error_log("Message Media Unknown Error");
			$this->response = new Response([
				"code" => $httpcode,
				"message" => "Message Media Unknown Error.",
			]);
		}
	}

	private function str_replace_first($search, $replace, $subject)
	{
		$search = '/'.preg_quote($search, '/').'/';
		return preg_replace($search, $replace, $subject, 1);
	}
	
}
