<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class NanoHealthController extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('wallet_model');
		$this->load->model('nano_health_model');
	}


	public function updateConfigYearsPricesGrid(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$configId = $_POST['config_id'];
				$grid = $_POST['grid'] ?? [];

				$this->db->trans_begin();
				$this->db->delete('nh_years_prices_grid',['nh_network_config_id' => $configId]);
				if(sizeof($grid) > 0){
					$this->db->insert_batch('nh_years_prices_grid',$grid);
				}
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					echo json_encode("500");
				} else {
					$this->db->trans_commit();
					echo json_encode("200");
				}
			}
		}
	}

	public function updateConfigMonthsPricesGrid(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$configId = $_POST['config_id'];
				$grid = $_POST['grid'] ?? [];
				foreach ($grid as $i => $row){
					foreach ($row as $k => $v){
						if(empty($v)){
							$grid[$i][$k] = null;
						}
					}
				}

				$this->db->trans_begin();
				foreach ($grid as $row){
					$n = $row['payment_period'] == 'DAILY' ? 22 : 1 ;
					if($row['payment_period'] == 'ONE_TIME'){
						$row['payment_duration_months'] = null;
					}
					$row['number_of_fractions'] = $n * ($row['payment_duration_months'] ?? 1);
					if(!empty($row['id'])){
						$this->db->where('id',$row['id']);
						$this->db->update('nh_months_prices_grid', $row);
					}else{
						$this->db->insert('nh_months_prices_grid',$row);
					}
				}
				if ($this->db->trans_status() === FALSE) {
					$this->db->trans_rollback();
					echo json_encode("500");
				} else {
					$this->db->trans_commit();
					echo json_encode("200");
				}
			}
		}
	}

	public function storeAct(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$id = $_POST['id'] ?? null;
				$_POST['nh_network_config_id'] = $_POST['config_id'];
				$_POST['amount'] = empty($_POST['amount']) ? null : $_POST['amount'];
				$_POST['unit_value'] = empty($_POST['unit_value']) ? null : $_POST['unit_value'];
				unset($_POST['config_id']);

				$exist = $this->db->get_where('nh_acts', ['id !=' => $id , 'nh_network_config_id' => $_POST['nh_network_config_id'] , 'code' => $_POST['code']]);
				if ($exist->num_rows() == 0) {
					if(!empty($id)){
						$this->db->where('id',$id);
						$this->db->update('nh_acts',$_POST);
					}else{
						$this->db->insert('nh_acts',$_POST);
					}
					echo json_encode(['code' => 200]);

				}else{
					echo json_encode(['code'=> 419 , 'message' => $this->lang->line("code_already_used")]);
				}
			}
		}
	}

	public function deleteAct(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$this->db->delete('nh_acts', ['id' => $_POST['id']]);
				echo json_encode(['code' => 200 ]);
			}
		}
	}

	public function createValidatingAgent()
	{
		if($this->isLogged()) {
			if (isset($_POST)) {
				$emailExist = $this->db->get_where('nh_validating_agents', ['email' => $_POST['email']]);
				if ($emailExist->num_rows() == 0) {
					do {
						$token = bin2hex(openssl_random_pseudo_bytes(16));
						$tokenExist = $this->db->get_where('nh_validating_agents',['token' => $token]);
					} while ($tokenExist->num_rows() > 0);

					$_POST['token'] = $token;
					$query = $this->db->insert('nh_validating_agents', $_POST);

					if ($query) {

						$link = base_url("Agent_password/?token=" . $token);
						$this->load->library('email');

						$this->email->from('noreply@ilink-app.com', 'iLink World');
						$this->email->to($_POST['email']);

						$this->email->subject($this->lang->line($_POST['role'] == 'DOCTOR' ?  "mail_title_validating_doctor" : "mail_title_validating_agent"));
						$this->email->message($_POST['firstname'] . ' ' . $_POST['lastname'] . ' ' . $this->lang->line($_POST['role'] == 'DOCTOR' ? "mail_body_validating_doctor" : "mail_body_validating_agent") . ' ' . $link);

						$this->email->send();

						echo json_encode(['code' => 200]);
					} else {
						echo json_encode(['code' => 500, 'message' => $this->lang->line("Une erreur s'est produite")]);
					}
				} else {
					echo json_encode(['code'=> 419 , 'message' => $this->lang->line("L'email entré est déjà utilisé")]);
				}
			}
		}
	}

	public function updateValidatingAgent()
	{
		if($this->isLogged()) {
			if (isset($_POST)) {
				$emailExist = $this->db->get_where('nh_validating_agents', ['id !=' => $_POST['id'], 'email' => $_POST['email']]);
				if ($emailExist->num_rows() == 0) {
					$this->db->where('id',$_POST['id']);
					$this->db->update('nh_validating_agents',$_POST);
					echo json_encode(['code' => 200]);
				}else{
					echo json_encode(['code'=> 419 , 'message' => $this->lang->line("L'email entré est déjà utilisé")]);
				}
			}
		}
	}

	public function deleteValidatingAgent(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$this->db->delete('nh_validating_agents', ['id' => $_POST['id']]);
				echo json_encode(['code' => 200]);
			}
		}
	}

	public function storeProviderClass(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$id = $_POST['id'];
				$_POST['nh_network_config_id'] = $_POST['config_id'];
				unset($_POST['config_id']);

				if(!empty($id)){
					$this->db->where('id',$id);
					$this->db->update('nh_provider_classes',$_POST);
				}else{
					$this->db->insert('nh_provider_classes',$_POST);
				}

				echo json_encode(['code' => 200 ]);
			}
		}
	}

	public function deleteProviderClass(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$this->db->delete('nh_provider_classes', ['id' => $_POST['id']]);
				echo json_encode(['code' => 200 ]);
			}
		}
	}

	public function validateSubscription($subscription_id)
	{
		echo $this->makeRequest('PUT','/insurances/subscriptions/'.$subscription_id.'/validate', $_POST);
	}

	public function rejectSubscription($subscription_id)
	{
		echo $this->makeRequest('PUT','/insurances/subscriptions/'.$subscription_id.'/reject', $_POST);
	}


	public function storeDrugAndDevice(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$id = $_POST['id'] ?? null ;

				$exist = $this->db->get_where('nh_drugs_and_devices', ['id !=' => $id ,'network_id' => $_POST['network_id'] , 'code' => $_POST['code']]);
				if ($exist->num_rows() == 0) {
					if(!empty($id)){
						$this->db->where('id',$id);
						$this->db->update('nh_drugs_and_devices',$_POST);
					}else{
						$this->db->insert('nh_drugs_and_devices',$_POST);
					}
					echo json_encode(['code' => 200]);

				}else{
					echo json_encode(['code'=> 419 , 'message' => $this->lang->line("code_already_used")]);
				}
			}
		}
	}

	public function deleteDrugAndDevice(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$this->db->delete('nh_drugs_and_devices', ['id' => $_POST['id']]);
				echo json_encode(['code' => 200]);
			}
		}
	}

	public function resubmitHealthCareSheet(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$url = NANO_SANTE_SERVICE_URL.'/health-care-sheets';
				$ch = curl_init($url);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
				/* set the content type json */
				curl_setopt($ch, CURLOPT_HTTPHEADER, array(
					'Content-Type:application/json',
					'Authorization:'.NANO_SANTE_SERVICE_TOKEN,
					'X-localization:'. $this->session->userdata('site_lang') == 'french' ? 'fr' : 'en'
				));
				/* set return type json */
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$body = new \stdClass();
				$body->health_care_sheet_id = $this->input->post('health_care_sheet_id');
				$body->user_id = $this->input->post('user_id');
				$body->action = 'RESUBMIT';
				curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));

				/* execute request */
				$result = curl_exec($ch);
				/* close cURL resource */
				curl_close($ch);

				if ($result) {
					echo $result;
				} else {
					echo json_encode(['status' => 500]);
				}
			}
		}
	}

	public function getInsured()
	{
		if($this->isLogged()) {
			if (isset($_POST)) {
				$url = NANO_SANTE_SERVICE_URL.'/insured';
				$dataArray = [
					'network_id' => $this->input->post('network_id'),
				];
				$query = $this->input->post('query');
				$option = $this->input->post('option');
				$dataArray[$option ?? 'name'] = $query;

				$data = http_build_query($dataArray);
//				$getUrl = $url."?".$data;
				$ch = curl_init($url."?".$data);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
				/* set the content type json */
				curl_setopt($ch, CURLOPT_HTTPHEADER, array(
					'Content-Type:application/json',
					'Authorization:'.NANO_SANTE_SERVICE_TOKEN,
					'X-localization:'. $this->session->userdata('site_lang') == 'french' ? 'fr' : 'en'
				));
				/* set return type json */
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


				/* execute request */
				$result = curl_exec($ch);
				/* close cURL resource */
				curl_close($ch);

				if ($result) {
					echo $result;
				} else {
					echo json_encode(['status' => 500]);
				}
			}
		}
	}

	public function saveHealthCareSheet($type = 'consultation')
	{
		echo $this->makeRequest('POST','/health-care-sheets/'.$type, $_POST);
	}

	public function updateHealthCareSheet($id)
	{
		echo $this->makeRequest('PUT','/health-care-sheets/'.$id, $_POST);
	}

	public function calculateHealthCareSheetPerformancesAmount()
	{
		echo $this->makeRequest('POST','/health-care-sheets/performances-amount', $_POST);
	}

	public function getHealthCareSheets()
	{
		if($this->isLogged()) {
			if (isset($_POST)) {
				$url = NANO_SANTE_SERVICE_URL.'/health-care-sheets';

				$data = http_build_query($_POST);
//				$getUrl = $url."?".$data;
				$ch = curl_init($url."?".$data);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
				/* set the content type json */
				curl_setopt($ch, CURLOPT_HTTPHEADER, array(
					'Content-Type:application/json',
					'Authorization:'.NANO_SANTE_SERVICE_TOKEN,
					'X-localization:'. $this->session->userdata('site_lang') == 'french' ? 'fr' : 'en'
				));
				/* set return type json */
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

				/* execute request */
				$result = curl_exec($ch);
				/* close cURL resource */
				curl_close($ch);

				if ($result) {
					echo $result;
				} else {
					echo json_encode(['status' => 500]);
				}
			}
		}
	}

	public function getSingleHealthCareSheet($id)
	{
		echo $this->makeRequest('GET','/health-care-sheets/'.$id);
	}

	public function getActs()
	{
		echo $this->makeRequest('GET','/acts');
	}


	public function generateInvoice()
	{
		if($this->isLogged()) {
			if (isset($_POST)) {
				$url = NANO_SANTE_SERVICE_URL.'/generate-invoice';

				$data = http_build_query($_POST);
//				$getUrl = $url."?".$data;
				$ch = curl_init($url."?".$data);
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
				/* set the content type json */
				curl_setopt($ch, CURLOPT_HTTPHEADER, array(
					'Content-Type:application/json',
					'Authorization:'.NANO_SANTE_SERVICE_TOKEN,
					'X-localization:'. $this->session->userdata('site_lang') == 'french' ? 'fr' : 'en'
				));
				/* set return type json */
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

				/* execute request */
				$result = curl_exec($ch);
				/* close cURL resource */
				curl_close($ch);

				if ($result) {
					echo $result;
				} else {
					echo json_encode(['status' => 500]);
				}
			}
		}
	}

	public function treatCareRequest(){
		echo $this->makeRequest('PUT','/authorizations-care-requests', $_POST);
	}

	public function validateInvoice($id)
	{
		echo $this->makeRequest('PUT','/invoices/'.$id, $_POST);
	}

	private function makeRequest($method , $path , $request_body = []){
		if(!$this->isLogged()) {
			return json_encode(['status' => 401]);
		}
		$url = NANO_SANTE_SERVICE_URL.$path;
		if($method == 'GET'){
			$data = http_build_query($_POST);
			$ch = curl_init($url."?".$data);
		}else{
			$ch = curl_init($url);
		}
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
		/* set the content type json */
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
			'Content-Type:application/json',
			'Authorization:'.NANO_SANTE_SERVICE_TOKEN,
			'X-localization:'. $this->session->userdata('site_lang') == 'french' ? 'fr' : 'en'
		));
		/* set return type json */
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$body = new \stdClass();
		foreach ($request_body as $key => $value){
			$body->{$key} = $value;
		}
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));

		/* execute request */
		$result = curl_exec($ch);
		/* close cURL resource */
		curl_close($ch);

		if ($result) {
			return $result;
		}else{
			return json_encode(['status' => 500]);
		}
	}

	public function storeExclusions(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$id = $_POST['id'];

//				var_dump($_POST);
				if(!empty($id)){
					$this->db->where('id',$id);
					$this->db->update('nh_exclusions',$_POST);
				}else{
					$this->db->insert('nh_exclusions',$_POST);
				}

				echo json_encode(['status' => 200 ]);
			}
		}
	}

	private function isLogged()
	{
		if (!$this->session->userdata('email')) {
			$this->session->set_flashdata('error', 'log in first');

			$data['alert'] = "ok";
			$data['message'] = "Login first!";
			$this->load->view('login', $data);
			return false;
		}
		return true;
	}
}
