<?php

class account_account extends controller {

// to do: migrate website from one server to another?

	public function __construct() {
		parent::__construct(dirname(__DIR__));
		hook_add('account.field.list', [$this, '__list_fields'], 1);
//		hook_add('account.field.update', [$this, '__data_entry_fields']);
		$this->account_model = $this->loadModel('account_model');
		
		$this->level = isset($_SESSION['current_user']) ? $_SESSION['current_user']['u_level'] : 0;
		$this->user_id = isset($_SESSION['current_user']) ? intval($_SESSION['current_user']['u_id']) : 0;
	}
	
	public function __Register() {
		$this->RegisterView(__CLASS__ .'::invite', ['account_view' => ['render_invite']]);
		$this->RegisterView(__CLASS__ .'::_new', ['account_view' => ['render_new','render_invitepopup']]);
		$this->RegisterView(__CLASS__ .'::_list', ['account_view' => ['render_list']]);
		$this->RegisterView(__CLASS__ .'::edit', ['account_view' => ['render_edit','render_invitepopup']]);
		$this->RegisterView(__CLASS__ .'::view', ['account_view' => ['render_view']]);

		$items = hook_execute('auth.*.css', []);
		foreach($items as $item) {
			$this->IncludeFile($item);
		}
	}
	
	// Display your profile
	// should not edit here
	/** member */
	public function index() {
        //login from google.. or other type of third-party user system?  Edit not possible
        if ($this->level == 3) {
            $this->redirect('/account/view');
        } else {
            $this->redirect('/account/edit');
        }
	}
	
/*	// if member, then invitee has same features as current, and is a subuser of current group -- access same section of file system, same domains, same databases
	// if staff/admin then specify features, and is in new group, or add to an existing group
	/** member * /
	public function invite() {
		$res = $this->DefaultResult(__METHOD__);
		$res['template'] = 'account_invite';
		return $res;
	} */
	
	// A person has been invited to join. This is the signup process:
	/** everyone */
	public function invite($hash = '') {
		$res = $this->DefaultResult(__METHOD__);
		
		if ($hash == '') die('missing hash');
		
		$invite = $this->account_model->invite_get($hash);
		if ($invite->empty()) {
			die('invalid hash');
		}
		// level 1 user to be created:
		$auth = hook_execute('nonce.create', FALSE, 'loglevel', 1, 86400, TRUE);		// single use, expires in 24hr

		$bounce = '/bouncing';
		$params = [
			'bounce' => $bounce,
			'user_id' => $invite->ui_user_id,				// are we creating a new user, or a new login for an existing user
			'auth' => $auth,
		];
		$handlers = hook_execute('auth.*.login', [], $params);
		
		$callback = NULL;
		foreach($handlers as $module => $info) {
			if (isset($info['register'])) $callback = $info['register'];
			if (!empty($info['button'])) {
				$list[] = ['link' => $info['link'], 'value' => $info['button']];
			}
		}
		if (is_callable($callback)) {
			$param = [&$res];
			call_user_func_array($callback, $param);
		}
		
		$res['email'] = $invite->ui_email;
		$res['provider'] = $list;
		$res['template'] = 'account_invite';
		$res['postlink'] = '';
		return $res;
	}
	
	public function invite_POST($hash = '') {
		if ($hash == '') die('missing hash');
		
		$invite = $this->account_model->invite_get($hash);
		if ($invite->empty()) {
			die('invalid hash');
		}

		$params = [
			'user_id' => $invite->ui_user_id,				// are we creating a new user, or a new login for an existing user
		];
		$handlers = hook_execute('auth.*.login', [], $params);
		
		$callback = NULL;
		foreach($handlers as $module => $info) {
			if (isset($info['register_post'])) {
				$callback = $info['register_post'];
				break;
			}
		}
		$res = [];
		if (is_callable($callback)) {
			$param = [&$res, $invite->ui_user_id];
			call_user_func_array($callback, $param);
		}
		return $res;
	}

	/** staff */
	public function _new() {
		$res = $this->DefaultResult(__METHOD__);
		$this->account_model->AssembleFieldlist($res);
		$res['template'] = 'account_new';
		return $res;
	}

	// if client then username is "clientusername-child",  and specify parent-id
	// also do a realtime check if linux username (or email) is taken
	public function _new_post() {
		$post = $this->post();
		$res = $this->account_model->createAccount($post);
		return $res;
	}

	/** staff */
	public function _list($param = '') {
		$res = $this->DefaultResult(__METHOD__);
		$param = strtolower($param);
		
		$rep = new ReportObject;
		hook_execute('account.field.list', $rep);
		if ($param == 'all') {
			return $this->account_model->UserList($rep);
		}
		$rep->asDataTablesDefinition($res);
		$res['template'] = 'account_list';
		return $res;
	}
	
	// what fields should be listed at /account/list ? 
	public function __list_fields(&$result) {
		$this->account_model->CustomFields($result);
	}
	
	/** member */
	public function edit() {
        if ($this->level == 3) {
            $this->redirect('/account/view');
        }
	// if not staff, then can only edit/view own profile,  otherwise any.
		$res = $this->DefaultResult(__METHOD__);
		$this->account_model->AccountProfile($res, $this->user_id, TRUE);
		$res['template'] = 'account_edit';
		return $res;
	}

	/** member */
	public function view() {
	// if not staff, then can only edit/view own profile,  otherwise any.
		$res = $this->DefaultResult(__METHOD__);
		$this->account_model->AccountProfile($res, $this->user_id, FALSE);
		$res['template'] = 'account_view';
		return $res;
	}

	
	//to do: display Noty when updated
	public function edit_POST() {
		$post = $this->post();
		$id = $post['id'];
		$auth = hook_execute('nonce.verify', FALSE, 'account', $id, $post['auth']);
		if (!$auth) return 0;
		$this->account_model->AccountProfile($res, $id, TRUE, TRUE);
		
		$action = isset($post['action']) ? $post['action'] : '';
		if ($action == 'invite') {
			//to do: generate a popup, allowing an email address to be entered
			return $this->account_model->Invite_popup($id, $post['auth']);
		} elseif ($action == 'send-invite') {
			// create a login to the same account (on account/edit)
			$email = empty($post['email']) ? '' : trim($post['email']);
			$hostname = $this->hostname();
			return $this->account_model->Invite_Create($id, $email, $hostname);
		}
		if(isset($post['is_locked'])){
			$chek=$this->account_model->updateuser($id);
		}
		
		//to do: save name. primary email requires verification before being updated
		
		$data = $GLOBALS['loader']->getModuleList();
		foreach($data as $name => $module_info) {
			if (isset($post[$name]) && $name != 'account') {
				$this->account_model->SaveUserSettings($res, $name, $post[$name]);
			}
		}
		return 1;
	}
	
}