<?php
namespace controllers;

use models\Page;
/**
 * Settings controller
 * @author Jérôme Brilland
 * @version 2.1
 * @copyright (c) 2019-2022, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class SettingsController extends \ActionController {

    protected function beforeFilter() {
        $authorization = \IoC::resolve( 'authorization' );
        $authorization->authorize( 'manage_settings' );
    }

    public function doIndex() {
        $this->settings = \IoC::resolve( 'settings' );
        $i18n = \IoC::resolve( 'i18n' );
        $this->title = $i18n->__( 'settings' );
        $this->showHomepageControl = true;
        $eventMediator = \IoC::resolve( 'eventmediator' );
        $eventMediator->trigger( 'before_show_settings', $this );
        $this->render( 'settingsform.html' );
    }

    public function doUpdate() {
        $configurationHandler = \IoC::resolve( 'databaseConfigurationHandler' );
        $settings = new \Configuration( $configurationHandler );
        $settings['site_title'] = $this->request->getParameters()->getString( 'site_title' );
        $settings['site_description'] = $this->request->getParameters()->getString( 'site_description' );
        $settings['from_name'] = $this->request->getParameters()->getString( 'from_name' );
        if ( $this->request->hasParameter( 'from_email' ) && ( !\Validator::validateEmail( $this->request->getParameter( 'from_email' ) ) ) ) {
            $this->flash['error'] = \IoC::resolve( 'i18n' )->__( 'invalid_email' );
            $this->redirect( BASE_URL . 'system/settings' );
        }
        $settings['from_email'] = $this->request->getParameter( 'from_email' );
        //$settings['administration_theme'] = $this->request->getParameters()->getString( 'administration_theme' );
        if ( $this->request->hasParameter( 'home_page' ) ) {
            $settings['home_page'] = $this->request->getParameters()->getInt( 'home_page' );
        }
        $configurationHandler->save();
        $this->flash['success'] = \IoC::resolve( 'i18n' )->__( 'settings_successfully_updated' );
        $this->redirect( BASE_URL . 'system/settings' );
    }
}
