<?php

class Config
{
    private $con_dist;

    public function __construct()
    {
        $dbs = new Database();
        $dist = $dbs->conDist();

        if ($dist instanceof mysqli) {
            $this->con_dist = $dist;
        }
    }

    public function getExternalIp()
    {
        $external_ip = exec('curl http://ipecho.net/plain; echo');
        if (!empty($external_ip) && $external_ip != '127.0.0.1') {
            define('MY_IP', $external_ip);
        } elseif(!empty($_SERVER['SERVER_ADDR']) && $_SERVER['SERVER_ADDR'] != '127.0.0.1') {
            define('MY_IP', $_SERVER['SERVER_ADDR']);
        }  else {
            $this->fatalHandler('unable to generate server ip');
        }
    }

    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);
        chmod($file, 0777);
    }

    public function fatalHandler($detail = '')
    {
        $error = error_get_last();

        if ($error !== null && ($error['type'] == 1 || $error['type'] == 4 || $error['type'] == 16)) {
            $log = "INSERT INTO log_fatal VALUES('','','fatal:','".addslashes(trim(preg_replace('/\s+/', ' ', print_r($error, true))))."', NOW(),'".addslashes($detail)."','".MY_IP."','".addslashes(trim(preg_replace('/\s+/', ' ', print_r(debug_backtrace(), true))))."')";
            if (mysqli_query($this->con_dist, $log)) {
                return true;
            } else {
                $this->logError(print_r(array(trim(preg_replace('/\s+/', ' ', print_r($error, true))), $detail), true));
            }
        }
    }

    public function getAllSettings($section)
    {
        $qry = "SELECT name,setting FROM settings WHERE section=$section";

        if ($q_res = mysqli_query($this->con_dist, $qry)) {
            while ($res = mysqli_fetch_assoc($q_res)) {
                define($res['name'], $res['setting']);
            }
        } else {
            return mysqli_error($this->con_dist);
        }
    }


}
