<?php

class Profiles extends Controller{

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

		$user = new \Models\User();
		$user->load(array('_id = ?', $f3->get('USER')->_id));
		if ($user->dry()) $f3->reroute('/index.php');

		// Check for DEMO settings
		if ($f3->get('DEMO') == 1) {
			$user->api = null;
		}

		$f3->set('res_user', $user);

		// Template settings
		$f3->set('active','profiles');
		$f3->set('inc','profiles-edit.html');
		$f3->set('inc_bottom', 'profiles-edit-bottom.html');
		$f3->set('title',$f3->get('lang_user_profile'));
		$f3->set('time_last_updated', date('Y/m/d H:i:s', $user->last_updated));


		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');

		$attributesToIgnore = array('last_login','api','psid','enabled','notes','role');
		$f3->set('PARAMS.id', $f3->get('USER')->_id);
		$params['id'] = $f3->get('USER')->_id;

		$user = new \Models\User();
		$user->load(array('_id = ?', $f3->get('USER')->_id));

		// Save or update the password
		$user_pass = '';
		if (trim($f3->get('POST.password_one')) == ''){
			if (!$user->dry()) $user_pass = $user->password;
		} else {
			$user_pass = $f3->get('POST.password_one');
		}
		$f3->set('POST.password', $user_pass);

		if ($f3->get('POST.username') == $user->username) {
			$f3->clear('POST.username');
			$attributesToIgnore[] = 'username';
		}

		try {
			$res_user = new \Models\User();
			$result = $res_user->post($f3, $params, true, $attributesToIgnore);

			$result ? $f3->reroute('/index.php?profile') : $f3->reroute('/index.php?profile');
		} catch (Exception $e){
			Utils::Logger('postEdit:Error posting profile - '.$e);
		}

	}

}