<?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\Str;
use Vvveb\Sql\LanguagesSQL as LanguagesSQL;
use Vvveb\System\Event as Event;
use Vvveb\System\User\Admin;
use Vvveb\System\View as View;

class Base {
	function _init() {
		if (! $this->session->get('csrf')) {
			$this->session->set('csrf', Str::random());
		}

		$admin = Admin::current();

		if (! $admin) {
			return $this->requireLogin();
		}
	}

	function redirect($url = '/', $parameters = []) {
		$redirect = \Vvveb\url($url, $parameters);

		if ($redirect) {
			$url = $redirect;
		}

		$this->session->close();

		return header("Location: $url");
	}

	function __construct() {
		$view = View :: getInstance();

		$menu = include DIR_APP . 'menu.inc';

		$menu       = Event::trigger('admin', 'menu', $menu);
		$view->menu = $menu;

		$languages = new languagesSQL();
		/*
				$view->languages = [
			
					['language_id' => 1,
					'name' => 'english',
					'code' => 'en'],

					['language_id' => 2,
					'name' => 'romanian',
					'code' => 'ro'],
				];
		*/
		$view->languages = $languages->getAll();

		return;
		echo '<ul class="nav navbar-nav flex-column" >';
		$this->menu($this->menu);
		echo '</ul>';
		//die('test');
	}

	function menu($menu) {
		foreach ($menu as $menuEntry) {
			echo '<li>' . $menuEntry['name'];

			if (isset($menuEntry['items'])) {
				echo '<ul>';
				$this->menu($menuEntry['items']);
				echo '</ul>';
			}

			echo '</li>';
		}
	}

	/**
	 * Call this method if the action requires login, if the user is not logged in, a login form will be shown.
	 *
	 */
	function requireLogin() {
		$view = view :: getInstance();
		$view :: template('user/login.html');

		die(view :: getInstance()->render());
	}

	/**
	 * Call this function if the requeste information was not found, for example if the specifed news, image, profile etc is not found then call this function.
	 * It shows a "Not found" page and it also send 404 http status code, this is usefull for search engines etc.
	 *
	 * @param unknown_type $code
	 */
	function notFound($statusCode = 404, $service = false) {
		return front_controller::notFound($statusCode, $service);
	}
}
