<?php

class Composer_Admin extends Controller {

	private $model_composer;

	function __construct() {
		parent::__construct(dirname(__DIR__));
		$this->model_composer = $this->loadModel('composer_model');
	}

	public function __Register() {
		$this->RegisterView(__CLASS__ .'::composer', ['composer_view' => ['render_check', 'render_iframe', 'render_iframe2']]);
	}
	
	// install, upgrade composer,  install/upgrade vendor files
	/** staff */
	public function composer($action = '') {
		$installed = $this->model_composer->GetInstalledVersion();
		$available = $this->model_composer->GetAvailableVersion();
		$param = $this->param('param', '');

		$res = $this->DefaultResult(__METHOD__);
		$res['param'] = $param;
		switch($action) {
			case 'upgrade':		// install/upgrade composer
				$res['template'] = 'composer_iframe';
				break;

			case 'upgrade-iframe':		// install/upgrade composer
				while (ob_get_level() > 0) {
					ob_end_flush();
				}
				$res = $this->model_composer->InstallLatestVersion($param);
				// send message back to parent if failed - for noty
				exit;

			case 'package-iframe':		// install/upgrade composer packages
				while (ob_get_level() > 0) {
					ob_end_flush();
				}
				$res = $this->model_composer->UpdatePackages($param);
				// send message back to parent if failed - for noty
				exit;
			
			case 'dependencies':		// install packages
				$res['template'] = 'composer_iframe2';
				break;
				
			case '':
				$dparam = ($param != '') ? '?param=' . rawurlencode($param) : '';
				if ($installed === FALSE) {		// not installed: redirect to install
					$this->redirect('/admin/composer/upgrade' . $dparam);
				} elseif (version_compare($installed, $available['version']) < 0) {	// ask to install
					$res['template'] = 'composer_check';
					$res['version_current'] = $installed;
					$res['version_new'] = $available['version'];
				} else {						// all ok, move on to next screen
					$this->redirect('/admin/composer/dependencies' . $dparam);
				}
				break;
		}
		return $res;
	}

}