<?php

class Users extends Controller{

	//! HTTP route pre-processor
	/**
	 * @param $f3 \Base
	 */
	function beforeroute($f3) {
		parent::beforeroute($f3);

		// Only super admins can use this class
		if ($f3->get('USER')->role < 9){
			$f3->error(403);
		}
	}

	/**
	 * @param $f3 \Base
	 */
	public function getIndex($f3){

		// Template settings
		$f3->set('active','users');
		$f3->set('inc','users.html');
		$f3->set('inc_bottom', 'users-bottom.html');
		$f3->set('title',$f3->get('lang_users'));

		// Load available users for listing
		$res_users = new \Models\User();
		$users = $res_users->find();

		$res_users = array();
		if ($users){
			foreach ($users as $user) {
				$res_user = array();
				$res_user['id'] = $user->_id;
				$res_user['username'] = '<a href="index.php?users&edit&'.$user->_id.'">'.$user->username.'</a>';
				$res_user['mail'] = $user->mail ? '<a href="mailto:'.$user->mail.'">'.$user->mail.'</a>' : '-';
				$res_user['last_login'] = $user->last_login ? date('Y/m/d H:i:s', $user->last_login) : '-';
				$res_user['role'] = \Models\User::getRoleName($user->role);
				$res_users[] = $res_user;
			}
		}
		$f3->set('res_users',$res_users);

		echo Template::instance()->render('layout.html');

	}

	/**
	 * @param $f3 \Base
	 */
	public function getCreate($f3){

		// Template settings
		$f3->set('active','users');
		$f3->set('inc','users-edit.html');
		$f3->set('inc_bottom', 'users-edit-bottom.html');
		$f3->set('title',$f3->get('lang_users'));

		$res_user = new \Models\User();
		$res_user->password = '1'; //Set password to set user login switch to yes
		$f3->set('res_user', $res_user);

		$f3->set('roles', \Models\User::getRoles());

		echo Template::instance()->render('layout.html');

	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function postCreate($f3, $params){

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1) $f3->reroute('/index.php?users&list');

		// Make sure they entered a password if they allowed login
		if ($f3->get('POST.allow_login') == '1'){
			if ((trim($f3->get('POST.password_one')) == '') || (trim($f3->get('POST.password_confirm') == ''))){
				$msg = \FlashMessage::instance();
				$msg->addMessage("Please enter a password.", 'danger');

				// Template settings
				$f3->set('active','users');
				$f3->set('inc','users-edit.html');
				$f3->set('inc_bottom', 'users-edit-bottom.html');
				$f3->set('title',$f3->get('lang_users'));

				$res_user = new \Models\User();
				$res_user->copyfrom('POST');
				$res_user->password = '1'; //Set password to set user login switch to yes
				$f3->set('res_user', $res_user);

				$f3->set('roles', \Models\User::getRoles());

				echo Template::instance()->render('layout.html');

				return;
			}

			$email = $f3->get('POST.mail') ? $f3->get('POST.mail') : '';
			$apikey = sha1(mt_rand().$email);
			$f3->set('POST.api', $apikey);
			$f3->set('POST.password', $f3->get('POST.password_one'));
		}

		$result = false;
		try {

			$user_res = new \Models\User();
			$result = $user_res->post($f3, $params, false);

			if (($result) && ($f3->exists('POST.test'))) return;
			$result ? $f3->reroute('/index.php?users&list') : $f3->reroute('/index.php?users&create');
		} catch (Exception $e){
			Utils::Logger('postCreate:Error posting user - '.$e);
		}

		// Template settings
		$f3->set('active','users');
		$f3->set('inc','users-edit.html');
		$f3->set('inc_bottom', 'users-edit-bottom.html');
		$f3->set('title',$f3->get('lang_users'));

		$res_user = new \Models\User();
		$res_user->copyfrom('POST');
		$res_user->password = '1'; //Set password to set user login switch to yes
		$f3->set('res_user', $res_user);

		$f3->set('roles', \Models\User::getRoles());

		echo Template::instance()->render('layout.html');
		return;

	}


	/**
	 * @param $f3 \Base
	 */
	public function getEdit($f3){

		$id = $f3->get('PARAMS.id');
		$res_user = new \Models\User();
		$res_user->load(array('_id = ?', $id));
		if ($res_user->dry()) $f3->reroute('/index.php?users&list');
		$f3->set('res_user', $res_user);

		// Template settings
		$f3->set('active','users');
		$f3->set('inc','users-edit.html');
		$f3->set('inc_bottom', 'users-edit-bottom.html');
		$f3->set('title',$f3->get('lang_users'));

		$f3->set('time_last_updated', date('Y/m/d H:i:s', $res_user->last_updated));

		$f3->set('roles', \Models\User::getRoles());

		echo Template::instance()->render('layout.html');

	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function postEdit($f3, $params){

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1) $f3->reroute('/index.php?users&list');

		// Save or update the password
		$user_pass = '';
		if ($f3->get('POST.allow_login') == '1'){
			if (trim($f3->get('POST.password_one')) == ''){
				$user = new \Models\User();
				$user->load(array('_id = ?', $f3->get('PARAMS.id')));
				if (!$user->dry()) $user_pass = $user->password;
			} else {
				$user_pass = $f3->get('POST.password_one');
			}
		}
		$f3->set('POST.password', $user_pass);

		try {
			$res_user = new \Models\User();
			$result = $res_user->post($f3, $params, true, array('last_login','api','psid'));

			$result ? $f3->reroute('/index.php?users&list') : $f3->reroute('/index.php?users&edit&'.$f3->get('PARAMS.id'));
		} catch (Exception $e){
			Utils::Logger('postEdit:Error posting user - '.$e);
		}

	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function postDelete($f3, $params){

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1) $f3->reroute('/index.php?users&list');

		try {

			// Remove any user info from ads
			$userId = $params['id'];
			$ads_res = new \Models\Ad();
			$ads = $ads_res->find(array('advertiser = ? OR user_id = ?',$userId, $userId));
			if (!empty($ads)){
				foreach ($ads as $ad) {
					$a = new \Models\Ad();
					$a->load(array('_id = ?', $ad->_id));
					try {
						if ($ad->advertiser->_id == $userId) $a->advertiser = null;
						if ($ad->user_id->_id == $userId) $a->user_id = $f3->get('USER');
					} catch (\Exception $e) {}
					$a->save();
				}
			}

			$user = new \Models\User();
			$result = $user->delete($f3, $params);
			echo $result;
		} catch (Exception $e){
			Utils::Logger('postDelete:Error deleting user - '.$e);
		}

	}

}
