<?php

class InstallController extends BaseController
{
    private $json;

    public function __construct()
    {

        $this->json = [
            'status'  => false,
            'message' => ''
        ];
    }

    private function getExtensions(){

        clearstatcache(true);

        $extensions = [
            'openssl'   => false,
            'pdo'       => false,
            'gd'        => false,
            'zip'       => false,
            'mbstring'  => false,
            'mcrypt'    => false,
            'tokenizer' => false
        ];

        foreach($extensions as $ext => &$loaded){
            $loaded = extension_loaded($ext);
        }

        return $extensions;

    }

    private function getPermissions(){

        clearstatcache(true);

        $permissions = [
            [
                'name' => 'public/screenshots',
                'path' => realpath('.') . '/screenshots',
                'is_writable' => false
            ],
            [
                'name' => 'public/tmp',
                'path' => realpath('.') . '/tmp',
                'is_writable' => false
            ],
            [
                'name' => 'app/storage/cache',
                'path' => realpath('../') . '/app/storage/cache',
                'is_writable' => false
            ],
            [
                'name' => 'app/storage/logs',
                'path' => realpath('../') . '/app/storage/logs',
                'is_writable' => false
            ],
            [
                'name' => 'app/storage/sessions',
                'path' => realpath('../') . '/app/storage/sessions',
                'is_writable' => false
            ],
            [
                'name' => 'app/storage/views',
                'path' => realpath('../') . '/app/storage/views',
                'is_writable' => false
            ],
            [
                'name' => 'app/config/app.php',
                'path' => realpath('../') . '/app/config/app.php',
                'is_writable' => false
            ],
            [
                'name' => 'app/config/database.php',
                'path' => realpath('../') . '/app/config/database.php',
                'is_writable' => false
            ]
        ];

        foreach($permissions as &$permission){
            $permission['is_writable'] = is_writable($permission['path']);
        }

        return $permissions;


    }

    public function install()
    {

        if(Config::get('database.installed')){
            return Redirect::route('index');
        }

        return View::make('install')
            ->with('extensions', $this->getExtensions())
            ->with('permissions', $this->getPermissions());
    }

    public function installProcess(){

        if(Config::get('database.installed')){
            return $this->send();
        }

        $databaseName = Input::get('database_name');
        $databaseUser = Input::get('database_user');
        $databasePass = Input::get('database_pass');
        $databaseHost = Input::get('database_host');


        $data = [
            'database_name' => $databaseName,
            'database_user' => $databaseUser,
            'database_pass' => $databasePass,
            'database_host' => $databaseHost
        ];

        $rules = [
            'database_name' => 'required',
            'database_user' => 'required',
            'database_pass' => 'required',
            'database_host' => 'required'
        ];

        $validator = Validator::make($data, $rules);

        if ($validator->fails()) {
            $this->json['message'] = $validator->errors()->all();
            return $this->send();
        }else{

            $extDB = $this->databaseTest($databaseHost, $databaseName, $databaseUser, $databasePass);
            if(! $extDB){
                $this->json['message'] = ['Invalid database information. Not Connected'];
                return $this->send();
            }else{

                try{
                    $this->saveDatabaseConfig($databaseHost, $databaseName, $databaseUser, $databasePass);
                    $databaseQueries = file_get_contents(storage_path('database.sql'));

                    $extDB->query($databaseQueries);

                    $this->json['status'] = true;



                    return $this->send();
                }catch (Exception $e){
                    $this->json['message'] = ['Error Occurred : ' . $e->getMessage()];
                    return $this->send();
                }


            }
        }
    }

    private function databaseTest($host, $name, $user, $pass){

        $dsn = 'mysql:dbname='. $name .';host=' . $host;

        try{
            $dbh = new PDO($dsn, $user, $pass);
            return $dbh;
        }catch (PDOException $e){
            return false;
        }
    }

    private function saveDatabaseConfig($host, $name, $user, $pass){

        $database = "<?php

        return array(

            'installed' => true,

            'fetch' => PDO::FETCH_CLASS,

            'default' => 'mysql',

            'connections' => array(

                'sqlite' => array(
                    'driver'   => 'sqlite',
                    'database' => __DIR__.'/../database/production.sqlite',
                    'prefix'   => '',
                ),

                'mysql' => array(
                    'driver'    => 'mysql',
                    'host'      => '$host',
                    'database'  => '$name',
                    'username'  => '$user',
                    'password'  => '$pass',
                    'charset'   => 'utf8',
                    'collation' => 'utf8_unicode_ci',
                    'prefix'    => '',
                ),
            ),

            'migrations' => 'migrations',


            'redis' => array(

                'cluster' => false,

                'default' => array(
                    'host'     => '127.0.0.1',
                    'port'     => 6379,
                    'database' => 0,
                ),

            ),

        );
        ";


        return file_put_contents( app_path('/config/database.php'), $database);
    }

    private function send()
    {
        return json_encode($this->json);
    }
}





