<?php
namespace install\controllers;

use install\library\RequirementsChecker;
use install\services\Install;

/**
 * Install 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 InstallController extends \ActionController {

    protected function beforeFilter() {
        $language = \IoC::resolve( 'locale' );
        $i18n = \IoC::resolve( 'i18n' );
        $i18n->load( ROOT_DIR . 'install' . DS . 'i18n' . DS . $language . '.ini' );
    }

    public function doStep1() {}

    public function doStep2() {
        $language = $this->request->getParameters()->getString( 'language', null );
        if ( !empty( $language ) ) {
            $_SESSION['locale'] = $language;
            $i18n = \IoC::resolve( 'i18n' );
            $i18n->load( ROOT_DIR . 'install' . DS . 'i18n' . DS . $language . '.ini' );
        }
        $requirementsChecker = new RequirementsChecker();
        $this->requirements = $requirementsChecker->getRequirements();
        $this->showNextStep = !$requirementsChecker->hasErrors();
    }

    public function doStep3() {
        $this->baseURL = $this->getBaseURL();
        $this->databaseType = $this->request->getParameters()->getAlpha( 'database', 'mysql' );
    }

    public function doStep4() {
        $install = new Install( $this->request->getParameters()->getArray( 'database' ), $this->request->getParameters()->getArray( 'settings' ) );
        $install->perform( $this );
    }

    public function createDatabaseFailed( $error ) {
        $this->flash['error'] = $error;
        $this->redirect( '?rt=install/step3' );
    }

    public function installSucceeded() {
    }

    public function installFailed( $error ) {
        $this->flash['error'] = $error;
        $this->redirect( '?rt=install/step3' );
    }

    protected function getBaseURL() {
        $protocol = strtolower( substr( $_SERVER['SERVER_PROTOCOL'], 0, 5 ) ) == 'https://' ? 'https://' : 'http://';
        $directory = dirname( $_SERVER['PHP_SELF'] );
        $directory = ( $directory == '/' ) ? '' : $directory;
        $host = $_SERVER['HTTP_HOST'];
        return $protocol . $host . $directory . '/';
    }
}
