<?php

class OvhSms{
	const ENDPOINT = 'https://eu.api.ovh.com/1.0';
	public $key,$secret,$consumer;

	function services(){
		return $this->rest(self::ENDPOINT.'/sms','GET');
	}
	//Infos sur le serrvice (credits restants etc...)
	/* eg service : sms-ry3016-1 */
	function infos($service){
		return $this->rest(self::ENDPOINT.'/sms/'.$service.'','GET');
	}
	//Sms reçu
	/* eg service : sms-ry3016-1 */
	function incoming($service){
		return $this->rest(self::ENDPOINT.'/sms/'.$service.'/incoming','GET');
	}
	//Sms en cours d'envois & etat
	/* eg service : sms-ry3016-1 */
	function pending($service){
		return $this->rest(self::ENDPOINT.'/sms/'.$service.'/jobs','GET');
	}

	//https://docs.ovh.com/fr/sms/envoyer_des_sms_avec_lapi_ovh_en_java/
	function send($service,$phone,$message){
		return $this->rest(self::ENDPOINT.'/sms/'.$service.'/jobs','POST',json_encode(array(
			'message' => $message,
			'charset' => 'UTF-8',
			'senderForResponse' => true,
			'receivers' => array($phone)
		)));
	}

	function rest($url,$method,$fields = array(),$headers = array()){

		$timestamp = file_get_contents(self::ENDPOINT.'/auth/time');
		$signature = $this->secret.'+'.$this->consumer.'+'.$method.'+'.$url.'++'.$timestamp;


		$signature = '$1$'.sha1($signature);

		$ch = curl_init();


		$curlOptions =  array(
						CURLOPT_RETURNTRANSFER => 1,
						CURLOPT_URL => $url,
						CURLOPT_SSL_VERIFYPEER => false,
						CURLOPT_SSL_VERIFYHOST=> false,
						CURLOPT_USERAGENT => 'GuzzleHttp/6.5.3 curl/7.58.0 PHP/7.2.24-0ubuntu0.18.04.4',
						CURLOPT_SSLVERSION => 6,
						CURLOPT_FOLLOWLOCATION => true,
						CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
						CURLOPT_HTTPHEADER =>  array_merge(array(
						    'Content-Type: application/json; charset=utf-8',
						    'X-Ovh-Application: '.$this->key,
						    'X-Ovh-Timestamp: '.$timestamp,
						    'X-Ovh-Signature: '.$signature,
						    'X-Ovh-Consumer: '.$this->consumer,
						),$headers)
		);




		$curlOptions[CURLOPT_CUSTOMREQUEST] = $method;

		if(!empty($fields) || $method=='POST'){
			$curlOptions[CURLOPT_POST] = 1;

			$curlOptions[CURLOPT_POSTFIELDS] = $fields;
		}else{
			$curlOptions[CURLOPT_POST] = false;
		}

		$curlOptions[CURLINFO_HEADER_OUT] = true;



		curl_setopt_array($ch,$curlOptions);
		$result = curl_exec($ch);




		if($result === false) throw new Exception('Curl error : '.$result.curl_error($ch));

		return json_decode($result,true);
		curl_close ($ch);
	}
}
?>