<?php
use \Models\User;

class Account {

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

		// Security headers
		header("Content-Security-Policy: script-src 'self' 'unsafe-inline' https://apis.google.com http://ajax.googleapis.com https://ajax.googleapis.com", true);
		header("X-Frame-Options: DENY", true);
		header("X-Content-Type-Options: nosniff", true);

	}

	/**
	 * check login state
	 * @return bool
	 */
	static public function isLoggedIn() {

		$f3 = \Base::instance();
		new DB\SQL\Session($f3->get('DB'), 'mysa_sessions', false);

		if ($f3->exists('SESSION.user_id')) {
			$user = new User();
			$user->load(array('_id = ?',$f3->get('SESSION.user_id')));
			if(!$user->dry()) {
				$f3->set('USER',$user);
				return true;
			}
		} elseif ($f3->exists('COOKIE.mysa_l')) {
			$user = new User();
			$user = $user->load(array('psid = ?',Utils::Decrypt($f3->get('COOKIE.mysa_l'))));
			if (!$user->dry()){
					$f3->set('SESSION.user_id',$user->_id);
					$f3->set('USER',$user);
					return true;
			}

		}
		return false;
	}

	/**
	 * @param $f3 \Base
	 */
	public function getLogin($f3) {
		$this->clearSession($f3);

		// Set template and theme (if not default)
		$config = new \Models\Config();
		$config->load(array('_id=?',1), null, 3600);
		if ($config->site_template != null) $f3->set('UI','ui/'.$config->site_template.'/');
		if ($config->site_theme != null) $f3->set('THEME',$config->site_theme);

		$ret = $f3->get('GET.ret') ? $f3->get('GET.ret') : '';
		$f3->set('return', $ret);

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

	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function postLogin($f3,$params) {
		if ($f3->exists('POST.username') && $f3->exists('POST.password')) {
			new DB\SQL\Session($f3->get('DB'), 'mysa_sessions', false);

			$user = new User();
			$user->load(array('username = ? OR mail = ?',$f3->get('POST.username'),$f3->get('POST.username')));
			if (!$user->dry()) {
				$valid = false;
				$valid = $user->verify_password($f3->get('POST.password'), $user->password);
				if($valid) {
					if ($f3->exists('POST.remember_me') && ($f3->get('POST.remember_me') == '1')){
						try {
						$user->psid = session_id();
						setcookie('mysa_l',Utils::Encrypt(session_id()),strtotime('+30 days'));
						} catch (Exception $e){
							\Utils::Logger('postLogin: Error setting remember_me - '.$e);
						}
					} elseif ($user->psid != ''){
						$user->psid = '';
					}
					$f3->set('SESSION.user_id',$user->_id);
					$ret = $f3->get('POST.return') ? urldecode($f3->get('POST.return')) : '';
					if (!$f3->exists('POST.test')){

						if (empty($user->last_login)) $this->_firstLoginMessage($f3, $user, $ret);

						$user->last_login = time();
						$user->save();

						if ($user->role >= 8){
							empty($ret) ? $f3->reroute('/index.php') : $f3->reroute($ret);
						} else {
							empty($ret) ? $f3->reroute('/index.php?ads&list') : $f3->reroute($ret);
						}
					}
				}
			}
			$fm = new FlashMessage();
			$fm->addMessage($f3->get('lang_wrong_username_password'), 'danger');
		}
		$ret = $f3->get('GET.ret') ? $f3->get('GET.ret') : '';
		$f3->set('return', $ret);
		echo Template::instance()->render('login.html');
	}

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

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

		if ($f3->exists('POST.mail')) {
			$user = new User();
			$user->load(array('mail = ?',$f3->get('POST.mail')));
			$fm = new FlashMessage();
			if (!$user->dry()) {
				$newPass = sha1((uniqid()));
				$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https://' : 'http://';
				$message = $f3->get('lang_a_request_to_reset_your_mysimpleads_password_was_made__your_new_password_is') . ': ' .
						$newPass .'<br />' . $protocol .$f3->get
								('HOST').$f3->get('BASE').'/index.php?login';
				$subject = $f3->get('lang_recover_password') . '|mySimpleAds';
				if (Utils::SendMail($message, $subject, $user->mail)) {
					$user->password=$newPass;
					$user->save();
					$fm->addMessage('New password sent', 'success');
				} else {
					$fm ->addMessage('Unable to send new password', 'danger');
				}

			} else {
				$fm ->addMessage('No account found with that e-mail', 'danger');
			}

		}
		$ret = $f3->get('GET.ret') ? $f3->get('GET.ret') : '';
		$f3->set('return', $ret);
		echo Template::instance()->render('login.html');
	}

	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	public function logout($f3,$params) {
		new DB\SQL\Session($f3->get('DB'), 'mysa_sessions', false);
		$this->clearSession($f3);
		$f3->reroute('/index.php?login');
	}


	/**
	 * @param $f3 \Base
	 * @param $params
	 */
	private function clearSession($f3){
		$f3->clear('SESSION');
		if ($f3->exists('COOKIE.mysa_l')) {
			$user = new User();
			$user = $user->load(array('psid = ?',Utils::Decrypt($f3->get('COOKIE.mysa_l'))));
			if(!$user->dry()) {
				$user->psid = '';
				$user->save();
			}
			setcookie('mysa_l',session_id(),strtotime('-1 year'));
		}

	}


	/**
	 * @param $f3 \Base
	 * @param $user \Models\User
	 * @param $ret string
	 */
	private function _firstLoginMessage($f3, $user, $ret){

		$message = $f3->get('lang_hi').', <br />';
		$fm = new FlashMessage();

		switch ($user->role){
			case 1:
				if (empty($ret)){
					$message .= '<strong>'.$f3->get('lang_welcome_to_our_ad_console') .'</strong>.';
				} else {
					$message .= '<strong>'.$f3->get('lang_welcome') .'</strong>. '.$f3->get('lang_to_get_started__go_ahead_and_update_your_ad__once_it_s_approved_it_will_start_showing_').' '.$f3->get('lang_if_you_modify_the_ad_again__it_will_need_to_be_re_approved_');
				}
				break;
			case 9:
				$message .= '<strong>'.$f3->get('lang_welcome_to_mysimpleads').'</strong>. '.$f3->get('lang_to_get_started__go_ahead_and_create_your_first_ad').' : <a href="index.php?ads&create">'.$f3->get('lang_create_an_ad').'</a>. '.$f3->get('lang_if_you_have_any_questions__you_can_click_the___on_the_top').'.';
				break;
			default:
				$message .= '<strong>'.$f3->get('lang_welcome_to_mysimpleads').'</strong>. '.$f3->get('lang_if_you_have_any_questions__you_can_click_the___on_the_top').'.';
		}
		$fm->addMessage($message, 'info');

	}

} 
