<?php

// FILE FOR AUTHENTICATION 
/*
All possible functions
- login
- logout
- forgotpassword
- signup
- emailverify
*/

//echo "i am here line number 13";die();

if($_SERVER['REQUEST_METHOD'] == 'GET') {

}

if($_SERVER['REQUEST_METHOD'] == 'POST') {
	$action = $_POST['action'];

	//echo "<pre>";print_r($action);die();

	//echo "i am here line number 22";die();

	include_once('config.php');
	include_once('common_functions.php');
	include_once('common_functions_app.php');

	//echo "i am here line number 28";die();

	switch($action){
		case 'signin' : {
			signin($_POST);
			break;
		}

		case 'forgot_password' : {

			forgotPassword($_POST);
			break;
		}
        case 'reset_password_admin' : {
			resetPasswordAdmin($_POST);
			break;
		}
		 case 'create_password_user' : {
			createPasswordUser($_POST);
			break;
		}
		default:
			include_once('language_message.php');
			$record=array('success'=>false, 'msg'=>$msgValidAction, 'data'=>array()); 
			jsonSendEncode($record); 
	}	
}

function signin($data) {
	global $mysqli;
	include_once('language_message.php');
	//echo'<pre>';print_r($data);die;
 	if(empty($data['email']) || empty($data['password'])) {
 		$record=array('success'=>false, 'msg'=>$msgEmptyAll, 'data'=>array()); 
		jsonSendEncode($record);  
 	} else {
 		$email 		 = $data['email'];
 		$password	 = md5($data['password']);
 		$player_id	 = $data['player_id'];
		$device_type = 'android';

	 	//-------------------------- check user email --------------------------
		$check_email_all=$mysqli->prepare("SELECT user_id from user_master where delete_flag='0'  and email=? and user_type IN(0,1)");
		$check_email_all->bind_param("s",$email);
		$check_email_all->execute();
		$check_email_all->store_result();
		$check_email=$check_email_all->num_rows;

		if($check_email <= 0) {
			$record=array('success'=>false, 'msg'=>$msgInvalidEmail, 'data'=>array()); 
			jsonSendEncode($record);    
		}
		
		//--------------------------- password check  ------------------
		$check_login_all=$mysqli->prepare("SELECT user_id, user_type,role_id from user_master where delete_flag='0'  and email=? and BINARY password=? and user_type IN(0,1)");
		$check_login_all->bind_param("ss",$email,$password);
		$check_login_all->execute();
		$check_login_all->store_result();
		$check_login=$check_login_all->num_rows;

		if($check_login <= 0) {
			$record=array('success'=>false, 'msg'=>$msgInvalidPassword, 'data'=>array()); 
			jsonSendEncode($record);    
		}

		$check_login_all->bind_result($user_id, $user_type,$role_id_get);
		$check_login_all->fetch();

		//----------------------------- check account activate or not ----------------------
		$active_status = checkAccountActivateDeactivate($user_id); 
	    if($active_status == '0') {
	      $record=array('success'=>false, 'msg'=>$msgAccountDeactivate, 'data'=>array('account_active_status'=>$active_status)); 
	      jsonSendEncode($record); 
	    }
		//-------------------------------- get user complete details --------------------------
		$user_details=getUserDetails($user_id);
		// set the user session 
		session_start();
		$_SESSION['user_id'] 	= encode($user_id);
		$_SESSION['user_type'] 	= $user_type;
		$_SESSION['role'] 	= $role_id_get;
		// $result =  DeviceTokenStore_1_Signal($user_id, $device_type, $player_id);
  //       if($result == 'no'){
  //           $result =  DeviceTokenStore_1_Signal($user_id, $device_type, $player_id);
  //       }

		$record=array('success'=>true, 'msg'=>$msgLoginSuccess, 'data'=>array('user_details'=>$user_details,'role_id_get'=>$role_id_get)); 
		jsonSendEncode($record);
 	}
}
function forgotPassword($data) {
    error_reporting(0);
    // echo "<pre>"; print_r($data);die();
	global $mysqli;
	include_once('language_message.php');
	include_once('mailFunctions.php');
 	include('site_config.php');
 	if(empty($data['email'])) {
 		$record=array('success'=>false, 'msg'=>$msgEmptyAll, 'data'=>array()); 
		jsonSendEncode($record);  
 	} 
 	else {

 		//echo "123 <pre>"; print_r($data);die();
 		$email	= $data['email']; 
        
	 	//-------------------------- check user email --------------------------
		$check_email_all=$mysqli->prepare("SELECT user_id,name, password from user_master where delete_flag='0' and user_type =0 and email=?");
		$check_email_all->bind_param("s",$email);
		$check_email_all->execute();
		$check_email_all->store_result();
		$check_email=$check_email_all->num_rows;
		// echo "check_email=";print_r($check_email);die();
		if($check_email <= 0) {
			$record=array('success'=>false, 'msg'=>$msgInvalidEmail1, 'data'=>array()); 
			jsonSendEncode($record);    
		}
	    else{


			$check_email_all->bind_result($user_id_get,$name_get, $password_get);
			$check_email_all->fetch();
			//$forgot_pass_identity = base64_encode($user_id);
			$fp_code = md5(uniqid());
			$resetPassLink = $siteURL.'resetpassword.php?uniqcode='.$fp_code;
			$mailContent = 'Recently a request was submitted to reset a password for your account. If this was a mistake, just ignore this email and nothing will happen.<br/>To reset your password, visit the following link:
			<a href="'.$resetPassLink.'" style="float: unset; width: 25%; display: block; margin: 26px auto 0; background:#3906A5; text-align: center; vertical-align: middle; user-select: none; border: 1px solid transparent; padding: .375rem .75rem; font-size: .875rem; line-height: 1.5; border-radius: .25rem; transition: color .15s ease-in-out,background-color .15s ease-in-out,border-color .15s ease-in-out,box-shadow .15s ease-in-out; color: #fff;text-decoration: unset;">Reset Password</a>';

			$active_flag	=	0;
			$user_type		=	0;
			$delete_flag	=	0;
			$createtime		=	date('Y-m-d H:i:s');
			$updatetime		=	date('Y-m-d H:i:s');
               
                
                // Now Insert Data Into Request Table
            
           	$forgot_insert = $mysqli->prepare("INSERT INTO forgot_password_master(user_id,user_type, email,forgot_pass_identity, active_flag, delete_flag, createtime, updatetime) VALUES (?,?,?,?,?,?,?,?)");
            $forgot_insert->bind_param("iissiiss", $user_id_get,$user_type, $email , $fp_code, $active_flag, $delete_flag, $createtime, $updatetime);
            $forgot_insert->execute();
            $insert_id=$mysqli->affected_rows;
            if($insert_id<=0) {	
	            $record =	array('success'=>'false', 'msg' =>$msg_succ_forgot); 
	            jsonSendEncode($record); 
            }	
            
            //mail Function call
            $postData['mailContent'] =	$mailContent;
            $postData['name'] 		=	$name_get;
            $postData['email']		=	$email;
            $postData['fromName']	=	$appName;
            $postData['app_name']	=	$appName;
            $postData['app_logo'] 	=	$appLogo;
            $subject =	"Forgot password";

            // echo "postData=";print_r($postData);die();

            $mailBody =	mailBodyForgotPasswordData($postData);
           	// echo "postData=";print_r($mailBody);die();
            $mailResponse =	mailSend($postData['email'], $postData['fromName'], $subject, $mailBody);
                
                // echo "postData=";print_r($mailResponse);die();
        	if($mailResponse == 'yes'){
            	$record=array('success'=>true, 'msg'=>$msgForgetPasswordSuccess, 'data'=>array());
         		jsonSendEncode($record);
            
            } 
            else{
       			$record=array('success'=>false, 'msg'=>$msgNotSendEmail, 'data'=>array()); 
            	jsonSendEncode($record);
       		}
               
        } 
 	}
}

function resetPasswordAdmin($data){
    // print_r($data);
    global $mysqli;
	include_once('language_message.php');
	include('mailFunctions.php');
	if(empty($data['uniqcode'])) {
 		$record=array('success'=>false, 'msg'=>$msgEmptyAll, 'data'=>array()); 
		jsonSendEncode($record);  
 	} 
 	else {

 	    $uniqcode	 = $data['uniqcode'];

 	    //echo "SELECT `forgot_id`, `user_id`, `email`, `user_type`,`active_flag`,`delete_flag`, `createtime` FROM `forgot_password_master` WHERE `active_flag`='0' AND `forgot_pass_identity`='".$uniqcode."'";die();

 	    $check_email = $mysqli->prepare("SELECT `forgot_id`, `user_id`, `email`, `user_type`,`active_flag`,`delete_flag`, `createtime` FROM `forgot_password_master` WHERE  `forgot_pass_identity`=?");
	    $check_email->bind_param("s",$uniqcode);
	    $check_email->execute();
	    $check_email->store_result();
	    $check_email_count=$check_email->num_rows;
	    if($check_email_count <= 0) {
	        $record = array('error'=>true, 'msg'=>$msgResetPasswordDeactivate, 'data'=>array());
	        jsonSendEncode($record);
	    }
	    else
	    {
	        $check_email->bind_result($forgot_id, $user_id, $email, $user_type, $active_flag, $delete_flag,$createtime);
	         $check_email->fetch();
	        $new_password = md5($data['password']);
	        
	        $updatetime=date('Y-m-d H:i:s');

	        $update_password=$mysqli->prepare("UPDATE user_master SET password=?, updatetime=? WHERE user_id=?");
	        $update_password->bind_param("ssi",$new_password,$updatetime,$user_id);
	        $update_password->execute();
	        $update_password->store_result();
	        $update_password_count=$update_password->affected_rows;  //0 1
	        //echo "update_password_count=";print_r($update_password_count);die();
	        if($update_password_count>0)
	        {
	        	$active_flag = 1;
	            $delet_password=$mysqli->prepare("UPDATE forgot_password_master SET active_flag=?,updatetime=? WHERE forgot_pass_identity=?");
	            $delet_password->bind_param("iss",$active_flag,$updatetime,$uniqcode);
	            $delet_password->execute();
	            $delet_password->store_result();
	            $delet_password_count=$delet_password->affected_rows;  //0 1
	            if($delet_password_count>0)
	            {
	                $record=array('success'=>true, 'msg'=>$msgResetPasswordSuccess, 'data'=>array());
	            	jsonSendEncode($record);
	            }else{
	               $record=array('error'=>true, 'msg'=>$msgResetPasswordError, 'data'=>array());
	            	jsonSendEncode($record);
	            }
	        }else{
	            $record=array('error'=>true, 'msg'=>$msgResetPasswordError, 'data'=>array());
	            jsonSendEncode($record);
	        }
		}
 	} 
}

function createPasswordUser($data){
    // print_r($data);
    global $mysqli;
	include_once('language_message.php');
	include('mailFunctions.php');
	if(empty($data['uniqcode'])) {
 		$record=array('success'=>false, 'msg'=>$msgEmptyAll, 'data'=>array()); 
		jsonSendEncode($record);  
 	} 
 	else {

 	    $uniqcode	 = $data['uniqcode'];

 	    //echo "SELECT `forgot_id`, `user_id`, `email`, `user_type`,`active_flag`,`delete_flag`, `createtime` FROM `forgot_password_master` WHERE `active_flag`='0' AND `forgot_pass_identity`='".$uniqcode."'";die();

 	    $check_email = $mysqli->prepare("SELECT `forgot_id`, `user_id`, `email`, `user_type`,`active_flag`,`delete_flag`, `createtime` FROM `forgot_password_master` WHERE  `forgot_pass_identity`=?");
	    $check_email->bind_param("s",$uniqcode);
	    $check_email->execute();
	    $check_email->store_result();
	    $check_email_count=$check_email->num_rows;
	    if($check_email_count <= 0) {
	        $record = array('error'=>true, 'msg'=>$msgResetPasswordDeactivate, 'data'=>array());
	        jsonSendEncode($record);
	    }
	    else
	    {
	        $check_email->bind_result($forgot_id, $user_id, $email, $user_type, $active_flag, $delete_flag,$createtime);
	         $check_email->fetch();
	        $new_password = md5($data['password']);
	        
	        $updatetime=date('Y-m-d H:i:s');

	        $update_password=$mysqli->prepare("UPDATE user_master SET password=?, updatetime=? WHERE user_id=?");
	        $update_password->bind_param("ssi",$new_password,$updatetime,$user_id);
	        $update_password->execute();
	        $update_password->store_result();
	        $update_password_count=$update_password->affected_rows;  //0 1
	        //echo "update_password_count=";print_r($update_password_count);die();
	        if($update_password_count>0)
	        {
	        	$active_flag = 1;
	            $delet_password=$mysqli->prepare("UPDATE forgot_password_master SET active_flag=?,updatetime=? WHERE forgot_pass_identity=?");
	            $delet_password->bind_param("iss",$active_flag,$updatetime,$uniqcode);
	            $delet_password->execute();
	            $delet_password->store_result();
	            $delet_password_count=$delet_password->affected_rows;  //0 1
	            if($delet_password_count>0)
	            {
	                $record=array('success'=>true, 'msg'=>$msgUserPasswordSuccess, 'data'=>array());
	            	jsonSendEncode($record);
	            }else{
	               $record=array('error'=>true, 'msg'=>$msgUserPasswordError, 'data'=>array());
	            	jsonSendEncode($record);
	            }
	        }else{
	            $record=array('error'=>true, 'msg'=>$msgUserPasswordError, 'data'=>array());
	            jsonSendEncode($record);
	        }
		}
 	} 
}
