<?php

class FUNCOES {

    public function __construct() {
        
    }

    public static function isAjax() {
        if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            return true;
        } else {
            return false;
        }
    }

    public static function getSocioCliente($id_cliente) {
        $apoio = array();

        $resultSocios = mysql_query("SELECT id,id_apoio "
                . " FROM user u "
                . " WHERE u.id_apoio = $id_cliente");
        $apoio[] = $id_cliente;
        while ($rowSocios = mysql_fetch_array($resultSocios)) {
            $apoio[] = $rowSocios['id'];
            $apoio[] = $rowSocios['id_apoio'];
        }
        if (count($apoio) < 2) {
            /**
             * sem ID E ID_APOIO
             */
            $apoio = array();
            $resultSocios = mysql_query("SELECT id,id_apoio "
                    . " FROM user u "
                    . " WHERE u.id = $id_cliente");
            $apoio[] = $id_cliente;
            while ($rowSocios = mysql_fetch_array($resultSocios)) {
                $apoio[] = $rowSocios['id'];
                $apoio[] = $rowSocios['id_apoio'];
            }
        }
        return $apoio;
    }

    public static function getApoios($id_user, $query_nivel = NULL) {
        $apoio = array();
        $resultSocios = mysql_query("SELECT id FROM user "
                . " WHERE id_apoio = $id_user "
                // . " AND status = 1"
                . " $query_nivel");
        $apoio[] = $id_user;
        while ($rowSocios = mysql_fetch_array($resultSocios)) {
            $apoio[] = $rowSocios['id'];
        }
        return $apoio;
    }

    public static function getApoiosBYNivel($id_user, $nivel) {
        $apoio = array();
        $resultSocios = mysql_query("SELECT u.id id
        FROM user u, ponto p 
        WHERE u.id_apoio = p.id
        AND p.id_apoio IN ($id_user) 
        AND u.nivel = $nivel
        AND u.status = 1 
        ORDER BY u.id DESC");
        $apoio[] = $id_user;
        while ($rowSocios = mysql_fetch_array($resultSocios)) {
            $apoio[] = $rowSocios['id'];
        }
        return $apoio;
    }

    public static function getCheckNome($id_apoio, $nome) {
        $result = mysql_query("SELECT nome FROM user "
                . " WHERE nome in ('$nome')"
                . " AND id_apoio = $id_apoio "
                . " AND status <> 0");

        $rowSocios = mysql_fetch_array($result);
        return $rowSocios;
    }

    public static function getExtension($string) {
        $explode = explode(".", $string);
        $extensao = $explode[count($explode) - 1];
        return $extensao;
    }

    public static function formatoDecimalHTML($valor, $symbol = false) {

        //str_replace('.', ',', $valor);
        return number_format($valor, 2, ',', '.');
    }

    public static function formatarDatatoHTML($data) {
        $dt = explode('-', $data);

        if ($dt[0]) {
            return $dt[2] . '/' . $dt[1] . '/' . $dt[0];
        }
        return NULL;
    }

    public static function formatarDatatoMYSQL($data) {
        $dt = explode('/', $data);

        if ($dt[0]) {
            return $dt[2] . '-' . $dt[1] . '-' . $dt[0];
        }
        return NULL;
    }

    static function timetoDays($time) {
        return (int) $time / (60 * 60 * 24);
    }

    static function isHtml($string) {
        if ($string != strip_tags($string)) {
            return true;
        }
        return false;
    }

    public static function logMsg($msg, $level = 'info', $file = 'main.log') {
        switch ($level) {
            case 'info':
                $msg = '[ INFO ] ' . $msg;
                break;

            case 'warning':
                $msg = '[ WARNING ] ' . $msg;
                break;

            case 'error':
                $msg = '[ ERROR ] ' . $msg;
                break;
        }
        // data atual
        $date = date('Y-m-d H:i:s');
        $msg = '[' . $date . '] ' . $msg;
        // adiciona quebra de linha
        $msg .= PHP_EOL;
        file_put_contents($file, $msg, FILE_APPEND);
    }

    /**
     * ERROR_FATAL DEBUG
     */
    public static function fatalErrorHandler() {

        # Getting last error
        $root = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR;
        $error = error_get_last();
        # Checking if last error is a fatal error
        if (($error['type']) || ($error['file'])) {
            $error_message = $error['message'] . ': ' . PHP_EOL . $error['file'] . ' line [ ' . $error['line'] . ' ]' . PHP_EOL . PHP_EOL;
            SELF::logMsg($error_message, 'error', $root . '/logs/error/' . 'error_fatal_' . date('Y-m-d') . '.log');
        }
    }

    public static function returnSqlStatus($metricas, $country) {

        if ($country == 'BR') {
            return " AND ( ($metricas.status_leitura  = 2  "
                    . "        AND ca.lote_fechamento_hash IS NOT NULL AND $metricas.status = 0)"
                    . "        OR "
                    . "       ($metricas.status_leitura <> 2  "
                    . "        AND ca.lote_fechamento_hash IS NULL AND $metricas.status <> 0) ) "
                    . " AND $metricas.cliente_fechamento IS NULL";
        } else {
            return " AND $metricas.status_leitura <> 2 "
                    . " AND $metricas.status <> 0";
        }
    }

    public static function console_log($data) {
        echo '<script>';
        echo 'console.log(' . json_encode($data) . ')';
        echo '</script>';
    }

    static function getChangelogUrl() {
        $myfile = fopen('update/' . 'changelog.txt', "r") or die("Impossível abrir o ficheiro changelog.txt!");
        $lines = count(file('update/' . 'changelog.txt'));
        $quebra = explode(PHP_EOL, fread($myfile, filesize('update/' . 'changelog.txt')));
        $changelog = explode(":", $quebra[$lines - 1]);
        fclose($myfile);
        $nodeServer = null;
        if (isset($changelog[4]) && isset($changelog[5])) {
            $nodeServer = $changelog[4] . ':' . $changelog[5] . ':' . $changelog[6];
        }
        return $nodeServer;
    }

    public static function exec_curl($URL, $CURLOPT_RETURNTRANSFER = true) {
        $ch = curl_init();
// Will return the response, if false it print the response
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, $CURLOPT_RETURNTRANSFER);
// Set the url
        curl_setopt($ch, CURLOPT_URL, $URL);
// Execute
        $result = curl_exec($ch);
// Closing
        curl_close($ch);
// Will dump a beauty json :3
        return json_decode($result);
        //var_dump(json_decode($result, true));
    }

    static function exec_curl_post($array) {
        $url = self::getChangelogUrl() . '/updatePontoVirtualConfig';

        $postdata = json_encode($array);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        $result = curl_exec($ch);
        curl_close($ch);
        return ($result);
    }

    public static function cryptografar($value) {
        return sha1(md5($value));
    }

    static function make_qrcode($id ,$user_id) { 
        //http://' . $_SERVER['HTTP_HOST'] .'/Gerenciamentokioskonline/
        $url = urlencode('http://www.kiosknet.mobi/online/c_jogadores.php?id_ponto=' . $id.'&user_id='.$user_id);
        $aux = 'php/qr_img.php?';
        $aux.='d=' . $url . '&';
        $aux.='e=H&';
        $aux.='s=6.5&';
        $aux.='t=P';
        $qrImage = 'qrcode_ponto_' . $id . '.png';
        copy('http://www.kiosknet.mobi/online/api/qr_img/'.$aux, 'img/qrcode/' . $qrImage);
        //copy('http://' . $_SERVER['HTTP_HOST'] .'/Gerenciamentokioskonline/api/qr_img/' . $aux, 'img/qrcode/' . $qrImage);
        return $qrImage;
    }

}
