<?php
/*  Portal Controller */

Class Portal extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();

		$parameters = json_decode(file_get_contents('php://input'), true);
	}

	function index()
	{ 	
		$this->load->view('login');
	}

	function login_check()
	{
		$email = $this->input->post('email');
		$password = $this->input->post('password');
		$loginString = $email.':'.$password;
		//$loginString = 'test.uat@glboothby.com:Password123';
		$this->session->set_userdata('emailstring',$loginString );

		$encodedLogin = base64_encode($loginString);

		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL => $this->Api_Url.'login',
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_POST => 1,	
			CURLOPT_HEADER => 1,
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Authorization: Basic '.$encodedLogin,
				'Client-IP: '.$this->Client_ip,
				'Transfer-Encoding:chunked',
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent
			),
		));

		$result = curl_exec($curl);
		//$result_decode = json_decode($result);

		$loginResponse = $this->parseHttpResponse($result);
		$cookie = $this->parseCookieHeader($loginResponse['headers']['Set-Cookie']);

		//debug($cookie,1);

		if( $loginResponse['body']->Message == 'SUCCESS' )
		{
			$this->session->set_userdata('account_number', $loginResponse['body']->Data->AccountNumbers[0] );
			$this->session->set_userdata('account_cookie', $cookie['account'] );
			echo 'done';
		}
		else
		{
			echo $loginResponse;
		}

		/*if( $result_decode->Message == 'SUCCESS' )
		{
			$this->session->set_userdata('account_number', $result_decode->Data->AccountNumbers[0] );
			echo 'done';
		}
		else
		{*/
			/*echo $result;
			echo '###';*/
			/*echo json_encode($loginResponse, JSON_PRETTY_PRINT);
			echo '###';
			echo json_encode($cookie, JSON_PRETTY_PRINT);*/
		//}
	}

	function check_session()
	{
		if( empty($this->session->userdata('account_number')) || empty($this->session->userdata('account_cookie')) )
		{
			$this->session->set_flashdata('session_msg', 'Session Expires');
			redirect('portal/index');
		}
	}

	function user_logout()
	{
		$this->session->unset_userdata('account_number');
		$this->session->unset_userdata('account_cookie');
		$this->session->set_flashdata('logout_msg', 'Logout Successful');

		redirect('portal/index');
	}

	function parseHttpResponse($response)
	{
	    // Parse the headers
		$headers = array();

		$body = null;

		// Split up the httpResponse
		$responseParts = explode("\r\n\r\n", $response);
		foreach ($responseParts as $i => $responsePart)
	    {
	    	$lines = explode("\r\n", $responsePart);

	    	// If the part has 200 response Code, parse the rest of the lines as headers.
	    	if($lines[0] == "HTTP/1.1 200 OK")
	    	{
				foreach ($lines as $j => $line)
			    {
			        if ($j === 0)
			            $headers['http_code'] = $line;
			        else
			        {
			            list ($key, $value) = explode(': ', $line);

			            $headers[$key] = $value;
			        }
			    }
	    	}
	    	// If last element, probably body
	    	else if($i === sizeof($responseParts)-1)
	    	{
	    		$body = json_decode($responsePart);
	    	}
	    }

	    return array(
	    	'headers' => $headers,
	    	'body' => $body
	    );
	}

	/*
	Account=KgInYYpL\/38WSRBdkWvmLPiWw4JBEGZVcm5XX\/2KWk4W5qRF4KCIZQgJ+BpO5kSGmNd\/LVc7Y0gywx5ZcGdcCdDJCO2JWIXhYhm44Oq4Y+Y3{*}; expires=Fri, 08-Sep-2017 12:33:24 GMT; path=\/
	*/

	function unescapeHeaderValue($v)
	{
		// When json strings are parsed, escape characters like '\/' are converted to '/'
		return json_decode('"' . $v . '"');
	}

	function parseCookieHeader($header)
	{
		$headerUnescaped = $this->unescapeHeaderValue($header);
		$headerParts = explode("; ", $headerUnescaped);
		$accountPart = $headerParts[0];
		$expiresPart = $headerParts[1];

		return array(
			'account' => substr($accountPart, strpos($accountPart, "=")+1),
			'expires'=> substr($expiresPart, strpos($expiresPart, "=")+1)
		);
	}

	function check_login()
	{

		$encodedLogin = base64_encode($this->session->userdata('emailstring'));

		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL => $this->Api_Url.'login',
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_POST => 1,
			CURLOPT_HEADER => 1,
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Authorization: Basic '.$encodedLogin,
				'Client-IP: '.$this->Client_ip,
				'Transfer-Encoding:chunked',
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent
			),
		));

		$response = curl_exec($curl);
		$data=explode("\n",$response);
		//debug($data,1);
		return $cookieString = str_replace('Set-Cookie: ', '', trim($data[9]));
	}


	function account()
	{
		$this->check_session();
		//$cookieString = $this->check_login();
		$curl = curl_init();
			curl_setopt_array($curl, array(
			CURLOPT_URL => $this->Api_Url.'Account/'.$this->session->userdata('account_number'),
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_HEADER => 1,
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Client-IP: '.$this->Client_ip,
				//'Authorization: Basic '.$this->session->userdata('emailstring'),
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent,
				'Cookie: Account='.$this->session->userdata('account_cookie')
			),
		));
		$result = curl_exec($curl);
		
		$loginResponse = $this->parseHttpResponse($result);
		$cookie = $this->parseCookieHeader($loginResponse['headers']['Set-Cookie']);

		if( $loginResponse )
		{
			//$result_decode = json_decode($result);
			//debug($result_decode,1);
			if(  $loginResponse['body']->Message == 'SUCCESS' )
			{
				$data['elec_mpan'] = $loginResponse['body']->Data->Sites[0]->ElectricMeters[0]->Mpan;
				$data['profile'] = $loginResponse['body']->Data;
				$this->session->set_userdata('account_name', $loginResponse['body']->Data->Name);
				$this->session->set_userdata('sites_data',  $loginResponse['body']->Data->Sites);
				$this->session->set_userdata('elec_mpan', $loginResponse['body']->Data->Sites[0]->ElectricMeters[0]->Mpan);
				$this->session->set_userdata('gas_mprn', $loginResponse['body']->Data->Sites[0]->GasMeters[0]->Mprn);
				$this->session->set_userdata('account_cookie', $cookie['account'] );

				$data['gas_mprn'] = $loginResponse['body']->Data->Sites[0]->GasMeters[0]->Mprn;
				$this->load->view('account', $data);
			}
		}
		else
		{
			echo $result; exit;
		}

	}

	function elec_reading()
	{
		$this->check_session();
		//$cookieString = $this->check_login();

		//$cookieString = str_replace(' ', '+', $cookieString);

		$ch = curl_init();
			curl_setopt_array($ch, array(
			CURLOPT_URL => $this->Api_Url.'MeterReading/'.$this->session->userdata('account_number').'/Electricity/'.$this->session->userdata('elec_mpan'),
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_HEADER => 1,
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Client-IP: '.$this->Client_ip,
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent,
				'Cookie: Account='.$this->session->userdata('account_cookie')
			),
		));

		$Elec_result = curl_exec($ch);
		$elec_result_decode = json_decode($Elec_result);

		$loginResponse = $this->parseHttpResponse($Elec_result);
		$cookie = $this->parseCookieHeader($loginResponse['headers']['Set-Cookie']);
		//debug($loginResponse,1);
		if( !empty($loginResponse['body']->Mpan) )
		{
			$data['reading_today'] = $loginResponse['body']->Meters[0]->Registers[0]->Readings[0]->Reading;
			$data['reading_previous'] = $loginResponse['body']->Meters[0]->Registers[0]->Readings[1]->Reading;

			$this->session->set_userdata('account_cookie', $cookie['account'] );

			$this->load->view('electric_reading', $data);
		}
		else
		{
			echo $loginResponse['body']->Message;
		}
	}


	function gas_reading()
	{
		$this->check_session();
		$ch = curl_init();
			curl_setopt_array($ch, array(
			CURLOPT_URL => $this->Api_Url.'MeterReading/'.$this->session->userdata('account_number').'/Gas/'.$this->session->userdata('gas_mprn'),
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_HEADER => 1,
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Client-IP: '.$this->Client_ip,
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent,
				'Cookie: Account='.$this->session->userdata('account_cookie')
			),
		));
		$Elec_result = curl_exec($ch);
		$elec_result_decode = json_decode($Elec_result);


		$loginResponse = $this->parseHttpResponse($Elec_result);
		$cookie = $this->parseCookieHeader($loginResponse['headers']['Set-Cookie']);

		//debug($elec_result_decode,1);
		if( !empty($loginResponse['body']->Mprn) )
		{
			$data['reading_today'] = $loginResponse['body']->Meters[0]->Readings[0]->Reading;
			$data['reading_previous'] = $loginResponse['body']->Meters[0]->Readings[1]->Reading;
			$this->session->set_userdata('account_cookie', $cookie['account'] );

			$this->load->view('gas_reading', $data);
		}
		else
		{
			echo $loginResponse['body']->Message;
		}
	}


	function invoice()
	{
		$this->check_session();
		//$cookieString = $this->check_login();

		$ch = curl_init();
			curl_setopt_array($ch, array(
			CURLOPT_URL => $this->Api_Url.'Invoice/'.$this->session->userdata('account_number'),
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_HEADER => 1,
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Client-IP: '.$this->Client_ip,
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent,
				'Cookie: Account='.$this->session->userdata('account_cookie')
			),
		));
		$Elec_result = curl_exec($ch);
		$elec_result_decode = json_decode($Elec_result);

		$loginResponse = $this->parseHttpResponse($Elec_result);
		$cookie = $this->parseCookieHeader($loginResponse['headers']['Set-Cookie']);

		//debug($elec_result_decode);
		if($loginResponse['body']->Message == 'SUCCESS')
		{
			$data['invoice'] = $loginResponse['body']->Data[0]->Invoices;
			$this->session->set_userdata('account_cookie', $cookie['account'] );
			$this->load->view('elec_billing',$data);
		}
		else
		{
			echo $loginResponse['body']->Message;
		}

	}

	function elec_billing()
	{
		$this->check_session();
		$this->load->view('elec_billing');
	}

	function gas_billing()
	{
		$this->check_session();
		$this->load->view('gas_billing');
	}

	function send_elec_reading()
	{
		$this->check_session();
		$site_data = $this->session->userdata('sites_data');

		$reading_parameter = [
			'Reading' => $this->input->post('elec_reading'),
			'Register' => $site_data[0]->ElectricMeters[0]->Meters[0]->Registers[0],
			'SerialNumber' =>$site_data[0]->ElectricMeters[0]->Meters[0]->SerialNumber
		];

		//debug($reading_parameter);

		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_POST => 1,
			CURLOPT_HEADER => 1,
			CURLOPT_URL => $this->Api_Url.'MeterReading/'.$this->session->userdata('account_number').'/Electricity/'.$site_data[0]->ElectricMeters[0]->Mpan,
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Client-IP: '.$this->Client_ip,
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent,
				'Cookie: Account='.$this->session->userdata('account_cookie')
			),
			CURLOPT_POSTFIELDS => json_encode($reading_parameter),
		));
		$Elec_result = curl_exec($curl);

		$loginResponse = $this->parseHttpResponse($Elec_result);
		$cookie = $this->parseCookieHeader($loginResponse['headers']['Set-Cookie']);
		
		//debug($loginResponse);
		if($loginResponse['body']->Message == 'SUCCESS')
		{
			$this->session->set_userdata('account_cookie', $cookie['account'] );
			echo json_encode($loginResponse['body']);
		}
		else
		{
			echo $loginResponse;
		}
		
	}

	function send_gas_reading()
	{
		$this->check_session();
		$site_data = $this->session->userdata('sites_data');

		//debug($site_data);
		$reading_parameter = [
			'Reading' => $this->input->post('gas_reading'),
			'SerialNumber' =>$site_data[0]->GasMeters[0]->Meters[0]->SerialNumber
		];
		//debug($reading_parameter);
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_POST => 1,
			CURLOPT_HEADER => 1,
			CURLOPT_URL => $this->Api_Url.'MeterReading/'.$this->session->userdata('account_number').'/Gas/'.$site_data[0]->GasMeters[0]->Mprn,
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Client-IP: '.$this->Client_ip,
				'Authorization: Basic '.$this->session->userdata('emailstring'),
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent,
				'Cookie: Account='.$this->session->userdata('account_cookie')
			),
			CURLOPT_POSTFIELDS => json_encode($reading_parameter),
		));
		$Elec_result = curl_exec($curl);
		$elec_result_decode = json_decode($Elec_result);

		$loginResponse = $this->parseHttpResponse($Elec_result);
		$cookie = $this->parseCookieHeader($loginResponse['headers']['Set-Cookie']);

		if($loginResponse['body']->Message == 'SUCCESS')
		{
			$this->session->set_userdata('account_cookie', $cookie['account'] );
			echo json_encode($loginResponse['body']);
		}
		else
		{
			echo $loginResponse;
		}
	}

	function forgotpassword()
	{
		$this->load->view('forgotpassword');
	}

	function change_password()
	{

		$reading_parameter['Email'] = $this->input->post('email');

		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_POST => 1,
			CURLOPT_URL => $this->Api_Url.'ForgottenPassword/',
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Client-IP: '.$this->Client_ip,
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent,
			),
			CURLOPT_POSTFIELDS => json_encode($reading_parameter),
		));
		$Elec_result = curl_exec($curl);
		debug($Elec_result);
	}

	function reset_password()
	{
		$reading_parameter['Email'] = $this->input->post('email');

		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_POST => 1,
			CURLOPT_URL => $this->Api_Url.'ResetPassword/',
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Client-IP: '.$this->Client_ip,
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent,
			),
			CURLOPT_POSTFIELDS => json_encode($reading_parameter),
		));
		$Elec_result = curl_exec($curl);
		debug($Elec_result);
	}

	function changepassword()
	{
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_RETURNTRANSFER => 1,

			CURLOPT_URL => $this->Api_Url.'RedeemPasswordReset/?t='.urlencode($_REQUEST['t']).'&ev='.urlencode($_REQUEST['ev']),
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Client-IP: '.$this->Client_ip,
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent,
			),
		));
		$Elec_result = curl_exec($curl);
			$elec_result_decode = json_decode($Elec_result);
			if($elec_result_decode->Message == 'Success')
			{
				$data['email'] = $elec_result_decode->Data->Email;
				$data['t'] = $_REQUEST['t'];
				$data['ev'] = $_REQUEST['ev'];
				$this->load->view('changepassword', $data);
			}
		else
		{
			$data['error'] = json_decode($Elec_result);
			$this->load->view('changepassword', $data);
		}
	}

	function new_password()
	{
		$reading_parameter['Email'] = $this->input->post('email');
		$reading_parameter['Password'] = $this->input->post('password');
		$reading_parameter['ConfirmPassword'] = $this->input->post('cpassword');

		//die();
		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_POST => 1,
			CURLOPT_URL => $this->Api_Url.'RedeemPasswordReset/?t='.urlencode($this->input->post('t')).'&ev='.urlencode($this->input->post('ev')),
			CURLOPT_HTTPHEADER => array(
				'Api-Key: '.$this->Api_Key,
				'Api-Type: Website',
				'Client-IP: '.$this->Client_ip,
				'Content-Type:application/json',	
				'Accept: application/json',	
				'Client-UA:'.$this->client_agent,
			),
			CURLOPT_POSTFIELDS => json_encode($reading_parameter),
		));
		$Elec_result = curl_exec($curl);
		$elec_result_decode = json_decode($Elec_result);
		if($elec_result_decode->Message == 'Success')
		{
			$this->session->set_flashdata('logout_msg', 'Password Change');
			redirect('portal/index');
		}
		else
		{
			$this->session->set_flashdata('session_msg', 'Password Change Fail');
			redirect('portal/changepassword');
		}
	}
}