<?php

class updateadmin_controller extends Controller {

	private $model_update;

	public function __construct() {
		parent::__construct(dirname(__DIR__));
		$this->model_update = $this->LoadModel('update_model');
		$this->_loadAll();
		hook_add('modules.field.list', [$this, '__list_fields'], 99);
	}

	public function __Register() {
		$this->RegisterView(__CLASS__ .'::update', ['update_view' => ['update_summary', 'update_install']]);
	}

	public function __list_fields(&$result) {
		$this->model_update->CustomFields($result);
	}

	protected function _loadAll($refresh = FALSE) {
		// do we have some urls? load each one
		$active_settings = $GLOBALS['loader']->LoadModuleSettings('update');
		$this->model_update->checkCatalog($active_settings['repo'] ?? '', $refresh);
	}

	/** admin setup */
	public function update($module = '', $param2 = '') {
		$res = $this->DefaultResult(__METHOD__);
		if ($module == 'check-now') {
			$this->_loadAll(TRUE);
			return [
//				'result' => -9999,
//				'message' => 'Catalog of Updates has been refreshed',
				'redirect' => '/admin/update',
			];
		} elseif ($module == 'install') {
/*			$param2 = str_replace(['..', '\\', '/', '|', '<', '>', '&'], '', $param2);
			$res = $this->model_update->performInstall($param2);
			error_log(json_encode($res));
			if (is_string($res)) {
				$res = [
					'result' => 9524,
					'message' => $res,
				];
			} elseif ($res === TRUE) {
				$res = [
					'result' => -9999,
					'message' => 'Module installed',
					// reload page
				];
			} */
			$modulename = str_replace(['..', '\\', '/', '|', '<', '>', '&'], '', $param2);
			$res['popup'] = [
				'module'	=> $modulename,
				'auth'		=> hook_execute('nonce.create', FALSE, 'update', $modulename),
				'title'		=> 'Installation Progress',
				'template'	=> 'update_install',
				'modal'		=> TRUE,
				'width'		=> 600,
				'button'	=> ['Close' => 'submit'],
			];
			return $res;
			
		} elseif ($module != '') {
			$module = str_replace(['..', '\\', '/', '|', '<', '>', '&'], '', $module);
			// update specified module
			$ok = $this->model_update->performUpdate($module);
			if ($ok === TRUE) {
			// reload datatable
				return [
					'result' => -9999,
					'message' => "Module \"{$module}\" has been updated successfully",
					'html' => [
						'field' => 'DataTables_Table_0',
						'action' => 'datatable.refresh',
					],
				];
			} elseif (is_string($ok)) {
				return [
					'result' => 9523,
					'message' => $ok,
				];
			} else {
				return [
					'result' => 9522,
					'message' => 'Unexpected Update error',
				];
			}
		}
		// updates are available for the following modules
		$this->_loadAll(FALSE);
		$res['template'] = 'update_summary';
		$res['lastcheck'] = $this->model_update->asDate();
		$res['datatable'] = $this->model_update->DataTable_Installable();
		$res['version']  = phpversion();
		if (function_exists('fpm_get_status')) {
			$res['version'] .= ' (FPM)';
		}
		return $res;
	}
	
	/** everyone */
	public function autologin() {
		header('Content-type: text/plain');
		$auth = $this->post('payload', '');
		// to do: get redirect url
		$payload = $this->model_update->Decrypt($auth);
			
		if ($payload !== FALSE) {
			$payload =  unpack('Vuser/Vexpiry/a4signature', $payload);
			if ($payload['signature'] == "pkp\0") {
				if ($payload['expiry'] < time() || time() < $payload['expiry'] + 300) {
					$user_id = $payload['user'];
					$params = new \StdClass;
					$params->user_id = $user_id;
					$user_info = hook_execute('login.verify', NULL, $params);
					if ($user_info !== NULL) {
						hook_execute('login', 0, $user_info);			// log in as user $user_id
					}
					$this->Redirect('/admin/settings');					// redirect to modules page
				}
			}
		}
	}

// show version on modules

// update all

}