<?php

namespace AuthStack\Installer\Services;

use AuthStack\Installer\Model\MySQL as MySQLModel;

class MySQL
{
    protected $errors = [];

    /**
     * @param $host
     * @param $dbname
     * @param $username
     * @param $password
     * @param null $port
     * @return MySQLModel|bool
     */
    public function verify($host, $dbname, $username, $password, $port = null)
    {
        $dsn = !is_null($port) ?
            sprintf("mysql:host=%s;port=%s;dbname=%s", $host, $port, $dbname)
            :
            sprintf("mysql:host=%s;dbname=%s", $host, $dbname);

        try
        {
            $pdo    = new \PDO($dsn, $username, $password);
            $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            // Check if database is empty
            $isEmpty = $pdo->query("SHOW TABLES")->fetchAll(\PDO::FETCH_ASSOC);

            if(sizeof($isEmpty))
            {
                throw new \Exception(sprintf("Database specified (%s) is not empty. AuthStack requires an empty database!", $dbname));
            }

            $result = $pdo->query("SELECT VERSION() AS version")->fetchAll(\PDO::FETCH_ASSOC);

            $version = $result[0]['version'];

            $result = new MySQLModel([
                'host'          => $host,
                'port'          => $port,
                'dbname'        => $dbname,
                'username'      => $username,
                'password'      => $password,
                'version'       => $version
            ]);
        }
        catch(\Exception $e)
        {
            $this->errors[] = $e->getMessage();

            $result = false;
        }

        return $result;
    }

    /**
     * @return array
     */
    public function getErrors()
    {
        return $this->errors;
    }

    public function getFirstError()
    {
        return isset($this->errors[0]) ? $this->errors[0] : null;
    }
}