<?php

class Administrator extends AppModel {

	var $name = 'Administrator';

	var $locked = [ 'homepage' ];

	var $actsAs = [
		'Acl' => 'requester'
	];

	var $belongsTo = [
		'Group'
	];

	var $displayField = 'full_name';

	var $validate = [
		'username'         => [
			[ 'rule' => 'notBlank', 'message' => 'This field cannot be left blank' ],
			[ 'rule' => 'isUnique', 'message' => 'This username has already assigned to another administrator' ] ],
		'full_name'        => [ [ 'rule' => 'notBlank', 'message' => 'This field cannot be left blank' ] ],
		'password'         => [ [ 'rule' => 'notBlank', 'message' => 'This field cannot be left blank', 'on' => 'create' ] ],
		'password_confirm' => [ [ 'rule' => 'passwordMatch', 'message' => 'Passwords do not match', 'on' => 'update' ] ]
	];

	var $hasOne = [
		'Photo' => 'Upload gif png jpg jpeg'
	];

	var $invisible = [ 'style', 'customization', 'recovery_hash' ];

	function passwordMatch($field, $data) {
		return !isset($this->data['Administrator']['password']) || $this->data['Administrator']['password'] == $this->data['Administrator']['password_confirm'];
	}

	function beforeSave($options = []) {
		if (isset($this->data['Administrator']['password'])) {
			$this->data['Administrator']['password'] = Security::hash($this->data['Administrator']['password'], null, true);
		}
		if (isset($this->data['Administrator']['recovery_hash'])) {
			$this->data['Administrator']['recovery_hash'] = Security::hash($this->data['Administrator']['recovery_hash'], null, true);
		}
		if (!empty($this->data['Administrator']['id']) && empty($this->data['Administrator']['group_id'])) {
			$this->data['Administrator']['group_id'] = $_SESSION['Auth']['Administrator']['group_id'];
		}
		if (isset($this->data['Administrator']['is_active']) && !$this->data['Administrator']['is_active'] && isset($this->data['Administrator']['id']) && $this->data['Administrator']['id'] == $_SESSION['Auth']['Administrator']['id']) {
			$this->data['Administrator']['is_active'] = true;
		}
		return true;
	}

	function afterFind($results, $primary = false) {
		require VECTORCMS_ROOT . 'webroot/css/css.php';
		foreach ($results as $i => $result) {
			# Unserialize style #
			if (isset($result[$this->alias]['style'])) {
				if (!$style = @unserialize($result[$this->alias]['style'])) {
					$style = [];
				}
				$results[$i][$this->alias]['style'] = array_merge($defaultStyle, $style);
			}
			# Unserialize customizations #
			if (isset($result[$this->alias]['customization'])) {
				if (!$customization = @unserialize($result[$this->alias]['customization'])) {
					$customization = [];
				}
				$results[$i][$this->alias]['customization'] = array_merge($customization);
			}
		}
		return $results;
	}

	function parentNode() {
		if (!$this->id && empty($this->data)) {
			return null;
		}

		$data = empty($this->data)
			? $this->read()
			: $this->data;

		return !empty($data['Administrator']['group_id'])
			? [ 'Group' => [ 'id' => $data['Administrator']['group_id'] ] ]
			: null;
	}

	function getAssignable($model, $administrator_id) {
		return $this->find('list');
	}

	function getOwnable($model, $administrator_id) {
		return $this->find('list');
	}

	/**
	 * Send new password to administrator.
	 *
	 * @param array $administrator Array with administrator data.
	 * @param string $randomPass Random generated password.
	 *
	 * @return array The result of the cake email sending.
	 */
	public function sendNewPassword($administrator, $randomPass) {

		// Create an e-mail
		$email = new CakeEmail();
		$email
			->emailFormat('both')
			->template('newpass')
			->viewVars([ 'administrator' => $administrator, 'pass' => $randomPass ])
			->from([ 'admin@intellex.com' => 'CMS administration' ])
			->to($administrator['Administrator']['email'])
			->subject('Password recovery');

		return $email->send();
	}

	/**
	 * Create administrator from an Intellex authentication.
	 *
	 * @param array $user The user info.
	 *
	 * @return array|bool
	 * @throws Exception
	 */
	public function createAdministratorFromIntellexUser($user) {

		# Check if this is an existing user
		$existing = $this->find('first', [
			'recursive'  => -1,
			'conditions' => [
				'email' => $user['email'] ]
		]);

		# Do not change anything for existing users
		if (!$existing) {

			# Is Intellex email
			$intellex = preg_match_all('~@intellex.rs$~', $user['email']);

			# Initialize new admin
			$admin = [
				'id'        => null,
				'email'     => $user['email'],
				'group_id'  => $intellex ? 1 : 2,
				'username'  => $user['email'],
				'full_name' => $user['name'],
				'is_active' => (bool) $intellex
			];

			# Save
			$success = $this->save($admin);
			if ($success) {

				# Load the admin
				$admin = $this->find('first', $this->id);

				# If administrator is not from @intellex.rs domain
				if (!$intellex) {

					# Notify support that someone is requesting access to the CMS
					$email = new CakeEmail();
					$email
						->to('support@intellex.rs')
						->subject(__('New adminstrator request on %s VectorCMS', Configure::read('Website.title')))
						->send(__("A person with an email %s has requested an access to the %s CMS.\n\n%s\n\n--\nIntellex", $user['email'], Configure::read('Website.title'), BACK_BASE_URL . '/administrators/'));
				}

				# Return administrator
				return reset($admin);
			}
		}

		return reset($existing);
	}

	/**
	 * Create administrator from google user
	 *
	 * @param mixed $google The data from the Google authorization server.
	 *
	 * @return array|bool
	 * @throws Exception
	 */
	public function createAdministratorFromGoogleUser($google) {

		# Intellex or not
		$intellex = substr($google->email, -12) === '@intellex.rs';

		# Check if this is an existing user
		$existing = $this->find('first', [
			'recursive'  => -1,
			'conditions' => [
				'email' => $google->email ]
		]);

		# Do not change anything for existing users
		if (!$existing) {

			# Initialize new admin
			$admin = [
				'id'        => null,
				'email'     => $google->email,
				'group_id'  => $intellex ? 1 : 2,
				'username'  => $google->email,
				'full_name' => $google->givenName . ' ' . $google->familyName,
				'is_active' => (bool) $intellex
			];

			# Save
			$success = $this->save($admin);
			if ($success) {
				$id = $success[$this->alias]['id'];

				# Upload the picture from the google
				if (!empty($google->picture)) {
					ClassRegistry::init('Upload')->fromRemote($this->alias, $id, 'Photo', $google->picture, "admin-{$id}_google");
				}

				# Load the admin
				$admin = $this->find('first', $this->id);

				# If administrator is not from @intellex.rs domain
				if (!$intellex) {

					# Notify support that someone is requesting access to the CMS
					$email = new CakeEmail();
					$email
						->to('support@intellex.rs')
						->subject(__('New adminstrator request on %s VectorCMS', Configure::read('Website.title')))
						->send(__("A person with an email %s has requested an access to the %s CMS.\n\n%s\n\n--\nIntellex", $google->email, Configure::read('Website.title'), BACK_BASE_URL . '/administrators/'));
				}

				# Return administrator
				return reset($admin);
			}
		}

		return reset($existing);
	}

}
