<?php
class ClassUserCustom extends ClassUser {
  
	public function createUserForWefraAdmin($data, $ext_id){
		$this->_data = $data;
		$this->_extId = $ext_id;
		
		$config = ClassConfig::getConfig();
		$oPDOLink = ClassConfig::databaseConnect();
		
		//IF password and confirmPassword are not identical, displaying an error message
		if($this->_data['formRegisterFieldPassword'] != $this->_data['formRegisterFieldConfirmPassword']){
			$message['state']='failed';
			$message['css_class']='failed';
			$message['translation_code'] = 'checkRegisterForm_notSamePassword';
			return $message;
		}
		else {
			$activation_code = rand();
			$sql="
			INSERT INTO user_user(email, password, activation_code, firstname, lastname, 
					core_lang_id, core_country_id, core_currency_id, core_theme_id,
					is_active, comment
			)VALUES(
					:email, :password, :activation_code,
					:firstname, :lastname, 
					12, 44, 4, 1,
					true, 'user created during installation process')
			";
			$execSQL = $oPDOLink->prepare($sql);
			if($execSQL->execute(array(
					':email'=>$this->_data['formRegisterFieldEmail'],
					':password'=>sha1($this->_data['formRegisterFieldPassword'].'-k3P[8x&'),
					':activation_code'=>$activation_code,
					':firstname'=>$this->_data['formRegisterFieldFirstname'],
					':lastname'=>$this->_data['formRegisterFieldLastname']
			))){
				$newUserId = $oPDOLink->lastInsertId('user_user_id_seq');
				//$isVipOfferActive = $this->_checkIfVipOfferActive();
				//$isEverythingForFreeActive = $this->_checkIfEverythingForFreeActive();
				// core user detail
				$sql="
				INSERT INTO user_detail(user_id, ext_id)
				VALUES (:user_id, :ext_id)
				";
				$execSQL = $oPDOLink->prepare($sql);
				$execSQL->execute(array(':user_id'=>$newUserId, ':ext_id'=>$this->_extId));
				
				// features for user
				$sql="
				INSERT INTO useruser_corefeature_rel(user_id, core_feature_id)
				VALUES (
					(SELECT id FROM user_user WHERE email=:email LIMIT 1),
					(SELECT id FROM core_feature WHERE code=:core_feature_code LIMIT 1)
				);
				";
				$execSQL = $oPDOLink->prepare($sql);
				$execSQL->execute(array(':email'=>$this->_data['formRegisterFieldEmail'], ':core_feature_code'=>'home'));
				$execSQL->execute(array(':email'=>$this->_data['formRegisterFieldEmail'], ':core_feature_code'=>'my-profile'));
				$execSQL->execute(array(':email'=>$this->_data['formRegisterFieldEmail'], ':core_feature_code'=>'logout'));
				
				$message['user_id'] = $newUserId;
				$message['activation_code'] = $activation_code;
				$message['status'] = "success";
				$message['css_class'] = 'success-message';
				//TODO change confirmation_registration by register_form_success when registrations will need an activation by clic on link in an email
				//$message['translation_code'] = 'register_form_success'; //'confirmation_registration';
				
				//TODO send an email to admin to indicate that there is a new registration
				return $message;
			} else {
				$message['status']='failed';
				$message['css_class'] = 'failed-message';
				//$message['translation_code'] = 'register_form_failed';
				return $message;
			}
		}
  }
  
  public function array_values_recursive($array){
    $arrayValues = array();
  
    foreach ($array as $value){
      if (is_scalar($value) OR is_resource($value)){
        $arrayValues[] = $value;
      }
      elseif (is_array($value)){
        $arrayValues = array_merge($arrayValues, array_values_recursive($value));
      }
    }
  
      return $arrayValues;
  }  
  //ENDOF array_values_recursive()

	public function getUser($user_id){
    $this->_userId = $user_id;
    $oPDOLink = ClassConfig::databaseConnect();

    $sql="
    SELECT ud.ext_id, uu.*
    FROM user_user uu
			LEFT JOIN user_detail ud
			  ON uu.id=ud.user_id
    WHERE uu.id=:user_id;
    ";
    $execSQL = $oPDOLink->prepare($sql);
    $execSQL->execute(array(':user_id'=>$this->_userId));
    $row = $execSQL->fetch(PDO::FETCH_ASSOC);
    return $row;
	}
	
	public function login($post_datas=array()){
		$this->_postDatas = $post_datas;
		$oPDOLink = ClassConfig::databaseConnect();

		if($this->_postDatas['formLoginFieldEmail']=='' || $this->_postDatas['formLoginFieldPassword']==''){
			$message['state'] = 'no_required_fields_filled';
			$message['css_class'] = 'failed-message';
			$message['translation_code'] = "message_requiredFieldsNotFilled";
			return $message;
		}
		
		$sql="
		SELECT uu.id, uu.email, uu.password, uu.firstname, uu.lastname, uu.phone,
			uu.core_lang_id, uu.core_country_id, uu.core_currency_id,
			uu.is_active, 
			(SELECT code FROM core_lang WHERE id=core_lang_id) AS lang_code,
			(SELECT code FROM core_country WHERE id=core_country_id) AS country_code,
			(SELECT code FROM core_currency WHERE id=core_currency_id) AS currency_code
		FROM user_user uu
			INNER JOIN user_detail ud
				ON uu.id=ud.user_id
		WHERE uu.email=:email AND uu.password=:password
		LIMIT 1
		";
		
		$execSQL = $oPDOLink->prepare($sql);
		$execSQL->execute(array(
				':email'=>$this->_postDatas['formLoginFieldEmail'],
				':password'=>sha1($this->_postDatas['formLoginFieldPassword'].'-k3P[8x&')
		));
		$row = $execSQL->fetch(PDO::FETCH_ASSOC);
		if(isset($row['is_active']) and $row['is_active']==false){
			$message['state'] = 'account_not_activated';
			$message['css_class'] = 'warning-message';
			$message['translation_code'] = 'messageLogin_accountNotActivated';
			return $message;
		} else if(isset($row['email'])){
			unset($_SESSION['features']);
			$_SESSION['features'] = $this->getFeatures($row['id']);
			$row['state'] = 'success';
			return $row;
		} else{
			$message['state'] = 'bad_login_or_password';
			$message['css_class'] = 'failed-message';
			//FIX translate this message
			$message['translation_code'] = "messageLogin_badLoginOrPassword";
			return $message;
		}
	}
  //ENDOF login()
	
  public function changePassword($user_id, $data){
		$this->_userId = $user_id;
		$this->_data = $data;
		$oPDOLink = ClassConfig::databaseConnect();
		
		$sql="
		SELECT password
		FROM user_user
		WHERE id=:user_id;
		";
		
		$execSQL = $oPDOLink->prepare($sql);
		$execSQL->execute(array(':user_id'=>$this->_userId));
		$row = $execSQL->fetch(PDO::FETCH_ASSOC);
		
		if(isset($row['password']) && sha1($this->_data['oldPassword'].'-k3P[8x&') != $row['password']){
			$message['state'] = 'failed_bad_password';
		} else if($this->_data['newPassword'] != $this->_data['confirmPassword']){
			$message['state'] = 'failed_password_confirm';
		} else{
		
		$sql="
		UPDATE user_user
		SET password=:password
		WHERE id=:user_id;
		";
		
		$execSQL = $oPDOLink->prepare($sql);
		if($execSQL->execute(array(
				':user_id'=>$this->_userId,
				':password'=>sha1($this->_data['newPassword'].'-k3P[8x&')
		))){
			$message['state'] = 'success';
		} else{
			$message['state'] = 'failed';
		}
		}
		return $message;
	}
}
