<?php

require_once('ErrorDebug.php');

class CSPCtrl {

	public function curl_req($data)//, $req, $data = '')
	{
	    $ch = curl_init();

	    curl_setopt($ch, CURLOPT_URL, Config::get('editorenv.urcCSPServerAddr').'?key='.Config::get('editorenv.urcCSPServerKey'));
	    //curl_setopt($ch, CURLOPT_USERPWD, Config::get('editorenv.urcDBServerAddr'));
	    //curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	    
	    //http_build_query
	    curl_setopt($ch, CURLOPT_POST, true );
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

   	    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Basic dXJjYWRtaW46dXJjNHI0aDhrNHMxZjBsNXcyaw==', 
	    	'Content-Type: application/json','Content-Length: ' . strlen($data)));

	    $result = curl_exec($ch);
	    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	    curl_close($ch);

	    if($httpCode == 200) {
	   		return $result;
	    }

	    //ErrorDebug::write($httpCode);

	    return false;
	}

	public function register($ctrlId, $mac, $email, $devType, $serialNo) {

		$submitObj = new stdClass;
		$submitObj->key = Config::get('editorenv.urcCSPServerKey');
		//$submitObj->additionalValues = array();

		$subItem = new stdClass;
		$subItem->ControlID = $ctrlId;
		$subItem->MACID = $mac;
		$subItem->Email = $email;
		$subItem->DeviceType = $devType;
		$subItem->SerialNo = $serialNo;
		$submitObj->additionalValues[] = $subItem;

		$jsonData = json_encode($submitObj);
		$result = $this->curl_req($jsonData);
		if($result == false) return false;

		$data = json_decode($result);

		if(!isset($data->success) || $data->success != true) {
			return false;
		}

		return true;
	}
}
