<?php   
class DB_Functions{       
private $db;
function __construct() {         
include_once './db_connect.php'; 
$this->db = new DB_Connect();         
$this->db->connect();     
}       
function __destruct() {
}  

function escape( $x ) {
return "'" . mysql_real_escape_string($x) . "'";
}
//////////get main url to reach the server folder////////////////
public function getAttachmentUrl() {
	$url = "http://test.cansale.in/cansaledms/API/";
	return $url;
}
 //////////Attendance view////////////////

public function getEng_attendance ($user_id, $from_date, $to_date) {
$result = mysql_query ("select * from user_attendence where user_id='$user_id' and date (in_datetime) >='$from_date' and date (out_datetime)<='$to_date'") or die(mysql_error());
    return $result;
}

 /////////////// City Master /////////////////////
 public function getStateMaster() {         
 $result = mysql_query("SELECT * FROM state_master order by state")or die(mysql_error());         
 return $result;     
 } 
 
 public function getCityMaster($state){
 $result = mysql_query("SELECT * FROM district_master  where status='A' and state='".$state."' order by city")or die(mysql_error());         
 return $result;
 }
 
 public function getUserMaster(){
 $result=mysql_query("select * from admin_users where status='active'");
 return $result;
 }
 public function getLocationDetail($loc_code){
 $result=mysql_query("select * from asc_master where asc_code='".$loc_code."'");
 return $result;
 }
 
 public function getIMEIDetails($ei) {
	$b=array();      
	//echo "SELECT * FROM billing_imei_data where imei='$ei' or imei2='$ei' order by id desc";
 $result = mysql_query("SELECT * FROM billing_imei_data where imei1='$ei' or imei2='$ei' order by id desc") or die(mysql_error());         
return $result;

 } 
 
 public function getUserDetails($ei){
	 //echo "select * from admin_users where username='$ei' or owner_code='$ei' and password='$password' and status='active'";
	 $result=mysql_query("select * from admin_users where username='$ei'")  or die(mysql_error()); 
	 return $result;
 }
 
 public  function getSaleData(){
	 $result=mysql_query("select * from sale_data order by id");
	 return $result;
	 
 }
 public  function getUserType($typeid){
	 $result=mysql_query("select * from usertype_master where refid='$typeid'");
	 return $result;
	 
 }
 public function getOffers(){
	 $result=mysql_query("select * from scheme_master where status='Active' AND from_date <= '".date("Y-m-d")."' AND to_date >= '".date("Y-m-d")."'");
	 return $result; 
 }
 
 public function getSaleData_User($ei){
	 $result=mysql_query("select * from sale_data where user_name='$ei'");
	 return $result;
	 
 }
 
 /*public function Retailer_list($ei){
	$result=mysql_query("SELECT * FROM my_retailer where create_by='".$ei."' and approval_status='Approved'"); 
	return $result;	 
 }*/
 ///// written on 17 april 2019 by shekhar
 public function Retailer_list($ei){
	$result=mysql_query("SELECT a.name,a.city,a.state,a.asc_code FROM asc_master a ,access_location b where b.uid='".$ei."' and b.status='Y' and a.asc_code = b.location_id and a.status='active' and a.user_level='6' order by a.name"); 
	return $result;	 
 }
 public function mappedLocation($ei){
	$result=mysql_query("SELECT * FROM access_location where uid='".$ei."' and status='Y'"); 
	return $result;	 
 }
 public function salesOrderList($ei){
	$result=mysql_query("SELECT * FROM purchase_order_master where create_by='".$ei."'"); 
	return $result;	 
 }
 public function TaDaList($ei){
	$result = mysql_query("SELECT * FROM ta_da where userid='".$ei."'"); 
	return $result;	 
 }
 ///// get product category
	public function stockList($retailerCode,$productCode){
		if($productCode){ $condition = " and partcode='".$productCode."'";}else{ $condition = "";}
		$result = mysql_query("SELECT * FROM stock_status where asc_code = '".$retailerCode."' ".$condition."")or die(mysql_error());         
		return $result;
	}
 ////// get purchase order item details
	public function salesOrderItems($order_no){
		return $result = mysql_query("SELECT * FROM purchase_order_data where po_no='".$order_no."'");
	}
	public function TaDaItems($ref_no){
		return $result = mysql_query("SELECT * FROM ta_da where system_ref_no='".$ref_no."'");
	}
 public function productList(){
	$result=mysql_query("SELECT * FROM product_master where status='active'"); 
	return $result;	 
 }
 public function productDetail($prodcode){
	$result=mysql_query("SELECT * FROM product_master where productcode='".$prodcode."'"); 
	return $result;	 
 }
 public function catName($pscatid){
	$result=mysql_query("SELECT prod_sub_cat,product_category FROM product_sub_category where psubcatid='".$pscatid."'"); 
	return $result;	 
 }
 public function brandName($brandcode){
	$result=mysql_query("SELECT make FROM make_master where id='".$brandcode."'"); 
	return $result;	 
 }
 public function productPrice($loc_state,$loc_type,$prodcode){
	$result=mysql_query("SELECT mrp,price FROM price_master where state='".$loc_state."' and location_type='".$loc_type."' and product_code='".$prodcode."' and status='active'"); 
	return $result;	 
 }
 
 public function task_master($ei){
	 //echo "SELECT * FROM task_master where 1 and (status='pending') or (status='open') or (status='in-progress')";
	 $result=mysql_query("SELECT * FROM task_master where assign_to='$ei' and (status='pending') or (status='open') or (status='in-progress')");
	 return $result;
 }
 


  ////////////////////Lead User Track///////////////
 public function LeadUserTrack($prime_id,$address,$date_value,$time_value,$eng_id,$latitude,$longitude,$imei,$model_id,$distance) {
	$sql =mysql_query("insert ignore into lead_user_track set prime_id ='$prime_id',eng_id='$eng_id',travel_date='$date_value',travel_time='$time_value',address='$address' ,latitude  = '$latitude' , longitude ='$longitude' ,  	imei ='$imei' , model_id = '$model_id',travel_km='$distance'");
    if(mysql_insert_id()){
	$a[prime_id] = $prime_id;
  $a["response"]='1';    
	return $a;  
 }  
else{
	$a[prime_id] = $prime_id;
	$a["response"]='0';    
	return $a;  	
	}
 	}
 ////////////////////event Track///////////////
 public function UserEventTrack($userid,$imei,$model_id,$date_value,$time_value,$distance,$latitude,$longitude,$address,$event,$event_refno) {
	$sql = mysql_query("INSERT INTO user_event_track set userid = '".$userid."', imei = '".$imei."', model_id = '".$model_id."', travel_date = '".$date_value."', travel_time = '".$time_value."', travel_km = '".$distance."', latitude = '".$latitude."', longitude = '".$longitude."', address = '".$address."', event_done = '".$event."', event_ref_no = '".$event_refno."'");
    if(mysql_insert_id()){
  		$a = '1';    
		return $a;  
	}
	else{
		$a = '0';    
		return $a;  	
	}
 }
 
 public function task_master_all(){
	 $result=mysql_query("SELECT * FROM task_master");
	 return $result; 
 }

 public function getfeedback_data($ei){
	 $result=mysql_query("SELECT * FROM product_feedback_data WHERE update_by = '".$ei."'");
	 return $result;
 }	
	
	
	public function RetailerPost($name,$city,$state,$addrs,$pin,$email,$phn,$latitude,$longitude,$create_by){
	$b=array();	
	$result=mysql_query("insert into my_retailer set  name='".$name."',city ='".$city."',state='".$state."',address='".$addrs."',pincode='".$pin."',email='".$email."',phone='".$phn."',latitude='".$latitude."',longitude='".$longitude."',create_by='".$create_by."'");
	if($result){
		$b['name']=$name;
		$b['city']=$city;
		$b['state']=$state;
		$b['address']=$addrs;
		$b['pincode']=$pin;
		$b['email']=$email;
		$b['phone']=$phn;
		$b['latitude']=$latitude;
		$b['longitude']=$longitude;
		$b['response']=1;	
	}else{
		$b['name']=$name;
		$b['city']=$city;
		$b['state']=$state;
		$b['address']=$addrs;
		$b['pincode']=$pin;
		$b['email']=$email;
		$b['phone']=$phn;
		$b['latitude']=$latitude;
		$b['longitude']=$longitude;
		$b['response']=0;
	}
	return $b;
}
	////// make sales order
	function createSO($prod_code,$retailerCode,$uid,$uname,$delivery_address,$latitude,$longitude,$address,$distance,$imei,$modelid){
		$flag = 1;
		$today = date("Y-m-d");
		$currtime = date("H:i:s");
		if($retailerCode){
		//// Make System generated PO no.//////
		$res_po = mysql_query("select max(temp_no) as no from purchase_order_master where po_from='".$retailerCode."'");
		$row_po = mysql_fetch_array($res_po);
		$c_nos = $row_po['no']+1;
		$po_no = $retailerCode."PO".$c_nos;
		//// get parent id
		$row_parent = mysql_fetch_assoc(mysql_query("select uid from mapped_master where mapped_code='".$retailerCode."' and status='Y'"));
		$parentcode = $row_parent["uid"];
		$total_amount = 0;
	///// Insert in item data by picking each data row one by one
	for($i=0; $i<count($prod_code) ; $i++) { 
		$prd_code =  $prod_code[$i]["productcode"];
		$prd_cat =  $prod_code[$i]["productcat"];
		$qty =  $prod_code[$i]["qty"];
		$price =  $prod_code[$i]["price"];
		$amount = round($qty * $price);
		$total_amount += $amount;
			/////////// insert data
		   $query2="insert into purchase_order_data set po_no='".$po_no."', prod_code='".$prd_code."',prod_cat='".$prd_cat."', req_qty='".$qty."', po_price='".$price."', po_value='".$amount."', hold_price='".$amount."', mrp='".$mrp."', discount='".$rowdiscount."', totalval='".$amount."'";
		   $result = mysql_query($query2);
		   if($result){
			   $flag *=1;
		   }else{
			   $flag *=0;
		   }
		   ////// hold the PO qty in stock ////
	       //$flag=holdStockQty($parentcode,$val,$req_qty[$k],$link1,$flag);
	}/// close for loop
	///// Insert Master Data
		$query1= "INSERT INTO purchase_order_master set po_to='".$parentcode."',po_from='".$retailerCode."',po_no='".$po_no."',temp_no='".$c_nos."',ref_no='".$ref_no."',requested_date='".$today."',entry_date='".$today."',entry_time='".$currtime."',req_type='PO',status='PFA',po_value='".$total_amount."',create_by='".$uid."',ip='app_user',sales_person='".$uname."',sales_executive='".$uid."',payment_status='',transport_exp='',discount='".$total_discount."',discount_type='PD',remark='".$remark."',delivery_address='".$delivery_address."', latitude = '".$latitude."', longitude = '".$longitude."', address = '".$address."'";
	$result1 = mysql_query($query1);
	if($result1){
		   $flag *=1;
	   }else{
		   $flag *=0;
	   }
	////// insert in activity table////
	$this->dailyActivity($uid,$po_no,"PO","ADD","app_user");
	if($flag==1){
		///// insert in event track
		$resp = $this->UserEventTrack($uid,$imei,$modelid,$today,$currtime,$distance,$latitude,$longitude,$address,"Sales Order Create",$po_no);
		return $po_no;
	}else{
		mysql_query("delete from purchase_order_data where po_no='".$po_no."'");
		mysql_query("delete from purchase_order_master where po_no='".$po_no."'");
		return 0;
	}
		}else{
			return "userid is blank";
		}
	///// check both master and data query are successfully executed
	}
	////// function to capture daily activities /////
	public function dailyActivity($uid,$refno,$activityType,$actionTaken,$ip){
		$todayDate = date('Y-m-d');
		$todayTime = date('H:i:s');
		$query = "INSERT INTO daily_activities set userid='".$uid."',ref_no='".$refno."',activity_type='".$activityType."',action_taken='".$actionTaken."',update_date='".$todayDate."',update_time='".$todayTime."',system_ip='".$ip."'";
		$result = mysql_query($query);
	}
 function product_feedback($fb_type,$fb_subj,$feedback,$image,$userid,$latitude,$longitude,$address,$distance,$imei,$model_id){
	$b=array();	
	$today = date("Y-m-d");
	$todaytime = date("H:i:s");
	///// make FB ref no
	$res_ref = mysql_query("SELECT MAX(ref_id) as mno FROM product_feedback_data WHERE update_by = '".$userid."'");
	$row_ref = mysql_fetch_assoc($res_ref);
	$next_mno = $row_ref["mno"] + 1;
	$ref_no = "FB/".$userid."/".$next_mno;
	////////
	$result = mysql_query("INSERT INTO product_feedback_data SET ref_no = '".$ref_no."', ref_id = '".$next_mno."', feedback_type = '".$fb_type."', feedback_subject = '".$fb_subj."', feedback = '".$feedback."', update_by = '".$userid."', update_date = '".date("Y-m-d H:i:s")."', latitude = '".$latitude."', longitude = '".$longitude."', address = '".$address."', image = '".$image."'");
	if($result){
		///// insert in event track
		$resp = $this->UserEventTrack($userid,$imei,$model_id,$today,$todaytime,$distance,$latitude,$longitude,$address,"Feedback Submit",$ref_no);
		$b['success'] = "Feedback is successfully submitted";
		$b['id'] = $userid;
	}else{
		$b['error'] = "Request could not processed. Please try again";
		$b['id'] = $userid;
	}
	return $b;
 }
 /////// add TA DA of sales executive
 public function addTaDa($uid , $food_exp , $food_filename , $courier_exp , $courier_filename , $localconv_exp , $localconv_filename , $mobile_exp , $mobile_filename , $other_exp , $other_filename , $remk,$latitude,$longitude,$address,$distance,$imei,$modelid){
	$todayDate = date('Y-m-d');
	$todayTime = date('H:i:s');
	// make expense system generated ref no.
	$sql = "SELECT MAX(seq_no) as qa FROM ta_da where userid='".$uid."'";
	$res = mysql_query($sql);
	$row = mysql_fetch_assoc($res);
	$code_id = $row["qa"];
	$next_seq = $row["qa"] + 1;
	/// make 3 digit padding
	$pad = str_pad(++$code_id,4,"0",STR_PAD_LEFT);
	//// make logic of ref no.
	$refno = "EXP/".strtoupper($uid)."/".$pad;
    /// calculate total exp amount
	$total_exp = $food_exp + $courier_exp + $localconv_exp + $mobile_exp + $other_exp;
	$query = "INSERT INTO ta_da set userid='".$uid."',system_ref_no='".$refno."',seq_no='".$next_seq."',food_exp='".$food_exp."',food_exp_img='".$food_filename."',courier_exp='".$courier_exp."',courier_exp_img='".$courier_filename."',localconv_exp='".$localconv_exp."',localconv_exp_img='".$localconv_filename."',mobile_exp='".$mobile_exp."',mobile_exp_img='".$mobile_filename."',other_exp='".$other_exp."',other_exp_img='".$other_filename."',entry_date='".$todayDate."',entry_time='".$todayTime."',entry_by='app_user',remark='".$remk."',total_amt='".$total_exp."',status='Pending', latitude = '".$latitude."', longitude = '".$longitude."', address = '".$address."'";
	$result = mysql_query($query); 
	if($result){
		///// insert in event track
		$resp = $this->UserEventTrack($uid,$imei,$modelid,$todayDate,$todayTime,$distance,$latitude,$longitude,$address,"TA/DA Submit",$refno);
		return $refno;
	}else{
		return 0;
	}
 }
 public function save_stock($retailer_name,$feature_phone,$smart_phone,$collection_amt,$collection_mode,$image_name,$image){
	 $a=array();
	 $result=mysql_query("insert into save_stock set retailer_name='$retailer_name',feature_phone='$feature_phone',smart_phone='$smart_phone',collection_amt='$collection_amt',collection_mode='$collection_mode',image_name='$image_name'");
	 if($result) {  	 
     $a["response"]=1;
     
   return $a;         
   
   } else{ if( mysql_errno() == 1062) {                
 
   $a["response"]=0;
   
   return $a;             
   } else {                 
 
   $a["status"]='no';
                  
  return $a;             
                     
 }} 
 }
 
 
 public function save_task($refid,$ref_no,$userid,$remark,$status,$image_name,$latitude,$longitude,$address,$distance,$imei,$model_id){
	$a=array();
	$todayDate = date('Y-m-d');
	$todayTime = date('H:i:s');
	////// update status in task master
	$res1 = mysql_query("UPDATE task_master SET status='".$status."' WHERE id='".$refid."'");
	if($res1){
		///// save in history 
		$res2 = mysql_query("INSERT INTO save_task_report SET id='".$refid."',userid='".$userid."',remark='".$remark."',status='".$status."',image_name='".$image_name."', updatedate = '".date("Y-m-d H:i:s")."', latitude = '".$latitude."', longitude = '".$longitude."', address = '".$address."'");
		if($res2){
			///// insert in event track
			$resp = $this->UserEventTrack($userid,$imei,$model_id,$todayDate,$todayTime,$distance,$latitude,$longitude,$address,"Task Execute",$ref_no);
			$b['success'] = "Task is successfully executed";
		}else{
			$b['error'] = "Request could not processed. Please try again";
		}
	}else{
		$b['error'] = "Request could not processed. Please try again";
	}
	return $b;
 }
 
 public function postsale($imei,$cust_name,$contact_no,$state,$city,$sync_date,$ei,$productname,$serial_no){
	 $a=array();
	 
	$result=mysql_query("insert into sale_data set imei='$imei',cust_name='$cust_name',contact_no='$contact_no',state='$state',city='$city',sync_date='$sync_date',user_name='$ei',productname='$productname',serial_no='$serial_no' ");
	
	 if($result) {  
	 
     $a["response"]=1;
     
   return $a;         
   
   } else {             
  if( mysql_errno() == 1062) {                
 
   $a["response"]=0;
   
   return $a;             
   } else {                 
 
   $a["status"]='no';
                  
 return $a;             
                     
 }
   }// end of else
 }// end of function
 
  /////////////user Attendence Data/////////////
  public function user_attendence($longitu_in,$latitu_in,$in_datetime,$out_datetime,$status_in,$status_out,$ei,$address_in,$address_out,$insert_date,$longitu_out,$latitu_out,$Image_in,$Image_out,$pmodel,$imei,$pmac) {
	 $a=array();
	 $todayDate = date('Y-m-d');
	 $todayTime = date('H:i:s');
	 $msg='';
	 $chk_user=mysql_fetch_array(mysql_query("select utype from admin_users where username='$ei'"));
	 
$chk=mysql_query("select * from user_attendence where user_id='$ei' and insert_date='$insert_date'");
$chk2=mysql_fetch_array($chk);
if(mysql_num_rows($chk)<=0 && $status_in!='' && $chk_user['utype']!='7'){
	//echo "insert into user_attendence set longitude_in='$longitu_in',latitude_in='$latitu_in',longitude_out='$longitu_out',latitude_out='$latitu_out',user_id='$ei',status_in='$status_in',in_datetime='$in_datetime',status_out='$status_out',out_datetime='$out_datetime',address_in='$address_in',address_out='$address_out',insert_date='$insert_date'";
	$result=mysql_query("insert into user_attendence set longitude_in='$longitu_in',latitude_in='$latitu_in',longitude_out='$longitu_out',latitude_out='$latitu_out',user_id='$ei',status_in='$status_in',in_datetime='$in_datetime',status_out='$status_out',out_datetime='$out_datetime',address_in='$address_in',address_out='$address_out',insert_date='$insert_date',Image_in='$Image_in',Image_out='$Image_out', pmodel = '$pmodel' , imei = '$imei' , pmac = '$pmac'  ")or die(mysql_error());
	$ref_no = mysql_insert_id();
	$latitude = $latitu_in;
	$longitude = $longitu_in;
	$address = $address_in;
}else if(mysql_num_rows($chk)>0 && $chk2['status_out']==''){
	$result=mysql_query("update user_attendence set status_out='$status_out',out_datetime='$out_datetime',address_out='$address_out',longitude_out='$longitu_out',latitude_out='$latitu_out',Image_out='$Image_out' ,pmodel = '$pmodel' , imei = '$imei' , pmac = '$pmac' where id='$chk2[id]'");
	$ref_no = $chk2['id'];
	$latitude = $latitu_out;
	$longitude = $longitu_out;
	$address = $address_out;
}
elseif(mysql_num_rows($chk)>0 && $chk2[status_in]!='' && $chk2[status_out]!='' ){
	$msg="Data Already Exist!";
}
else if($chk_user['utype']='7'){
	$msg="You are not authorized for attendence!";
}
else{
	$msg="Plese Log In First!";
}
if($result) { 
   ///// insert in event track
   $resp = $this->UserEventTrack($user_id,$imei,$pmodel,$todayDate,$todayTime,$distance,$latitude,$longitude,$address,"Attendance IN",$ref_no); 
   $a["status"]='yes';
   $a["id"]=$id;  
   $a["msg"]=$msg;      
return $a;         
} else {             
if( mysql_errno() == 1062) {                
 // Duplicate key - Primary Key Violation   
   $a["status"]='yes';
   $a["userid"]=$ei;
   $a["msg"]=$msg;               
 return $a;             
 } else {                 
 // For other errors 
   $a["status"]='no';
   $a["userid"]=$ei;
   $a["msg"]=$msg;                 
 return $a;             
 }                     
 }

}
 ////// function for upload user document
	public function uploadDoc($seid,$docname,$fname,$docfile){
		$msgg="";
		$stss="";
		////////// if GST file is uploaded 
		if($docfile!=NULL && $docfile!=""){
			$binary = base64_decode($docfile);
			$result = file_put_contents("user_doc/".$fname,$binary);
			///update status verified in sign up table
			$query1 = mysql_query("INSERT INTO document_upload set doc_name= '".$docname."',file_name='".$fname."',upload_by='".$seid."',upload_from='APP'");
			if(!$query1){
				$msgg="Request could not be procesed";
				$stss = "fail";
			}else{
				$msgg = "Document is successfully uploaded.";
				$stss = "success";
			}
		}else{
			$msgg="Request could not be procesed";
			$stss = "fail";
		}
		return $stss."~".$msgg; 
	}
 public function changePassword($user_id,$old_password,$new_password){
		$b=array();
		//// check old password should be matched
		//echo "SELECT uid,password,status from admin_users where username='".$user_id."'";
		$userdet = mysql_fetch_assoc(mysql_query("SELECT uid,password,status from admin_users where username='".$user_id."' or phone = '".$user_id."' or emailid = '".$user_id."'"));
		//// check userid is active or deactive
		if($userdet["status"] == "active"){
			///// check old password is correct or not
			if($userdet["password"] == $old_password){
				$result = mysql_query("UPDATE admin_users set password = '".$new_password."' where uid='".$userdet["uid"]."'");
				if($result){
					$b['response'] = "Password is changed successfully.";	
				}else{
					$b['response'] = "Something went wrong. Please try again.";
				}
			}else{
				$b['response'] = "Old password is not matched.";
			}
		}else{
			$b['response'] = "Userid is deactivated.";
		}
		return $b;
	}
	///// function to get sale order qty as well sale qty associate with requested sales executive
	public function getSaleReport($user_id,$from_date,$to_date){
		if($from_date){ 
			$f_date = $from_date;
			$t_date = $to_date;
		}else{ 
			$f_date = date("Y-m-d");
			$t_date = date("Y-m-d");
		}
		////// get sale order qty
		$res_so = mysql_query("SELECT b.prod_code, b.req_qty, b.qty FROM purchase_order_master a, purchase_order_data b WHERE a.po_no=b.po_no and a.sales_executive='".$user_id."' and a.entry_date >= '".$f_date."' and a.entry_date <= '".$t_date."' GROUP BY b.prod_code");
		return $res_so;
	}
	///// function to get selected task history
	public function taskHistory($refid){
		////// get sale order qty
		$res_th = mysql_query("SELECT * FROM save_task_report WHERE id='".$refid."' ORDER BY updatedate");
		return $res_th;
	}
	///// function to get leave list of employee ////
	public function LeaveList($ei){
		$result = mysql_query("SELECT * FROM hrms_leave_request where empid='".$ei."'"); 
		return $result;	 
 	}
	/////// add Add Leave for employee /////
 	public function addLeave($empid , $leave_type , $from_date , $to_date , $purpose , $leave_description, $leave_duration){
		$todayDate = date('Y-m-d');
		$todayTime = date('H:i:s');
		
		$query = "INSERT INTO hrms_leave_request SET empid='".$empid."',leave_type='".$leave_type."',from_date='".$from_date."',to_date='".$to_date."',leave_duration='".$leave_duration."',purpose='".$purpose."',description='".$leave_description."',status='Pending',entry_date='".$todayDate."',entry_time='".$todayTime."'";
		$result = mysql_query($query); 
		if($result){
			return 1;
		}else{
			return 0;
		}
 	}
	/////// Leave view of employee /////
 	public function LeaveItems($ref_no){
		return $result = mysql_query("SELECT * FROM hrms_leave_request WHERE id='".$ref_no."'");
	}
	/////// get employee salary slip details //////
	public function SalarySlipItems($emp_id, $salary_month, $salary_year){
		return $result = mysql_query("SELECT * FROM hrms_salary_upload WHERE emp_id='".$emp_id."' and salary_month='".$salary_month."' and salary_year='".$salary_year."'");
	}
	/////// Leave cancel of employee /////
 	public function LeaveCancel($ref_no, $cancel_by, $cancel_remark){
 		$todayDate = date('Y-m-d');
		$todayTime = date('H:i:s');
		
		$result = mysql_query("UPDATE hrms_leave_request SET cancel_by = '".$cancel_by."', cancel_date = '".$todayDate."', cancel_time = '".$todayTime."', cancel_remark = '".$cancel_remark."' WHERE id='".$ref_no."'");
		if($result){
			return 1;
		}else{
			return 0;
		}	
	}
	////// function for activity add
	public function ActivityAdd($activity_name,$activity_desc,$file_name,$attach_file,$create_by){
		$todayDate = date('Y-m-d');
		$todayTime = date('H:i:s');
		
		////////// if activity file is uploaded 
		if($attach_file!=NULL && $attach_file!=""){
			$binary = base64_decode($attach_file);
			$result = file_put_contents("activity_file/".$file_name,$binary);
		}
	
		////// count max no. of activity in selected state
		$query_code="select MAX(temp_no) as tn from hrms_activities_master where 1 ";
		$result_code=mysql_query($query_code);
		if(!$result_code){
			$err_msg = "ER1".mysql_error();
		}
		$arr_result2=mysql_fetch_array($result_code);
		$code_id=$arr_result2[0];
		/// make 6 digit padding
		$tmp_no = $code_id+1;
		$pad=str_pad($tmp_no,6,"0",STR_PAD_LEFT);		
		$activate_no = "A".$pad; 
		
		///insert data into db table
		$query1 = mysql_query("INSERT INTO hrms_activities_master set temp_no = '".$tmp_no."', activity_no ='".$activate_no."', activity_desc = '".$activity_name."', activity_detail = '".$activity_desc."', file_name = '".$file_name."', file_path = '".$attach_file."', status = 'Active', create_by = '".$create_by."', create_date = '".$todayDate."'");
		
		if($query1){
			///insert data into db table
			$query2 = mysql_query("INSERT INTO daily_activities set userid = '".$create_by."', ref_no ='".$activate_no."', activity_type = 'ACTIVITY', action_taken = 'ADD', update_date = '".$todayDate."', update_time = '".$todayTime."', system_ip = 'app_user'");
		}
		
		if($query2){
			return 1;
		}else{
			return 0;
		}		
	}
	///// function to get activity list ////
	public function ActivityList($activity_no){
		$result = mysql_query("SELECT * FROM hrms_activities_master where activity_no = '".$activity_no."'"); 
		return $result;	 
 	}
 	/////// Activity view of employee /////
 	public function ActivityItems($ref_no){
		return $result = mysql_query("SELECT * FROM hrms_activities_master WHERE activity_no = '".$ref_no."'");
	}
	////// function for activity add
	public function ActivityFeedbackAdd($activity_no,$activity_remark,$file_name,$attach_file,$create_by){
		$todayDate = date('Y-m-d');
		$todayTime = date('H:i:s');
		
		////////// if activity file is uploaded 
		if($attach_file!=NULL && $attach_file!=""){
			$binary = base64_decode($attach_file);
			$result = file_put_contents("activity_feedback_file/".$file_name,$binary);
		}
			
		///insert data into db table
		$query1 = mysql_query("INSERT INTO hrms_activities_feedback set activity_no ='".$activity_no."', feedback = '".$activity_remark."', file_name = '".$file_name."', file_path = '".$attach_file."', update_by = '".$create_by."', update_date = '".$todayDate."'");
		
		if($query1){
			///insert data into db table
			$query2 = mysql_query("INSERT INTO daily_activities set userid = '".$create_by."', ref_no ='".$activity_no."', activity_type = 'FEEDBACK', action_taken = 'ADD', update_date = '".$todayDate."', update_time = '".$todayTime."', system_ip = 'app_user'");
		}
		
		if($query2){
			return 1;
		}else{
			return 0;
		}		
	}
	///// function to get activity feedback list ////
	public function ActivityFeedBackList($activity_no){
		$result = mysql_query("SELECT * FROM hrms_activities_feedback where activity_no = '".$activity_no."'"); 
		return $result;	 
 	}
	//// get lat long
	public function liveTrack($uid,$latitude,$longitude,$deviceid){
		$res_lt = mysql_query("INSERT INTO live_track SET userid='".$uid."' , latitude='".$latitude."' , longitude='".$longitude."' , device_id='".$deviceid."'");
		if($res_lt){
			return "1";	
		}else{
			return "0";	
		}
	}
}

