<?php defined('MW_INSTALLER_PATH') || exit('No direct script access allowed');

/**
 * DatabaseController
 * 
 * @package MailWizz EMA
 * @author Serban George Cristian <cristian.serban@mailwizz.com> 
 * @link http://www.mailwizz.com/
 * @copyright 2013-2014 MailWizz EMA (http://www.mailwizz.com)
 * @license http://www.mailwizz.com/license/
 * @since 1.0
 */
 
class DatabaseController extends Controller
{
    public function actionIndex()
    {
        if (!getSession('filesystem') || !getSession('license_data')) {
            redirect('index.php?route=filesystem');
        }
        
        $this->validateRequest();
        
        if (getSession('database')) {
            redirect('index.php?route=admin');
        }

        $this->data['breadcrumbs'] = array(
            'Database import' => 'index.php?route=database',
        );
        
        $this->render('database');
    }
    
    protected function validateRequest()
    {
        if (!getPost('next')) {
            return;
        }

        $dbHost = getPost('hostname');
        $dbName = getPost('dbname');
        $dbUser = getPost('username');
        $dbPass = getPost('password');
        $dbPrefix = getPost('prefix');
        
        if (empty($dbHost)) {
            $this->addError('hostname', 'Please provide your database hostname!');
        } elseif (!preg_match('/^([a-z0-9\_\-\.]+)$/i', $dbHost)) {
            $this->addError('hostname', 'The hostname must contain only letters, numbers, underscores, dashes and dots!');
        }
        
        if (empty($dbName)) {
            $this->addError('dbname', 'Please provide your database name!');
        } elseif (!preg_match('/^([a-z0-9\_]+)$/i', $dbName)) {
            $this->addError('dbname', 'Database name must contain only letters, numbers and underscores!');
        }
        
        if (empty($dbUser)) {
            $this->addError('username', 'Please provide your database access username!');
        }

        if (!empty($dbPrefix) && !preg_match('/^([a-z0-9\_]+)$/', $dbPrefix)) {
            $this->addError('prefix', 'Tables prefix must contain only lowecase letters, numbers and underscores!');
        }
        
        if ($this->hasErrors()) {
            return $this->addError('general', 'Your form has a few errors, please fix them and try again!');
        }
        
        try {
            $dbh = new PDO(sprintf('mysql:dbname=%s;host=%s', $dbName, $dbHost), $dbUser, $dbPass);
            $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (Exception $e) {
            return $this->addError('general', $e->getMessage());
        }
        
        $searchReplace = array(
            '{DB_HOST}'     => $dbHost,
            '{DB_NAME}'     => $dbName,
            '{DB_USER}'     => $dbUser,
            '{DB_PASS}'     => $dbPass,
            '{DB_PREFIX}'   => $dbPrefix,
        );
        
        $contents = @file_get_contents(MW_MAIN_CONFIG_FILE_DEFINITION);
        if (empty($contents)) {
            return $this->addError('general', 'Unable to open the definition configuration file!');
        } 
        
        $contents = str_replace(array_keys($searchReplace), array_values($searchReplace), $contents);
        if (!@file_put_contents(MW_MAIN_CONFIG_FILE, $contents)) {
            return $this->addError('general', 'Unable to write the configuration file!');
        }
        
        // try to force the mode of the file/dir
        @chmod(dirname(MW_MAIN_CONFIG_FILE), 0755);
        @chmod(MW_MAIN_CONFIG_FILE, 0555);
        
        setSession('config_file_created', 1);
        
        try {
            // Always make sure each FK constraint has the fk_ prefix to avoid some nasty bugs i have found across multiple shared hosts!!!
            $sqlFiles = array(
                MW_APPS_PATH . '/common/data/install-sql/schema.sql',
                MW_APPS_PATH . '/common/data/install-sql/insert.sql',
                MW_APPS_PATH . '/common/data/install-sql/country-zone.sql',
            );
            
            $dbh->exec('SET time_zone="+00:00"');
            $dbh->exec('SET NAMES utf8');
            $dbh->exec('SET SQL_MODE=""');
            
            foreach ($sqlFiles as $sqlFile) {
                $dbh->beginTransaction(); 
                $queries = CommonHelper::getQueriesFromSqlFile($sqlFile, $dbPrefix);
                if (empty($queries)) {
                    continue;
                }
                foreach ($queries as $query) {
                    $dbh->exec($query);
                } 
                $dbh->commit();  
            }

        } catch (Exception $e) {
            $dbh->rollBack();
            return $this->addError('general', $e->getMessage());
        }
        
        // insert the license info.
        $licenseData = (array)getSession('license_data', array());
        foreach ($licenseData as $key => $value) {
            $sql = '
            INSERT INTO `'.$dbPrefix.'option` SET 
                `category`      = "system.license",
                `key`           = :key,
                `value`         = :value,
                `is_serialized` = 0, 
                `date_added`    = NOW(), 
                `last_updated`  = NOW()
            ';
            $sth = $dbh->prepare($sql);
            $sth->execute(array(
                ':key'      => $key,
                ':value'    => $value,
            ));
        }
        
        // insert the version
        $sth = $dbh->prepare('
            INSERT INTO `'.$dbPrefix.'option` SET 
                `category`     = "system.common", 
                `key`          = "version", 
                `value`        = :v, 
                `date_added`   = NOW(), 
                `last_updated` = NOW()
        ');
        $sth->execute(array(':v' => MW_VERSION));
        
        setSession('databaseData', array(
            'DB_HOST'   => $dbHost,
            'DB_NAME'   => $dbName,
            'DB_USER'   => $dbUser,
            'DB_PASS'   => $dbPass,
            'DB_PREFIX' => $dbPrefix,
        ));
        setSession('database', 1);
    }
}