<?php


class Database
{
    private $my_dist_host;
    private $my_dist_user;
    private $my_dist_pass;

    private $mo_db;
    private $mo_host;

    public function __construct()
    {
        $this->my_dist_host = '167.114.96.213';
        $this->my_dist_user = 'auditor';
        $this->my_dist_pass = 'root@sa123!#$';
        $this->my_dist_db = 'sauditor_v2_0';

        $this->mo_db = 'distributed';
        $this->mo_host = 'mongodb://167.114.96.216:27017';
    }

    public function logError($err)
    {
        $dir = '/var/www/html/logs/';
        $file = '/var/www/html/logs/error.log';
        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $error = $err.print_r(error_get_last(), true);
        $fhn = fopen($file, 'a+');
        fwrite($fhn, $error."\n");
        fclose($fhn);
    }

    public function conMongo($try = '')
    {
        if (empty($try)) {
            $try = 0;
        }

        try {
            $mongo = new mongoClient($this->mo_host);
            $mongoDB = $mongo->selectDB($this->mo_db);
        }
        catch (Exception $e) {
            if ($try <= 2) {
                $try += 1;
                // $this->logError($e);
                $this->conMongo($try);
            }
        }

        return $mongoDB;
    }

    public function conDist($try = '')
    {
        if (empty($try)) {
            $try = 0;
        }

        $con_dist = new mysqli($this->my_dist_host, $this->my_dist_user, $this->my_dist_pass, $this->my_dist_db);
        if (mysqli_connect_error()) {
            if ($try <= 2) {
                $try += 1;
                // $this->logError(mysqli_connect_error());
                $this->conDist($try);
            }
        }

        return $con_dist;
    }
}
