<?php
date_default_timezone_set('America/Sao_Paulo');

ini_set("log_errors", 1);
if (debugEnabled()) {
    error_reporting(32767);
    ini_set("display_errors", 1);
} else {
    error_reporting(0);
    ini_set("display_errors", 0);
}
if (file_exists(__DIR__ . "/config.php")) {
    include_once __DIR__ . "/config.php";
}
class DB
{
    private $connection = NULL;
    private static $_instance = NULL;
    public static function getInstance()
    {
        if (!self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    private function __clone()
    {
    }
    public function getConnection($db_host, $db_port, $db_name, $db_user, $db_pass)
    {
        $con_name = $db_host . "_" . $db_name;
        try {
            if (!isset($this->connection[$con_name])) {
                $this->connection[$con_name] = new PDO("mysql:host=" . $db_host . ";port=" . $db_port . ";dbname=" . $db_name . ";charset=utf8", $db_user, $db_pass, array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_TIMEOUT => 5));
                $this->connection[$con_name]->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            }
        } catch (PDOException $e) {
            if (debugEnabled()) {
                exit("Failed to connect to DB: " . $e->getMessage());
            }
            return NULL;
        } catch (Exception $d) {
            if (debugEnabled()) {
                exit("Failed to connect to DB: " . $d->getMessage());
            }
            return NULL;
        }
        return $this->connection[$con_name];
    }
}
function conexao_AppPanel()
{
    return DB::getInstance()->getConnection(I9TEAM_DB_HOST, I9TEAM_DB_PORT, I9TEAM_DB_NAME, I9TEAM_DB_USER, I9TEAM_DB_PASS);
}

function debugEnabled()
{
    if (defined("PANEL_DEBUG") && PANEL_DEBUG) {
        return true;
    }
    return false;
}

function cryptPassword($password, $salt = "", $rounds = 20000)
{
    $hash = crypt($password, sprintf("\$6\$rounds=%d\$%s\$", $rounds, $salt));
    return $hash;
}

function buscarConfig(){
 $PDO = conexao_AppPanel();
 if ($PDO !== NULL) {
   $sql = "SELECT * FROM `configuracoes`";
   $stmt = $PDO->prepare($sql);
   $stmt->execute();
   return $stmt->fetch(PDO::FETCH_ASSOC);
}
return false;
}

function addCountDownload($AppID){
    $PDO = conexao_AppPanel();
    if ($PDO !== NULL) {
        $sql = "SELECT * FROM `aplicativos` WHERE `ID` = :id";
        $stmt = $PDO->prepare($sql);
        $stmt->bindParam(":id", $AppID, PDO::PARAM_INT);
        $stmt->execute();
        $app = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($app) {
            $downloadCount = $app['download'] + 1;

            $sqlUpdate = "UPDATE `aplicativos` SET `download` = :download WHERE `ID` = :id";
            $stmtUpdate = $PDO->prepare($sqlUpdate);
            $stmtUpdate->bindParam(":download", $downloadCount, PDO::PARAM_INT);
            $stmtUpdate->bindParam(":id", $AppID, PDO::PARAM_INT);
            $stmtUpdate->execute();

            return $downloadCount;
        } else {
            return false;
        }
    }
}

function buscarUsuarios($email, $senha){
 $PDO = conexao_AppPanel();
 if ($PDO !== NULL) {
   $sql = "SELECT * FROM `usuarios` WHERE `Email` = :email AND `Senha` = :senha;";
   $stmt = $PDO->prepare($sql);
   $stmt->bindParam(":email", $email, PDO::PARAM_STR, 250);
   $stmt->bindParam(":senha", $senha, PDO::PARAM_STR, 250);
   $stmt->execute();
   return $stmt->fetch(PDO::FETCH_ASSOC);
}
return false;
}

function buscarUsuariosID($id){
 $PDO = conexao_AppPanel();
 if ($PDO !== NULL) {
   $sql = "SELECT * FROM `usuarios` WHERE `ID` = :id;";
   $stmt = $PDO->prepare($sql);
   $stmt->bindParam(":id", $id, PDO::PARAM_INT);
   $stmt->execute();
   return $stmt->fetch(PDO::FETCH_ASSOC);
}
return false;
}

function buscarApps(){
 $PDO = conexao_AppPanel();
 if ($PDO !== NULL) {
   $sql = "SELECT * FROM `aplicativos` ORDER BY download DESC;";
   $stmt = $PDO->prepare($sql);
   $stmt->execute();
   return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
return false;
}

function buscarAppsID($id){
 $PDO = conexao_AppPanel();
 if ($PDO !== NULL) {
   $sql = "SELECT * FROM `aplicativos` WHERE `ID` = :id;";
   $stmt = $PDO->prepare($sql);
   $stmt->bindParam(":id", $id, PDO::PARAM_INT);
   $stmt->execute();
   return $stmt->fetch(PDO::FETCH_ASSOC);
}
return false;
}

function uploadFile($arquivo, $pasta, $tipos, $nome = null){
    if(isset($arquivo)){
        $infos = explode(".", $arquivo["name"]);

        if(!$nome){
            for($i = 0; $i < count($infos) - 1; $i++){
                $nomeOriginal = $nomeOriginal . $infos[$i] . ".";
            }
        }
        else{
            $nomeOriginal = $nome . ".";
        }

        $tipoArquivo = $infos[count($infos) - 1];

        $tipoPermitido = false;
        foreach($tipos as $tipo){
            if(strtolower($tipoArquivo) == strtolower($tipo)){
                $tipoPermitido = true;
            }
        }
        if(!$tipoPermitido){
            $retorno["erro"] = "Tipo não permitido";
        }
        else{
            if(move_uploaded_file($arquivo['tmp_name'], $pasta . $nomeOriginal . $tipoArquivo)){
                $retorno["caminho"] = $pasta . $nomeOriginal . $tipoArquivo;
            }
            else{
                $retorno["erro"] = "Erro ao fazer upload";
            }
        }
    }
    else{
        $retorno["erro"] = "Arquivo nao setado";
    }
    return $retorno;
}

function registrarApp($nome, $link, $imagem){
    $PDO = conexao_AppPanel();
    if ($PDO !== NULL) {
        $sql = "INSERT INTO `aplicativos` (`ID`, `Nome`, `Link`, `Status`, `Imagem`) VALUES (NULL, :nome, :link, '1', :imagem);";
        $stmt = $PDO->prepare($sql);
        $stmt->bindParam(":nome", $nome, PDO::PARAM_STR, 255);
        $stmt->bindParam(":link", $link, PDO::PARAM_STR, 255);
        $stmt->bindParam(":imagem", $imagem, PDO::PARAM_STR, 255);
        if ($stmt->execute()) {
            return $PDO->lastInsertId();
        }
    }
    return false;
}

function editarApp($nome, $link, $imagem, $id, $code){
    $PDO = conexao_AppPanel();
    if ($PDO !== NULL) {
        $sql = "UPDATE `aplicativos` SET `Nome` = :nome, `Link` = :link, `Imagem` = :imagem , `code` = :code WHERE `aplicativos`.`ID` = :id;";
        $stmt = $PDO->prepare($sql);
        $stmt->bindParam(":nome", $nome, PDO::PARAM_STR, 255);
        $stmt->bindParam(":link", $link, PDO::PARAM_STR, 255);
        $stmt->bindParam(":imagem", $imagem, PDO::PARAM_STR, 255);
        $stmt->bindParam(":id", $id, PDO::PARAM_INT);
        $stmt->bindParam(":code", $code, PDO::PARAM_INT);
        
        if ($stmt->execute()) {
            return true;
        }
    }
    return false;
}

function statusApp($id){
    $PDO = conexao_AppPanel();
    if ($PDO !== NULL) {
        $sql = "UPDATE `aplicativos` SET `Status` = !`Status` WHERE `aplicativos`.`ID` = :id;";
        $stmt = $PDO->prepare($sql);
        $stmt->bindParam(":id", $id, PDO::PARAM_INT);
        if ($stmt->execute()) {
            return true;
        }
    }
    return false;
}

function excluirApp($id){
    $PDO = conexao_AppPanel();
    if ($PDO !== NULL) {
        $sql = "DELETE FROM `aplicativos` WHERE `aplicativos`.`ID` = :id LIMIT 1;";
        $stmt = $PDO->prepare($sql);
        $stmt->bindParam(":id", $id, PDO::PARAM_INT);
        if ($stmt->execute()) {
            return true;
        }
    }
    return false;
}

function atualizarSenhaUsuario($senha){
    $PDO = conexao_AppPanel();
    if ($PDO !== NULL) {
        $sql = "UPDATE `usuarios` SET `Senha` = :senha WHERE `usuarios`.`ID` = 1;";
        $stmt = $PDO->prepare($sql);
        $stmt->bindParam(":senha", $senha, PDO::PARAM_STR, 255);
        if ($stmt->execute()) {
            return true;
        }
    }
    return false;
}


function atualizarConfigSemSenha($titulo, $icone, $logo, $background, $email){
 $PDO = conexao_AppPanel();
 if ($PDO !== NULL) {
    $sql = "UPDATE `configuracoes` SET `Titulo` = :titulo, `Logotipo_1` = :icone, `Logotipo_2` = :logo, `Background` = :background WHERE `configuracoes`.`ID` = 1;";
    $stmt = $PDO->prepare($sql);
    $stmt->bindParam(":titulo", $titulo, PDO::PARAM_STR, 255);
    $stmt->bindParam(":icone", $icone, PDO::PARAM_STR, 255);
    $stmt->bindParam(":logo", $logo, PDO::PARAM_STR, 255);
    $stmt->bindParam(":background", $background, PDO::PARAM_STR, 255);
    if ($stmt->execute()) {
        return true;
    }
}
return false;
}

function atualizarConfigComSenha($titulo, $icone, $logo, $background, $email, $senha){
 $PDO = conexao_AppPanel();
 if ($PDO !== NULL) {
    $sql = "UPDATE `configuracoes` SET `Titulo` = :titulo, `Logotipo_1` = :icone, `Logotipo_2` = :logo, `Background` = :background WHERE `configuracoes`.`ID` = 1;";
    $stmt = $PDO->prepare($sql);
    $stmt->bindParam(":titulo", $titulo, PDO::PARAM_STR, 255);
    $stmt->bindParam(":icone", $icone, PDO::PARAM_STR, 255);
    $stmt->bindParam(":logo", $logo, PDO::PARAM_STR, 255);
    $stmt->bindParam(":background", $background, PDO::PARAM_STR, 255);
    if ($stmt->execute()) {
        if (atualizarSenhaUsuario($senha)) {
            return true;
        }
    }
}
return false;
}


?>