<?php
	//MWENEWEZI CHANIKA FRAMEWORK
	/**
	 * 
	 */
	class DIR_MAKER
	{
		function dir_make($dir_path)
		{
			if(!file_exists($dir_path)){
				if(mkdir($dir_path,0777,true) and chmod($dir_path, 0777)){
					return 1;
				}else{
					return 0;
				}
			}
		}
	}
	class LOG
	{
		//define function name  
		function create_log($arMsg,$log_path_loc)  
		{  
			$dir_makeObj=new DIR_MAKER();
			$dir_makeObj->dir_make($log_path_loc);
			//define empty string                                 
			$stEntry="";  
			//get the event occur date time,when it will happened  
			$arLogData['event_datetime']='['.date('D Y-m-d h:i:s A').'] [client '.$_SERVER['REMOTE_ADDR'].']';  
			//if message is array type  
			if(is_array($arMsg))  {  
				//concatenate msg with datetime  
				foreach($arMsg as $msg)  
				$stEntry.=$arLogData['event_datetime']." ".$msg."rn";  
			}else{   //concatenate msg with datetime  
				
				$stEntry.=$arLogData['event_datetime']." ".$arMsg."rn";  
			}  
			//create file with current date name  
			$stCurLogFileName='log_'.date('Ymd').'.txt';  
			//open the file append mode,dats the log file will create day wise  
			$fHandler=fopen($log_path_loc.$stCurLogFileName,'a+');  
			//write the info into the file  
			fwrite($fHandler,$stEntry);  
			//close handler  
			fclose($fHandler);  
		}
	}
	/**
	 * Database connection
	 */
	class DB
	{
			
		//connection to the database
		function database()
		{	
			$log_path="../../logs/error_logs/";
			$dir_makeObj=new DIR_MAKER();
			//log Object
			$logObj=new LOG();
			try{
				$db=new PDO("mysql:host=localhost;dbname=provama","root","");
				$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_OBJ);
				$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

				return $db;
			}catch(Exception $e){
				$dir_makeObj->dir_make($log_path);
				$logObj->create_log($e,$log_path);
				die("error");
			}
				
		}
	}

	/**
	 * Insert data to table
	 */
	class INSERT
	{
		function inserter($table,$fields,$data)
		{
			/*Usage guide Example
				$field=array("fname","sname");
				$dat=array("mwenewezi","chanika");
				$test=new INSERT;
				$test=$test->inserter("users",$field,$dat);*/

			//variable
			$fields_data="";
			$data_holder="";
			$exec_variable=array();

			//database connector object
			$db=new DB;
			$db=$db->database();
			
			for ($i=0; $i < count($fields); $i++) { 
				//set fields data
				if(empty($fields_data)){
					$fields_data=$fields[$i];
				}else{
					$fields_data=$fields_data.",".$fields[$i];
				}
				//set data holder
				if(empty($data_holder)){
					$data_holder=":".$fields[$i];
				}else{
					$data_holder=$data_holder.",:".$fields[$i];
				}
				//set execution data
				$exec_variable[$fields[$i]]=$data[$i];
			}
			//insert data
			$db->query("SET FOREIGN_KEY_CHECKS=0");
			$query1="INSERT INTO $table($fields_data)VALUES($data_holder)";

			//echo $query1;
			$stmt=$db->prepare($query1);

			$ret="";
			try{
				if($stmt->execute($exec_variable)){
					$ret=1;
				}
			}catch(PDOException $e){
				//echo $e;
				if ($e->getCode() == 23000) {
			        $ret="entry_exists";
			    } else {
			    	//echo $e;
			        $ret=0;
			    }
			}
			$db->query("SET FOREIGN_KEY_CHECKS=1");
			return $ret;
			}
	}


	/**
	 * check numrows
	 */
	class ROWCOUNT{
		function rowcounter($table,$data,$where,$whereValues){

			//database connector object
			$db=new DB;
			$db=$db->database();
			
			//insert data
			$query="SELECT $data FROM $table WHERE $where='$whereValues'";
			//echo $query;
			if($query=$db->query($query)){
				$ret=$query->rowCount();
			}else{
				$ret=0;
				//print_r($error);
			}
			return $ret;
			}
		
	}
	/**
	 * check numrows
	 */
	class ALLROWCOUNT{
		function allrowcounter($table,$data){

			//database connector object
			$db=new DB;
			$db=$db->database();
			
			//insert data
			$query="SELECT $data FROM $table";
			//echo $query;

			if($query=$db->query($query)){
				$ret=$query->rowCount();
			}else{
				$ret=0;
				//print_r($error);
			}
			return $ret;
			}
		
	}

	/**
	 * Retrieve Data
	 */
	class RETRIEVE
	{
		function retriever()
		{
			/*Usage guide example
			$fe=new RETRIEVE;
			$fe=$fe->retriever("users","*");*/

			$args="";
			$query="";
			if(func_get_args()){
				$args=func_get_args();
			}
			
			//database connector object
			$db=new DB;
			$db=$db->database();

			//var
			$fetch_type="";

			//overloading
			if (func_num_args()==3) { //($table,$data,$db)     SELECT data FROM TABLE
		        $table=$args[0];
		        $data=$args[1];
		        $fetch_type=$args[2];

		        $query="SELECT $data FROM $table";
		    }else if(func_num_args()==5){ //($table,$data,$where,$whereValues)     SELECT WITH WHERE 
		    	$table=$args[0];
		        $data=$args[1];
		        $where=$args[2];
		        $whereValues=$args[3];
		        $fetch_type=$args[4];

		        $query="SELECT $data FROM $table WHERE $where = '$whereValues'";
		    }else if(func_num_args()==6){ //($table,$data,$where,$whereValues,$db)     SELECT WITH WHERE 
		    	$table=$args[0];
		        $data=$args[1];
		        $where=$args[2];
		        $whereValues=$args[3];
		        $orderBy=$args[4];
		        $fetch_type=$args[5];

		        $query="SELECT $data FROM $table WHERE $where = '$whereValues' ORDER BY $orderBy";
		    }else if(func_num_args()==7){ //($table,$data,$where,$whereValues,$db)     SELECT WITH WHERE 
		    	$table=$args[0];
		        $data=$args[1];
		        $where=$args[2];
		        $whereValues=$args[3];
		        $orderBy=$args[4];
		        $order=$args[5];
		        $fetch_type=$args[6];

		        $query="SELECT $data FROM $table WHERE $where = '$whereValues' ORDER BY $orderBy $order";
		    }
		   
		    //echo $query;
		    $row="";
		    if($fetch_type=="fetch"){
		    	$sql=$db->prepare($query);
		    	$sql->execute();
				$rows=$sql->fetch();
		    }else if($fetch_type=="fetchAll"){
		    	$sql=$db->prepare($query);
		    	$sql->execute();
				$rows=$sql->fetchAll();
		    }else{
		    	echo "<p class='alert alert-danger'>Fetch type error </p>";
		    }
			

			if($rows){
				return $rows;
			}else if($sql->fetchColumn()==0){
				return $ret=1020;
			}else{
				return $ret=0;
			}
		}
	}

	


	/**
	 * update Data
	 */
	class UPDATE
	{
		function updater($table,$data,$where,$whereValues){
			//database connector object
			$db=new DB;
			$db=$db->database();

			//update
			$query="UPDATE $table SET $data WHERE $where='$whereValues'";
			$sql=$db->prepare($query);
			
			$error=$sql->errorInfo();

			//echo $query."<br>";

			$ret="";
			try{
				if($sql->execute()){
					$ret=1;
				}
			}catch(PDOException $e){
				if ($e->getCode() == 23000) {
			        $ret="entry_exists";
			    } else {
			        $ret=0;
			    }
			}
			return $ret;
		}
	}

	/**
	 * update Data
	 */
	class DATA_TABLE_RETRIEVE
	{	
		//DATA TABLE DISPLAY
		function data_table_display()
		////getTable =Array //orderBy=String //orderByType=String //getCount=Int //getPage=Int
		{
			/*USAGE GUIDE
				$field=array("fname","sname");
				$retrieve=new DATA_TABLE_RETRIEVE;
				$retrieve=$retrieve->data_table_display("users","fname","ASC",3,2);
				echo "<pre>";
				print_r($retrieve);*/

			//database connector object
			$db=new DB;
			$db=$db->database();

			//variables
			$query="";
			$get_num_rows=0;
			$count=0;
			$page=1;
			$Table="";

			$getTable="";
			$orderBy="";
			$orderByType="";
			$getCount=0;
			$getPage=0;
			$output="";

			if(func_get_args()){
				$args=func_get_args();
			}

			if (func_num_args()==6) {  //FETCH
		        $table=$args[0]; 
		        $orderBy=$args[1];
				$orderByType=$args[2];
				$getCount=$args[3];
				$getPage=$args[4];
				$output=$args[5];
		       	
		       	//set count
				if(!empty($getCount)){
					$count=$getCount;
				}else{
					$count=5;
				}
				//set page
				if(!empty($getPage)){
					$page=$getPage;
				}else{
					$page=0;
				}
				//set get table from array
				$Table=$table;

				//implementation
				/*if($page!=0){
					$page=$page*$count;
				}*/
				//page counter
				if($page!=0){
					$page=(1*$page*$getCount)-$getCount;
				}
				
				if(!empty($orderBy)){
					if(empty($orderByType) or $orderByType=="ASC"){
						$query="SELECT * FROM $Table ORDER BY $orderBy ASC LIMIT $page,$count";
					}else if($orderByType=="DESC"){
						$query="SELECT * FROM $Table ORDER BY $orderBy DESC LIMIT $page,$count";
					}
				}else{
					$query="SELECT * FROM $Table LIMIT $page,$count";
				}
				$get_num_rows="SELECT * FROM $table";
		    }
		    else if(func_num_args()==3) {  //SEARCH
		    	$table=$args[0]; 
		       	$where=$args[1];
				$output=$args[2]; //fetch
		       	
				//set get table from array
				$Table=$table;
				
				$query="SELECT * FROM $Table WHERE $where";
				$get_num_rows="SELECT * FROM $table";
		    }

		    //echo $query;
			$sql=$db->query($query);
			$rows=$sql->fetchAll();

			//get num rows
			$get_num_rows=$db->query($get_num_rows);
			$get_num_rows=$get_num_rows->rowCount();

			if($rows and $get_num_rows){
				if($output=="data"){
					return $rows;
				}else if($output=="count"){
					return $get_num_rows;
				}
			}else if($sql->fetchColumn()==0){
				return $ret=1020;
			}else{
				return $ret=0;
			}
		}

		

		//DATA TABLE SEARCH
		function data_table_search($getSearchValue,$getFields,$getTable,$orderBy,$orderByType)
		//$getSearchValue=String //$getFields=Array //getTable =String //orderBy=String
		{
			/*Usage GUILDE
				$field=array("fname","sname");
				$search=new DATA_TABLE_RETRIEVE;
				$search=$search->data_table_search("mw",$field,"users","fname","DESC");
				echo "<pre>";
				print_r($search);*/
			//database connector object
			$db=new DB;
			$db=$db->database();

			//search
			if(!empty($getSearchValue)){
				$query="";
				$SearchValue="";
				foreach ($getFields as $key) {
					if(empty($SearchValue)){
						$SearchValue=$key." LIKE '%$getSearchValue%'";
					}else{
						$SearchValue=$SearchValue." OR ".$key." LIKE '%$getSearchValue%'";
					}
				}
				if(!empty($orderBy)){
					if(empty($orderByType) or $orderByType=="ASC"){
						$query="SELECT * FROM $getTable WHERE $SearchValue ORDER BY $orderBy ASC";
					}else if($orderByType=="DESC"){
						$query="SELECT * FROM $getTable WHERE $SearchValue ORDER BY $orderBy DESC";
					}
				}else{
					$query="SELECT * FROM $getTable WHERE $SearchValue";
				}
					
				//echo $query."<br />";
				$sql=$db->query($query);
				$rows=$sql->fetchAll();

				if($rows){
					return $rows;
				}else if($sql->fetchColumn()==0){
					return $ret=1020;
				}else{
					return $ret=0;
				}
			}
		}
	}	
	/**
	 * update Data
	 */
	class DELETE
	{
		function deleter($table,$where,$data){ //DELETE SPECIFIC COLUMN
			//database connector object
			$db=new DB;
			$db=$db->database();

			//delete
			$query="DELETE FROM $table WHERE $where = '$data'";
			$sql=$db->prepare($query);
			
			$error=$sql->errorInfo();
			
			if($sql->execute()){
				$ret=1;
			}else{
				$ret=0;
				//$error=$sql->errorInfo();
				//print_r($error);
			}
			return $ret;
		}
	}

	/**
	 * update Data
	 */
	class SEARCH
	{
		//DONT US THIS.....................
		function searcher($getTable,$SearchValue){ //SEARCH
			//database connector object
			$db=new DB;
			$db=$db->database();

			//search
			foreach ($getFields as $key) {
				if(empty($SearchValue)){
					$SearchValue=$key." LIKE '%$getSearchValue%'";
				}else{
					$SearchValue=$SearchValue." OR ".$key." LIKE '%$getSearchValue%'";
				}
			}

			$query="SELECT * FROM $getTable WHERE $SearchValue";
			$sql=$db->query($query);
			
			if($sql){
				$ret=1;
			}else{
				$ret=0;
			}
			return $ret;
		}
	}

	class TIMEAGO{
		function time_elapsed_string($datetime, $full = false) {
			$now = new DateTime;
			$ago = new DateTime($datetime);
			$diff = $now->diff($ago);

			$diff->w = floor($diff->d / 7);
			$diff->d -= $diff->w * 7;

			$string = array(
			    'y' => 'year',
			    'm' => 'month',
			    'w' => 'week',
			    'd' => 'day',
			    'h' => 'hour',
			    'i' => 'minute',
			    's' => 'second',
			);
			foreach ($string as $k => &$v) {
			    if ($diff->$k) {
			        $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
			    } else {
			        unset($string[$k]);
			    }
			}

			if (!$full) $string = array_slice($string, 0, 1);
			return $string ? implode(', ', $string) . ' ago' : 'just now';
			}
	}

	class IP{
		function getUserIpAddr(){
		    $ipaddress = '';
		    if (isset($_SERVER['HTTP_CLIENT_IP']))
		        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
		    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
		        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
		    else if(isset($_SERVER['HTTP_X_FORWARDED']))
		        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
		    else if(isset($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
		        $ipaddress = $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
		    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
		        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
		    else if(isset($_SERVER['HTTP_FORWARDED']))
		        $ipaddress = $_SERVER['HTTP_FORWARDED'];
		    else if(isset($_SERVER['REMOTE_ADDR']))
		        $ipaddress = $_SERVER['REMOTE_ADDR'];
		    else
		        $ipaddress = 'UNKNOWN';
		    return $ipaddress;
		}
		function getUserLocationFromIpAddr($ip){
			try {
				$geoPlugin_array = unserialize(file_get_contents('http://www.geoplugin.net/php.gp?ip=' . $ip) );
		    	return $geoPlugin_array;
			} catch (Exception $e) {
				return $e;
			}
			
			
		}
	}

	/**
	 * 
	 */
	class SQL_MATHS
	{
		
		function sum($table,$data)
		{
			//database connector object
			$db=new DB;
			$db=$db->database();
			
			//insert data
			$query="SELECT SUM($data) as sum FROM $table";
			//echo $query;
			$ret="";
			if($query=$db->query($query)){
				$ret=$query;
			}else{
				$ret=0;
				//print_r($error);
			}
			return $ret;
			
		}
	}

	/**
	 * 
	 */
	class SEND_EMAIL
	{
		function phpmailer_send($mailer_r_path,$subject_,$body_,$email_to){
			require_once($mailer_r_path."lib/PHPMailer/src/PHPMailer.php");
			require_once($mailer_r_path."lib/PHPMailer/src/SMTP.php");
			require_once($mailer_r_path."lib/PHPMailer/src/Exception.php");

			/*$mailer_name="BS Jobs";
			$mailer_email="support@brightersetting.com";
			$mailer_password="";
			$mailer_website="brightersetting.com";
			$mail_host="mail.brightersetting.com";

			$mail = new PHPMailer\PHPMailer\PHPMailer();
		    $mail->IsSMTP(); // enable SMTP
		    $mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
		    $mail->SMTPAuth = true; // authentication enabled
		    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
		    $mail->Host = $mail_host;
		    $mail->Port = 465; // or 587
		    $mail->IsHTML(true);
		    $mail->Username = $mailer_email;
		    $mail->Password = $mailer_password;
		    $mail->setFrom($mailer_email,$mailer_name);
		    $mail->Subject = $subject_;
		    $mail->Body = $body_;
		    $mail->addAddress($email_to);*/

		    $mailer_name="PROVAMA";
			$mailer_email="bsettingtest@gmail.com";
			$mailer_password="bsettingtest@!!!";
			$mailer_website="www.provama.com";
			

			$mail = new PHPMailer\PHPMailer\PHPMailer();
		    $mail->IsSMTP(); // enable SMTP
		    $mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
		    $mail->SMTPAuth = true; // authentication enabled
		    $mail->SMTPSecure = 'tls'; // secure transfer enabled REQUIRED for Gmail
		    $mail->Host = "smtp.gmail.com";
		    $mail->Port = 587; // or 587
		    $mail->IsHTML(true);
		    $mail->Username = $mailer_email;
		    $mail->Password = $mailer_password;
		    $mail->setFrom($mailer_email,$mailer_name);
		    $mail->Subject = $subject_;
		    $mail->Body = $body_;
		    $mail->addAddress($email_to);

			if(!$mail->Send()){
				//echo "<p class='alert alert-warning'>Mailer Error: " . $mail->ErrorInfo ."</p>";
				return 0;
			}else{
				return 1;
			}
		}
		
	}
	//GET ROOT DIRECTORY
	class ROOTDIRGET{
		function root_dir_getter(){
		  $url=sprintf(
		    "%s://%s%s",
		    isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http',
		    $_SERVER['SERVER_NAME'],
		    $_SERVER['REQUEST_URI']
		  );
		  $modifyUrl = parse_url($url);
		  $root_dir=$modifyUrl["scheme"]."://".$modifyUrl["host"];
		  return $root_dir;
		}
	}
?>