<?php

namespace Sargilla\Flatlab4\Console;

use PDO;
use PDOException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CreateDatabase extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'db:create';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Crea la base de datos para el sistema';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $database = env('DB_DATABASE', false);

        if (! $database) {
            $this->info('No se puede crear la base de datos porque env(DB_DATABASE) esta vacio');
            return;
        }

        try {
            $pdo = $this->getPDOConnection('127.0.0.1', 3306, 'root', 'root');
            $pdo->exec(sprintf(
                'CREATE DATABASE IF NOT EXISTS %s CHARACTER SET %s COLLATE %s;',
                $database,
                config('database.connections.mysql.charset'),
                config('database.connections.mysql.collation')
            ));
        } catch (PDOException $exception) {
            $this->error(sprintf('Error al crear la base de datos %s, %s', $database, $exception->getMessage()));
        }
    }
    /**
     * @param  string $host
     * @param  integer $port
     * @param  string $username
     * @param  string $password
     * @return PDO
     */
    private function getPDOConnection($host, $port, $username, $password)
    {
        return new PDO(sprintf('mysql:host=%s;port=%d;', $host, $port), $username, $password);
    }

    
}
