<?php

class ClassApp extends ClassUser {
  public function __construct(){}
  public function __destruct(){}
  
	private function _checkIfVipOfferActive(){
		$config = ClassConfig::getConfig();
    	//$oPDOLink = ClassConfig::databaseConnect();
		if($config['is_vip_offer_active']==='true'){
			return true;
		} else {
			return false;
		}
	}
	
	private function _checkIfEverythingForFreeActive(){
		$config = ClassConfig::getConfig();
    	//$oPDOLink = ClassConfig::databaseConnect(); //FIX is this code still needed?
		if($config['is_everything_for_free_offer_active']=='true'){
			return true;
		} else {
			return false;
		}
	}
	
	public function listActiveApps(){
		$oPDOLink = ClassConfig::databaseConnect();
		$sql = "
		SELECT *
		FROM app_app
		WHERE is_active=TRUE;
		";
		$execSQL = $oPDOLink->prepare($sql);
		$execSQL->execute(array());
		$rows = $execSQL->fetchAll(PDO::FETCH_ASSOC);
		return $rows;
	}
	
	private function _checkIfUserReferralExists($email_referral){
		$oPDOLink = ClassConfig::databaseConnect();
		$sql = "SELECT id FROM user_user WHERE email=:email LIMIT 1;";
		$execSQL = $oPDOLink->prepare($sql);
		$execSQL->execute(array(':email'=>$email_referral)); 
		$row = $execSQL->fetch(PDO::FETCH_ASSOC);
		return $row['id'];
	}
	
	private function _createDefaultPublicProfileForNewUser($user_id, $email, $country_id, $lang_id, $description, $files){
		$oPDOLink = ClassConfig::databaseConnect();
		$sql = "
		INSERT INTO public_profile(user_id, email, country_id, lang_id, description, photo_name, photo_type, photo_size, photo)
		VALUES(:user_id, :email, :country_id, :lang_id, :description, :photo_name, :photo_type, :photo_size, :photo);
		";
		$execSQL = $oPDOLink->prepare($sql);
		$execSQL->execute(array(
				':user_id'=>$user_id,
				':email'=>$email,
				':country_id'=>$country_id,
				':lang_id'=>$lang_id,
				':description'=>$description,
				':photo_name'=>$files['form_addPublicProfile_photo']['name'],
				':photo_type'=>$files['form_addPublicProfile_photo']['type'],
				':photo_size'=>$files['form_addPublicProfile_photo']['size'],
				':photo'=>base64_encode(file_get_contents($files['form_addPublicProfile_photo']['tmp_name']))
		));
	}
	
  public function createUser($data, $files){
		$this->_data = $data;
		$config = ClassConfig::getConfig();
		$oPDOLink = ClassConfig::databaseConnect();
		
		if($this->_data['register_form_emailReferral'] != ''){
			$user_referral_id = $this->_checkIfUserReferralExists($this->_data['register_form_emailReferral']);
			if($user_referral_id == false){
				$message['state']='failed';
				$message['css_class']='failed';
				$message['translation_code'] = 'checkEmailReferralDoesNotExists';
				return $message;
			}
		} else {
			$user_referral_id = 1;
		}
		
		if($this->_data['register_form_password'] != $this->_data['register_form_passwordConfirm']){
			$message['state']='failed';
			$message['css_class']='failed';
			$message['translation_code'] = 'checkRegisterForm_notSamePassword';
			return $message;
		}
		else {
			//get currency
			$sql="
			SELECT core_currency_id AS id
			FROM core_country
			WHERE id=:country_id
			LIMIT 1
			";
			$execSQL = $oPDOLink->prepare($sql);
			$execSQL->execute(array(':country_id'=>$this->_data['country']));
			$currency_row = $execSQL->fetch(PDO::FETCH_ASSOC);
			
			//get theme design
			$sql="
			SELECT id
			FROM core_theme
			WHERE code=:code_theme
			LIMIT 1
			";
			$execSQL = $oPDOLink->prepare($sql);
			$execSQL->execute(array(':code_theme'=>'default')); //TODO theme may be a variable
			$theme_row = $execSQL->fetch(PDO::FETCH_ASSOC);
			$rand = (string) rand();
			$microtime = (integer) time();
			$activation_code = $rand . $microtime;
			$sql="
			INSERT INTO user_user(firstname, lastname, email, password, core_country_id, core_currency_id, core_lang_id, core_theme_id, activation_code)
			VALUES(:firstname, :lastname, :email, :password, :core_country_id, :core_currency_id, :core_lang_id,:core_theme_id, :activation_code)
			";
			$execSQL = $oPDOLink->prepare($sql);
			if($execSQL->execute(array(
					':firstname'=>$this->_data['register_form_firstname'],
					':lastname'=>$this->_data['register_form_lastname'],
					':email'=>$this->_data['register_form_email'],
					':password'=>sha1($this->_data['register_form_password'].'-k3P[8x&'),
					':core_country_id'=>$this->_data['country'],
					':core_currency_id'=>$currency_row['id'],
					':core_lang_id'=>$this->_data['lang'],
					':core_theme_id'=>1, //$theme_row['id'],
					':activation_code'=> (string) $activation_code
			))){
				$newUserId = $oPDOLink->lastInsertId('user_user_id_seq');
				//$isVipOfferActive = $this->_checkIfVipOfferActive();
				//$isEverythingForFreeActive = $this->_checkIfEverythingForFreeActive();
				// core user detail
				
				$sql="
				INSERT INTO user_detail(user_id, user_referral_id)
				VALUES (:user_id, :user_referral_id)
				";
				$execSQL = $oPDOLink->prepare($sql);
				$execSQL->execute(array(
						':user_id'=>$newUserId,
						':user_referral_id'=>$user_referral_id,
						//':is_premium'=>($isVipOfferActive==true)?true:0,
						//FIX get the lifespan of VIP offer from SQL table core_config
						//':is_premium_end_date'=>($isVipOfferActive==true && $isPromotionalCode==true)?date('Y-m-d', strtotime('+6 months')):null,
						//':is_premium_end_date'=>($isVipOfferActive==true)?'2017-08-31':null,
				));
				
				// create a default public profile
				$this->_createDefaultPublicProfileForNewUser($newUserId, $this->_data['register_form_email'], $this->_data['country'], $this->_data['lang'], $this->_data['register_form_description'], $files);
				
				// defining database name of user for Premium abonement
				$db_name = "user_".$activation_code;
				
				$sql_createdb = "CREATE DATABASE ".$db_name;
				$execSQL = $oPDOLink->prepare($sql_createdb);
				$execSQL->execute(array());
			
				//TODO import data
				$oPDOPrivate = new PDO("pgsql:host=localhost;dbname=".$db_name.";user=".InterfacePostgreSQL::PG_USER.";password=".InterfacePostgreSQL::PG_PASSWORD);
				
				// $sql = file_get_contents(ClassConfig::getURLRoot('apps/install/install-v1.0.0.sql')); //DEV
				$sql = file_get_contents("/var/www/html/buo/apps/install/install-v1.0.0.sql"); //PROD
				$patterns = array();
				$patterns[0] = '/installuserbuoid/';
				$patterns[1] = '/installuserfirstname/';
				$patterns[2] = '/installuserlastname/';
				$patterns[3] = '/installuseremail/';
				
				$replacements = array();
				$replacements[0] = $newUserId;
				$replacements[1] = $this->_data['register_form_firstname'];
				$replacements[2] = $this->_data['register_form_lastname'];
				$replacements[3] = $this->_data['register_form_email'];
				ksort($patterns); ksort($replacements);
				$sql2 = preg_replace($patterns, $replacements, $sql);
				$oPDOPrivate->exec($sql2);
				
				// insert into user_detail SQL table
				$sql="
				UPDATE user_detail
				SET db_name=:db_name, db_host='localhost', db_user=:db_user, db_password=:db_password
				WHERE user_id=:user_id
				";
				$execSQL = $oPDOLink->prepare($sql);
				$execSQL->execute(array(
					':db_name'=>$db_name,
					':db_user'=>InterfacePostgreSQL::PG_USER,
					':db_password'=>InterfacePostgreSQL::PG_PASSWORD,
					':user_id'=>$newUserId,
				));
				
				// features for user 
				/*
				TODO: Get the list of feature to create for user from the SQL table core_feature
				ie by a value which could be is_a_feature_for_registration=TRUE
				*/
				$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['register_form_email'], ':core_feature_code'=>'home'));
				$execSQL->execute(array(':email'=>$this->_data['register_form_email'], ':core_feature_code'=>'apps'));
				$execSQL->execute(array(':email'=>$this->_data['register_form_email'], ':core_feature_code'=>'my-profile'));
				$execSQL->execute(array(':email'=>$this->_data['register_form_email'], ':core_feature_code'=>'contact'));
				$execSQL->execute(array(':email'=>$this->_data['register_form_email'], ':core_feature_code'=>'logout'));
				
				$execSQL->execute(array(':email'=>$this->_data['register_form_email'], ':core_feature_code'=>'social-network'));
				$execSQL->execute(array(':email'=>$this->_data['register_form_email'], ':core_feature_code'=>'my-public-profile'));
				$execSQL->execute(array(':email'=>$this->_data['register_form_email'], ':core_feature_code'=>'people-i-may-know'));
				$execSQL->execute(array(':email'=>$this->_data['register_form_email'], ':core_feature_code'=>'connection-requests'));
				$execSQL->execute(array(':email'=>$this->_data['register_form_email'], ':core_feature_code'=>'my-network'));
				
				$message['user_id'] = $newUserId;
				$message['activation_code'] = $activation_code;
				$message['state'] = "success";
				$message['css_class'] = 'success-message';
				$message['translation_code'] = 'register_form_success';
				return $message;
			} else {
				$message['state']='failed';
				$message['css_class'] = 'failed-message';
				$message['translation_code'] = 'register_form_failed';
				return $message;
			}
		}
  }
  
	public function activateUser($activation_code){
		$this->_activationCode = (string) $activation_code;
		$oPDOLink = ClassConfig::databaseConnect();
		
		$sql="
		UPDATE user_user
		SET is_active=TRUE
		WHERE activation_code=:activation_code
		";
		$execSQL = $oPDOLink->prepare($sql);
		if($execSQL->execute(array(':activation_code'=>$this->_activationCode))){
			$sql="
			SELECT firstname, email
			FROM user_user
			WHERE activation_code=:activation_code
			";
			$execSQL = $oPDOLink->prepare($sql);
			$execSQL->execute(array(':activation_code'=>$this->_activationCode));
			$row = $execSQL->fetch(PDO::FETCH_ASSOC);
			
			$message['firstname'] = $row['firstname'];
			$message['email'] = $row['email'];
			$message['state'] = 'success';
			$message['css_class'] = 'success-message';
			$message['translation_code'] = 'message_activateUserSuccess';
		} else {
			$message['state'] = 'failed';
			$message['css_class'] = 'failed-message';
			$message['translation_code'] = 'message_activateUserFailed';
		}
		return $message;
		
	}

	public function listUsersWithActivationCodeAndActivated(){
		$oPDOLink = ClassConfig::databaseConnect();
		$sql = "
		SELECT activation_code
		FROM user_user
		WHERE activation_code!='no activation code needed'
			AND is_active=TRUE;
		";
		$execSQL = $oPDOLink->prepare($sql);
		$execSQL->execute(array());
		$users = $execSQL->fetchAll(PDO::FETCH_ASSOC);
		return $users;
	}

}