<?php

/**
 * Vvveb
 *
 * Copyright (C) 2020  Ziadin Givan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

namespace Vvveb\Controller;

use Vvveb\System\User\Admin;

//define('INSTALL_SQL_PATH', DIR_ROOT . 'install/sql/');
define('REQUIRED_EXTENSIONS', ['mysqli', 'xml', 'libxml', 'pcre',  'zip', 'dom', 'curl', 'gettext']);

class Index extends Base {
	function checkRequirements() {
		$notMet = [];

		if (version_compare(PHP_VERSION, MIN_PHP_VERSION) < 0) {
			$notMet[] = 'You need at least PHP ' . MIN_PHP_VERSION . ', your current version ' . PHP_VERSION;
		}

		foreach (REQUIRED_EXTENSIONS as $extension) {
			if (! extension_loaded($extension)) {
				$notMet[] = sprintf(__('PHP extension %s is not installed'), $extension);
			}
		}

		return $notMet;
	}

	function writeConfig($data) {
		$configFile = DIR_ROOT . 'config/db.php';
		file_put_contents($configFile, "<?php\n return " . var_export($data, true) . ';');
	}

	function index() {
		if (is_file(DIR_ROOT . 'config/db.php')) {
			header('Location: /');

			die('Already installed!');
		}

		$this->view->requirements = $this->checkRequirements();

		if ($this->request->post) {
			$host   = $this->request->post['host'];
			$user   = $this->request->post['user'];
			$pass   = $this->request->post['password'];
			$dbname = $this->request->post['database'];
			$prefix = $this->request->post['prefix'];
			$driver = 'mysqli';

			$data['default']              = $driver;
			$data['connections'][$driver] = $this->request->post;

			try {
				$import = new \Vvveb\System\Import\Sql($driver, $host, $dbname, $user, $pass, $prefix);
				$import->createDb($dbname);
				$this->writeConfig($data);
				$import->setPath(DIR_ROOT . "install/sql/$driver/import/");
				$import->createDb($dbname);
				$import->createTables();
				$import->insertData();
				$import->db->close();

				header('Location: ' . $_SERVER['REQUEST_URI'] . '?action=install');
			} catch (\Exception $e) {
				$this->view->errors[] = 'Db error: ' . $e->getMessage() . ' Error code:' . $e->getCode();
			}
		}
	}

	function install() {
		if ($this->request->post) {
			//set admin password
			$result = Admin::update($this->request->post, ['user' => 'admin']);

			header('Location: ' . preg_replace('@/install.*$@', '/admin/', $_SERVER['REQUEST_URI']));
		}

		$this->view->template('install.html');
	}
}
