<?php
class DBMainServer extends mysqli{  
    static private $instance;
    
    public static $a_especial_chars = array(
        'À' => 'a', 'Á' => 'a', 'Â' => 'a', 'Ã' => 'a', 'Ä' => 'a', 'Å' => 'a',
        'Æ' => 'a', 'Ç' => 'c', 'È' => 'e', 'É' => 'e', 'Ê' => 'e', 'Ë' => 'e',
        'Ì' => 'i', 'Í' => 'i', 'Î' => 'i', 'Ï' => 'i', 'Ð' => 'd', 'ñ' => 'n',
        'Ò' => 'o', 'Ó' => 'o', 'Ô' => 'o', 'Õ' => 'o', 'Ö' => 'o', 'Ø' => 'o',
        'Ù' => 'u', 'Ú' => 'u', 'Û' => 'u', 'Ü' => 'u', 'Ý' => 'y', 'Þ' => 'b',
        'ß' => 's', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a',
        'å' => 'a', 'æ' => 'a', 'ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e',
        'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'd',
        'Ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o',
        'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'ý' => 'y',
        'þ' => 'b', 'ÿ' => 'y', '\'' => '', '%' => '', '"' => ''
    );

    const WARNING = 1;
    const STOP_CRITICAL = 2;

    public static function getInstance() {
        if (self::$instance == null) {
            self::$instance = new self();
        } 
        return self::$instance;
    }
    
    static function getInsertId(){
        return self::$instance->insert_id;
    }

    private function __construct($db = null) {
        $entity = new EntityRepository();
        $query = "SELECT `key`,value "
                . "FROM settings "
                . "WHERE `key` = 'MAIN_DB_HOSTNAME' OR `key` = 'MAIN_DB_NAME' OR `key` = 'MAIN_DB_USERNAME' OR `key` = 'MAIN_DB_PASSWORD' ";
        
        $result = $entity->query($query);
        if($result){
            foreach($result as $row){
                $data[$row['key']] = $row['value'];
            }
        }
        
        if($db!==null){
            $data['MAIN_DB_NAME'] = $db;
        } 

        parent::__construct($data['MAIN_DB_HOSTNAME'], $data['MAIN_DB_USERNAME'], $data['MAIN_DB_PASSWORD'], $data['MAIN_DB_NAME']);
        
        if ($this->connect_error) {
            $error = 'Oops... algo salio mal al intentar conectarse al Servidor principal: ' . $this->connect_error;
            $this->getErrorMessage($error);
        }
        return $this;
    }
    
    public function execute($query) {
        $r = $this->query($query);
        if ($r) {
          return $r;
        } else {
            $error = "Al intentar <b>$query</b> se produjo: <i>$this->error</i>";
            $this->getErrorMessage($error);
        }
    }
    
    public function getErrorMessage($error) {
        return '<span class="error_database">' . $error . '</span>';
    }
}
