<?php 


function load_curl($url,$data)
{
	$CI = & get_instance();
	$CI->config->load('iugu');  

	$c_handle = curl_init();
	$headers = array('Authorization: '.$CI->config->item('auth'));
	curl_setopt($c_handle, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($c_handle, CURLOPT_URL, $url);
	curl_setopt($c_handle, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($c_handle, CURLOPT_POST, 1);
	curl_setopt($c_handle, CURLOPT_POSTFIELDS, http_build_query($data));
	$buffer = curl_exec($c_handle);
	if($buffer === false)
	{
	    return 'Curl error: ' . curl_error($c_handle);
	}
	else
	{
		return $buffer;
	}
	curl_close($c_handle);
}

function auto_logout($field)

{
	$CI = & get_instance();
    $t = time();
    $t0 = $CI->session->userdata($field);
    $diff = $t - $t0;
    //return array('t' => $t, '$t0'=>$t0,'diff'=>$diff);
    //return false;
    if(!empty($t0) && $diff >(60*10))
    {          
        return true;
    }
    else
    {
    	$CI->session->set_userdata($field, time());
    }
}

function encrypt_data($data){
	$CI = & get_instance();
	return $CI->encrypt->encode($data); 
}

function decrypt_data($data){
	$CI = & get_instance();
	return $CI->encrypt->decode($data); 
}


function load_language($lang_key,$echo=FALSE){

  $CI = & get_instance();

  $lang=$CI->session->userdata('language');
//print_r($lang);exit();
  if(empty($lang))

  	{$lang = 'pr';}
//print_r($lang);exit();
  $CI->config->load($lang);

  if($echo){

  	return $CI->config->item($lang_key);

  }else{

    echo $CI->config->item($lang_key);

  }



}	



function firebase(){

	//require base_url() . '/vendor/autoload.php';

	require "vendor/autoload.php";

	

	$DEFAULT_URL = 'https://ipok-178210.firebaseio.com'; 

	$DEFAULT_TOKEN = 'uPLqbrvbDnB8hB3N4QtqiH2eZaU3BOs4JTMbj8ih'; 

	$firebase = new \Firebase\FirebaseLib($DEFAULT_URL,$DEFAULT_TOKEN);

	return $firebase;

}





function set_upload_options($path, $type = 'jpg|png|jpeg|bmp') 

{

	//upload an image options

	$config = array();

	$config['upload_path']   = $path; 

	$config['allowed_types'] = $type; 

	$config['max_size']      = 0; 

	$config['max_width']     = 0; 

	$config['max_height']    = 0; 

	return $config;

}



function check_cep_viacep($cep)

{



	/*$curl_handle = curl_init();

	curl_setopt($curl_handle, CURLOPT_URL, 'https://viacep.com.br/ws/40301110/json/');

	curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);

	curl_setopt($curl_handle, CURLOPT_POST, 1);

	$buffer = curl_exec($curl_handle);

	curl_close($curl_handle);*/

		$arrContextOptions=array(

    "ssl"=>array(

        "verify_peer"=>false,

        "verify_peer_name"=>false,

    ),

    );  





	$path = 'https://viacep.com.br/ws/'.$cep.'/json/';

	$buffer = file_get_contents($path,false, stream_context_create($arrContextOptions));

	//$buffer = file_get_contents($path);

	//print_r($buffer);die();

	return $buffer;

}



function cpf_validator($cpf)

{

	$cpf = preg_replace('/[^0-9]/', '', (string) $cpf);

	// Validate size

	if (strlen($cpf) != 11)

		return false;

	// Calculates and checks first check digit

	for ($i = 0, $j = 10, $sum = 0; $i < 9; $i++, $j--)

		$sum += $cpf{$i} * $j;

	$result = $sum % 11;



	if ($cpf{9} != ($result < 2 ? 0 : 11 - $result))

		return false;

	// Calculates and checks second check digit

	for ($i = 0, $j = 11, $sum = 0; $i < 10; $i++, $j--)

		$sum += $cpf{$i} * $j;

	$result = $sum % 11;

	return $cpf{10} == ($result < 2 ? 0 : 11 - $result);

}



function change_time_to_local($dateTimeUTC = null, $dateFormat = 'H:i:s')

{

	if(strlen($dateTimeUTC)==13)

    { $dateTimeUTC = $dateTimeUTC /1000; }

	$date = new DateTime(date('Y-m-d h:i:s',$dateTimeUTC), new DateTimeZone('UTC'));

	$ip = $_SERVER['REMOTE_ADDR'];

	//print_r($ip);

	if($ip=='::1')

		{

			$date->setTimezone(new DateTimeZone('UTC'));

			echo $date->format('h:i A'); 

		}

		else

		{	

			$rs = json_decode(file_get_contents('http://ip-api.com/json/'.$ip));

			$time_Z = $rs->timezone;

			//print_r($time_Z);

			$date->setTimezone(new DateTimeZone($time_Z));

			echo $date->format('h:i A'); 

		}

}



function local_time_in_server($dateTimeUTC = null, $dateFormat = 'H:i:s')

{

	if(strlen($dateTimeUTC)==13)

    { $dateTimeUTC = $dateTimeUTC /1000; }

	$date = new DateTime(date('Y-m-d H:i:s',$dateTimeUTC), new DateTimeZone('UTC'));

	$ip = $_SERVER['REMOTE_ADDR'];

	if($ip=='::1')

		{

			$date->setTimezone(new DateTimeZone('UTC'));

			return $date->format('h:i A'); 

		}

		else

		{	

			$rs = json_decode(file_get_contents('http://ip-api.com/json/'.$ip));

			$time_Z = $rs->timezone;

			$date->setTimezone(new DateTimeZone($time_Z));

			return $date->format('h:i A'); 

		}

}



function send_mail($msg,$email,$sub)

{

	$CI = & get_instance();



 	$settings = $CI->db->get('settings')->row();

 	//print_r($msg);die();



    $configs = array(

		'protocol'=>'smtp',

		'smtp_host'=>$settings->smtp_host,

		'smtp_user'=>$settings->smtp_username,

		'smtp_pass'=>$settings->smtp_password,

		'smtp_port'=>'587',

		'smtp_timeout'=>20,

        'mailtype' => 'html',

        'charset' => 'iso-8859-1',

        'wordwrap' => TRUE

		); 



		$CI->load->library('email', $configs);

		$CI->email->initialize($configs);

		$CI->email->set_newline("\r\n");

		$CI->email

			->from($settings->admin_email, 'Ipok')

			->to($email)

			->subject($sub)

			->message($msg);

		$CI->email->send();

  }





  function get_clinic_list($doc_id)

  {

  	$CI = & get_instance();

  	$CI->db->select('tbl_clinic.id as clinic_id,

					tbl_clinic.name as clinic_name,

					tbl_clinic.profile_photo as clinic_pic');

	$CI->db->from('tbl_clinic');

	$CI->db->join('tbl_clinic_doctors', 'tbl_clinic_doctors.clinic_id = tbl_clinic.id','inner');

	$CI->db->where('tbl_clinic_doctors.doctor_id',$doc_id);

	$query = $CI->db->get();

	return $query->result_array();

  }



  function get_notification($id,$type)

  {

  	$CI = & get_instance();

  	if($type=="PATIENT")

  	{

  		$CI->db->select("id,

						type,

						CASE 

							WHEN type = '0' THEN 'New Booking'

							WHEN type = '1' THEN 'Waiting List'

							WHEN type = '2' THEN 'Consultation Reminder'

							WHEN type = '3' THEN 'Consulation Canceled'

						END as type_desc,

						message,

						read_status,

						time");

		$CI->db->from('tbl_patient_notification');

		$CI->db->where('patient_id',$id);

  	}

  	elseif($type=="DOCTOR")

  	{

  		$CI->db->select("id,

						type,

						CASE

							WHEN type = '0' THEN 'Redemption Made'

							WHEN type = '1' THEN 'New Review'

							WHEN type = '2' THEN 'New Consultation'

							WHEN type = '3' THEN 'Added to new clinic'

						END as type_desc,

						message,

						read_status,

						time");

		$CI->db->from('tbl_doctor_notifications');

		$CI->db->where('doctor_id',$id);

  	}

  	$CI->db->limit(10);

	$CI->db->order_by('time','DESC');

	$query = $CI->db->get();

	return $query->result_array();

  }



  function push_sent($fcm_data,$type) 

{

	$CI = & get_instance();

    //print_r($fcm_data);die();



    $data1 = "SELECT * FROM settings WHERE id = '0'";



    $query1 = $CI->db->query($data1);



    $rs = $query1->row();

    $key = $rs->api_key;

    //$key = 'AIzaSyCGDtxjM3gDFKNEvooXMQ9uGs8P5r7hYAE';



  /*  $data = "{ \"notification\": { \"title\": \"".$fcm_data['title']."\", \"text\": \"".$fcm_data['message']."\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"".$fcm_data['id']."\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_token."\"}";*/

/*  $data = "{ \"notification\": { \"title\": \"hi\", \"text\": \"hellonewmessage\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"12\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"c7yemODrWAY:APA91bFqfFVJsydZrtSjwhD_c_2uBcm_N3XZvbOyiaX4O1mlDtAVbEo2XyRsKpoQ3ypvOZkCnJ9qsA9tcGKeHutItKrU2LhBZbpfgCNM0ZFxw5An6biIhuh0HOW_yfsd90YbUzEhnj7Y\"}";*/



 //type 1 - Free Booking Confirmed

  if($type == '1') //push for patient

  {

		$data = "{ \"notification\": { \"title\": \"".$fcm_data['type']."\", \"text\": \"".$fcm_data['message']."\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"".$fcm_data['id']."\",\"type\" : \"".$fcm_data['type']."\",\"booking_id\" : \"".$fcm_data['booking_id']."\",\"booking_date\" : \"".$fcm_data['booking_date']."\",\"doctor_id\" : \"".$fcm_data['doctor_id']."\",\"doctor_name\" : \"".$fcm_data['doctor_name']."\",\"doctor_specialization\" : \"".$fcm_data['doctor_specialization']."\",\"message\" : \"".$fcm_data['message']."\",\"time\" : \"".$fcm_data['time']."\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_data['to']."\"}";

		

	}

	else if($type == '2') //push for doctor

	{

		$data = "{ \"notification\": { \"title\": \"".$fcm_data['type']."\", \"text\": \"".$fcm_data['message']."\" , \"sound\": \"default\" }, \"time_to_live\": 60, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"".$fcm_data['id']."\",\"type\" : \"".$fcm_data['type']."\",\"message\" : \"".$fcm_data['message']."\",\"read_status\" : \"".$fcm_data['read_status']."\"}}}, \"collapse_key\" : \"trip\", \"priority\":\"high\", \"to\" : \"".$fcm_data['to']."\"}";

	}

	



    $ch = curl_init("https://fcm.googleapis.com/fcm/send"); 

    $header = array('Content-Type: application/json', 'Authorization: key='.$key);



    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);



    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);



    curl_setopt($ch, CURLOPT_POST, 1);



    //curl_setopt($ch, CURLOPT_POSTFIELDS, "{ \"notification\": { \"title\": \"olakka title\", \"text\": \"Olakka message\" }, \"data\" : {\"response\" : {\"status\" : \"success\", \"data\" : {\"id\" : \"$request[id]\"}}} \"to\" : \"cAAoKqSKvgk:APA91bH-mvqwAp1JYW1oBZl_aheVDb7HOWx0YjXU6Wmmm-G_CB-60T2M6WKwsjPDMUfu47nCf1qi4a9SREiwRifAFBWszVTL8XA1y4_nb7ZiI9EmX7rpKsWogsrzqXSwKt56cd8sH5ox\"}");



    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);



    // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);



    // curl_close($ch);



    $out = curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $result = curl_exec($ch);

    curl_close($ch);

    return $result;





}

//print(cpf_validator('111.444.777-35'));// return 1 if valid else no return



?>