<?php 

// Include main file
include_once('../libs/main.php');

// Check user Login
include_once('checkLogin.php');

// Logical section of page
$userObj =  new  user();

$successMsg = '';

if(isset($_REQUEST['successMsg'])){
	$successMsg = $_REQUEST['successMsg'];
}

if(isset($_REQUEST['failedMsg'])){
	$failedMsg = $_REQUEST['failedMsg'];
}

if(isset($_REQUEST['act']) && $_REQUEST['act']=='validate_email'){
	if($_REQUEST['email']==''){
		echo 'Please enter email address';
		exit;
	}else if(validateEmail($_REQUEST['email'])){
		
		if(isset($_REQUEST['user_id']) && $userObj->checkEmailExist($_REQUEST['email'],$_REQUEST['user_id'])){
			echo "Email already exist";
			exit;
		}else if($userObj->checkEmailExist($_REQUEST['email'])){
			echo "Email already exist";
			exit;
		}
	}else{
		echo 'Please enter valid email address';
		exit;
	}
	
	return true;
}



if(isset($_REQUEST['act']) && $_REQUEST['act']=='edit' && isset($_REQUEST['user_id'])){
	$userDetail = $userObj->fromId($_REQUEST['user_id']);
}


if(isset($_POST['submit'])){
	$userData = new stdClass();
	
	if(isset($_FILES['profile_image']) && $_FILES['profile_image']['name']!=''){
		$image=$_FILES['profile_image']['name'];
		$image=time().'_'.$image;
		$extension = strtolower(getExtension($image));
		
		if($extension!='jpg' and $extension!='gif' and $extension!='jpeg' and $extension!='png'){
			header('location:addpackage.php?$failedMsg=Invalid image extension.');
			exit;
		}
		
		move_uploaded_file($_FILES['profile_image']['tmp_name'], DIR_UPLOAD_BANNER.$image);		
		$userData->profile_image	= $image;	
	}else{
		$userData->profile_image	= $_POST['uploaded_file'];	
	}
	
	$userData->user_name 		= $_POST['user_name'];
	$userData->mobile_no 		= $_POST['mobile_no'];
	$userData->email_address 		= $_POST['email_address'];
	$userData->user_status  		= $_POST['user_status'];
	$userData->user_created_date= date('Y-m-d H:i:s');
	$userData->user_ip_address= $_SERVER['REMOTE_ADDR'];		
	$userData->user_last_login_date = date('Y-m-d');	
	
	// edit user details 
	if(isset($_POST['user_id'])){

		$userData->user_id = $_POST['user_id'];
		$pageD = $userObj->fromId($userData->user_id);
		if(isset($_FILES['profile_image']) && $_FILES['profile_image']['name']!=''){
			if($pageD->profile_image!='' && file_exists(DIR_UPLOAD_BANNER.$pageD->profile_image)){
				unlink(DIR_UPLOAD_BANNER.$pageD->profile_image);
			}
		}	
		
		$rs = $userObj->updateRecords($userData);
		if($rs){
			$successMsg ="Agency Details Updated successfully";			
			header('Location:userlist.php?successMsg='.$successMsg);
			exit;
		}
		
	// add user details 	
	}else{
	
		$userData->user_password 	= md5($_POST['user_password']);	
		$rs = $userObj->addRecords($userData);
		if($rs){
			$uniqId = 'DS'.$rs;
			$userObj->addUniqId($uniqId, $rs);
			$successMsg ="Agency Details Added successfully";			
			header('Location:userlist.php?successMsg='.$successMsg);
			exit;
		}
		
	}
}



// Include Template 
include_once('../libs/routs.php')

?>
