<?php
    
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    
	class Functions {
	    
		// Paginaiton function 
		public function pagination_config($url,$count,$perpage) {
			$config = array();
			$config["base_url"] = $url;
			$config['reuse_query_string'] = true;
			$config["total_rows"] = $count;
			$config["per_page"] = $perpage;
			$config['full_tag_open'] = '<ul class="pagination pagination-split">';
			$config['full_tag_close'] = '</ul>';
			$config['prev_link'] = '<i class="fa fa-angle-left" aria-hidden="true"></i>';
			$config['prev_tag_open'] = '<li>';
			$config['prev_tag_close'] = '</li>';
			$config['next_link'] = '<i class="fa fa-angle-right" aria-hidden="true"></i>';
			$config['next_tag_open'] = '<li>';
			$config['next_tag_close'] = '</li>';
			$config['cur_tag_open'] = '<li class="active"><a href="#">';
			$config['cur_tag_close'] = '</a></li>';
			$config['num_tag_open'] = '<li>';
			$config['num_tag_close'] = '</li>';
			$config['first_tag_open'] = '<li>';
			$config['first_tag_close'] = '</li>';
			$config['last_tag_open'] = '<li>';
			$config['last_tag_close'] = '</li>';

			$config['first_link'] = '<i class="fa fa-angle-double-left" aria-hidden="true"></i>';
			$config['last_link'] = '<i class="fa fa-angle-double-right" aria-hidden="true"></i>';
			return $config;
		}
		
		public function send_email ( $to, $temp_id, $search_arr = array (), $subject=false, $reply_to=false ) {
            $CI = get_instance();
			$CI->db->from ( 'email_templates' )->where ( 'id', $temp_id );
			$et = $CI->db->get ()->row_array ();
			
			if( empty( $et ) ) {
				return false;
			}
			$aes = $CI->config->item ( 'admin_email_settings' );
			
			$search_arr = $search_arr + array ( '{sign}' => $aes['admin_sign'] );
			$message = str_replace (
				array_keys ( $search_arr ),
	  			array_values ( $search_arr ),
				$et['template']
			);
			
			$message = '<div style="border-top:5px solid #eefaff;min-height:150px;background-color:#eefaff;padding:20px; font-family:arial; font-size:18px; line-height:18px;">' . $message . '</div>';
			
			require_once APPPATH.'third_party/phpmailer/src/Exception.php';
    	    require_once APPPATH.'third_party/phpmailer/src/PHPMailer.php';
    	    require_once APPPATH.'third_party/phpmailer/src/SMTP.php';
    	    
    	    $email = new PHPMailer(true);
    	    $email->isSMTP();
            $email->Host     = 'smtp.gmail.com';
            $email->SMTPAuth = true;
            $email->Username = $aes['gmail_username'];
            $email->Password = $aes['gmail_password'];
            $email->SMTPSecure = 'ssl';
            $email->Port     = 465;
            $email->CharSet = "UTF-8";
            $email->Encoding = "base64"; 
			$email->setFrom( $aes['admin_email'], $aes['admin_name'] );
			
			if ( ! empty ( $subject ) ) {
			    $email->Subject = $subject;
			} else {
			    $email->Subject = $et['subject'];
			}
			
			if ( ! empty ( $reply_to ) ) {
			    $email->addReplyTo( $reply_to );
			    $email->addCC( $reply_to );
			}
			
            $tos = explode( ",", $to );
            if ( ! empty ( $tos ) ) {
                foreach ( $tos as $to ) {
                    $email->addAddress($to);
                }
            }
            $email->isHTML(true);
            $email->Body = $message;
		
			try {
			    if ( $email->send() ) {
			        return true;
			    }
			} catch (Exception $e) {
				//echo 'Caught exception: '. $e->getMessage();
			}
			return false;
		}
		
        public function send_email_sendgrid ( $to, $temp_id, $search_arr = array () ) {
            $CI = get_instance();
			$CI->db->from ( 'email_templates' )->where ( 'id', $temp_id );
			$et = $CI->db->get ()->row_array ();
			
			if( empty( $et ) ) {
				return false;
			}
			$aes = $CI->config->item ( 'admin_email_settings' );
			
			$search_arr = $search_arr + array ( '{sign}' => $aes['admin_sign'] );
			$message = str_replace (
				array_keys ( $search_arr ),
	  			array_values ( $search_arr ),
				$et['template']
			);
			
			$message = '
				<div style="width:68%;float:left;margin:10px auto; padding:20px;">
					' . $message . '
				</div>
			';
			
			$message = '<div style="border-top:5px solid #eefaff;min-height:150px;background-color:#eefaff;padding:20px; font-family:arial; font-size:18px; line-height:18px;">' . $message . '</div>';
			
			require_once APPPATH . 'third_party/sendgrid/vendor/autoload.php';	

			$email = new \SendGrid\Mail\Mail();
			$email->setFrom( $aes['admin_email'], $aes['admin_name'] );
			$email->setSubject( $et['subject'] );

			$email->addTo( $to );
			
			$email->addContent( "text/html", $message );
		
			$sendgrid = new \SendGrid( SENDGRID_API_KEY );
			try {
				$response = $sendgrid->send( $email );
				$status = $response->statusCode();

				if ( $status == '202' ) {
					return true;
				}
			} catch (Exception $e) {
				//echo 'Caught exception: '. $e->getMessage();
			}
			return false;
		}


		function push_insert_notification ( $data ) {
		    if ( ! empty ( $data ) ) {
		        $CI = get_instance();
    		    $data['created_on']	= date ( 'Y-m-d H:i:s' );
    		    //if( ! isset($data['is_hidden']) && ( $data['is_hidden'] != 1 ) ) {
    			    $CI->db->insert ( 'notification', $data );
    			    $data['notification_id'] = $CI->db->insert_id ();
    		    //}
    		    
    		    if( isset ( $data['sender_user_id'] ) && ( $data['sender_user_id'] > 0 ) ) {
		            $CI->db->select ( 'name, photo' )->from ( 'users' )->where ( array ( 'id' => $data['sender_user_id'] ) )->limit ( 1 );
        			$query = $CI->db->get ();
        			if ( $query->num_rows() > 0 ) {
        				$row = $query->row_array ();
        				$data['sender_name']    = $row['name'];
        				$data['sender_image']   = $row['photo'];
        			}
		        }
    		    
		        $data['table']  = 'caregiver';
		        $this->send_notification( $data );
    			
		    }
		}

		public function send_notification ( $data ) {
    		if ( ! empty ( $data ) ) {
    		    $CI = get_instance();
    		    $table = 'patient';
    		    if ( isset ( $data['table'] ) && ! empty ( $data['table'] ) ) {
    		        $table = $data['table'];
    		    }
    			$CI->db->select ( 'device_token, device_type' )->from ( $table )->where ( array ( 'id' => $data['user_id'] ) )->limit ( 1 );
    			$query = $CI->db->get ();
    			if ( $query->num_rows() > 0 ) {
        			$row = $query->row_array ();
					if ( ! empty ( $row['device_token'] ) ) { 
						$url = 'https://fcm.googleapis.com/fcm/send';
						
						$fields = array (
							'to'			=> $row['device_token'],
							'notification' 	=> array (
								"title"	 	=> $data['title'],
								"body" 		=> ((isset($data['body']))?$data['body']:''),
								"type"		=> $data['type'],
								"sound"		=> 'default'
							),
							'data' => array (
								"title" 	=> $data['title'],
								"body" 		=> ((isset($data['body']))?$data['body']:''),
								"type"		=> $data['type']
							),
							"content_available"	=> true
						);
						
						if( $row['device_type'] != 'iOS' ) {
							unset($fields['notification']);
						} else if( ( $row['device_type'] == 'iOS' ) && ( isset ( $data['is_hidden'] ) && ( $data['is_hidden'] == 1 ) ) ) {
							unset($fields['notification']);
						}
    					if( isset ( $data['sender_user_id'] ) && ( $data['sender_user_id'] > 0 ) ) {
    					    $fields['data']['sender_user_id'] = $data['sender_user_id'];
    					}
    					if( isset ( $data['sender_image'] ) && ! empty ( $data['sender_image'] ) ) {
    					    $fields['data']['sender_image'] = $data['sender_image'];
    					}
    					if( isset ( $data['sender_name'] ) && ! empty ( $data['sender_name'] ) ) {
    					    $fields['data']['sender_name'] = $data['sender_name'];
    					}
						
						//echo "<pre>"; print_r($fields); echo "</pre>"; die;
						$headers = array (
							'Authorization: key=AAAAwzz_vmg:APA91bHSL73q3HPvHR_RAI3zxob6fyFJpI2brqoRG3-GYKLWPJzahSNAeenubXpq1E7uOc4Y2alYvN5OTzW9AhtDjvIgy6Q4PG8Bp1DN3fekv021vBcHbd1hIKeu8qtOLdww32RIbwPQ',
							'Content-Type: application/json'
						);
						
						$ch = curl_init ();
						curl_setopt ( $ch, CURLOPT_URL, $url );
						curl_setopt ( $ch, CURLOPT_POST, true );
						curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
						curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
						curl_setopt ( $ch, CURLOPT_POSTFIELDS, json_encode ( $fields ) );

						$result = curl_exec ( $ch );
						//echo "<pre>"; print_r($result); echo "</pre>"; die;
						curl_close ( $ch );
						
						return true;
					}
    					
    				
    			}
    		}
    		
    		return false;
    	}
    	
    	function get_subscription ( $user_id ) {
    	    $CI = get_instance();
			$CI->db->select ( '*' )->from ( 'user_subscription' )->where ( array ( 'user_id' => $user_id ) )->limit ( 1 );
			$query = $CI->db->get ();
		
			if ( $query->num_rows() > 0 ) {
				$row = $query->row_array ();
				return $row;
			}
		}
		
		function update_subscription ( $data ) {
		    $CI = get_instance();
			$CI->db->where ( 'user_id', $data['user_id'] );
			$CI->db->update ( 'user_subscription', $data );
		}
		
		function add_subscription ( $data ) {
			
			if ( ! empty ( $data ) ) {
			    $CI = get_instance();
			    $data['created_on']	    = date ( 'Y-m-d H:i:s' );
				$CI->db->insert ( 'user_subscription_log', $data );
				
				if ( isset ( $data['data'] ) ) {
				    unset( $data['data'] );
				}
				
				$user_id                = $data['user_id'];
				$subscription           = $this->get_subscription ( $user_id );
				if ( ! empty ( $subscription ) ) {
				    unset($data['created_on']);
				    $CI->db->where ( 'user_id', $user_id );
					$CI->db->update ( 'user_subscription', $data );
				} else {
					$CI->db->insert ( 'user_subscription', $data );
				}
				
				// Send email to user
				$user = $CI->user_model->get_user ( $user_id );
				
				if ( ! empty ( $user ) ) {
					$search_arr			= array(
						'{name}'		=> $user['name'].' '.$user['surname'],
						'{package}'		=> $data['package_name']
					);
					$temp_id	        = 4;
					
					$this->send_email ( $user['email'], $temp_id, $search_arr );
					
				}
				
			}
		}
		
		function insert_transaction ( $data ) {
		    if ( ! empty ( $data ) ) {
		        $CI = get_instance();
		        $data['created_on']	    = date ( 'Y-m-d H:i:s' );
			    $CI->db->insert ( 'transactions', $data );
			    return $CI->db->insert_id ();
		    }
		}
		
		function delete_subscription ( $user_id ) {
		    if ( $user_id > 0 ) {
		        $CI = get_instance();
		        $CI->db->where ( 'user_id', $user_id );
				$CI->db->delete ( 'user_subscription' );
		    }
		}
		
	}
	
?>