<?php
class Remote {
	
	private $config;
	private $db;

	function __construct() {
		global $db, $config; //App/boostrap.php

		$this->config = $config; 
		$this->db = $db;
	}
	
	public function createRemoteRequest($survey_code=null) {
		$attach = [];
		$status = 'ok';
		
		$survey = $this->db
			->join('survey_registry sry', 'sry.survey_id=sy.id')
			->join('survey_types stp', 'stp.id=sy.type_id')
			->where('sy.code', $survey_code)
			->where('sy.json_answers', NULL, 'IS NOT')
			->where('sy.remote_added', 0)
			->getOne('survey sy', "sy.*, sry.*, sy.id survey_id, stp.survey_label, stp.cc_id, stp.ms_id, sry.created_at registry_created_at");
			
		if (isset($survey['code'])) {
			$attach = $this->db->where('survey_uuid', $survey_code)->get('survey_attachments');
			if (is_array($attach) && !empty($attach)) {
				foreach($attach as $index => $file) {
					$attach[$index]['data'] = base64_encode(file_get_contents(ATTACH_DIR.$file['uuid']));
				}
			}
		} else {
			$status = 'err';
		}
		
		$return_data = json_encode(['status'=>$status, 'survey'=>$survey, 'survey_code'=>$survey_code, 'attach'=>$attach]);
		
		$endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];
		
		$cmd = (int)$survey['remote_auto_tlc_id'] > 0 ? 'update-request' : 'create-request';
		
		$remote_auto_tlc_id = (isset($survey['remote_auto_tlc_id'])&&(int)$survey['remote_auto_tlc_id']>0) ? $survey['remote_auto_tlc_id'] : 0;
		
		$vars = ['data'=>$return_data, 'cmd'=>$cmd, 'request-id'=>$remote_auto_tlc_id];
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $endpoint);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);  //Post Fields
		//curl_setopt($ch, CURLOPT_USERPWD, "dev-ght:demo");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 
		curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout in seconds
						
		$curldata = curl_exec($ch);
		
		$curl_info = curl_getinfo($ch);
		
		file_put_contents(PUBLIC_HTML.'request.log', json_encode(curl_getinfo($ch)));
		
		curl_close($ch);
		
		return $curldata;
								
	}
	
}