<?php
error_reporting( error_reporting() & ~E_NOTICE );
/** Konstanten */
include (__DIR__ . '/connect.db.php');
include_once (__DIR__ . '/const.php');
/** HTMLPurifier */
require_once ($_SERVER['DOCUMENT_ROOT'] . HOME_DIR . '/_library/htmlpurifier-4.10.0/library/HTMLPurifier.auto.php');

$config                           = HTMLPurifier_Config::createDefault();
$config->set('Core.Encoding', 'UTF-8');
$config->set('HTML.Doctype', 'HTML 4.01 Transitional');
$config->set('Attr.AllowedFrameTargets',  array('_blank' => true));
$purifier                         = new HTMLPurifier($config);
  
/**
 *  Funktionen 
 */

function my_autoload($className)
{
  $file                   = __DIR__ . '/classes/' . strtolower($className) . '.class.php';
  if(file_exists($file)) {
    require_once($file);
  }
}

function createUUID()
{

    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

function makeHtmlEntities($str)
{
  $string                           = htmlentities($str, ENT_QUOTES, "UTF-8");
  return $string;
}

function showHtmlEntities($str)
{
  global $purifier;
  $string                           = stripslashes(html_entity_decode($str, ENT_QUOTES, "UTF-8"));
  $string                           = $purifier->purify($string);
  return $string;
}

function buildSlug($str)
{
  setlocale(LC_ALL, 'en_US.UTF8');
  $slug                             = $str;
  $slug                             = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
  $slug                             = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $slug);
  $slug                             = strtolower(trim($slug, '-'));
  $slug                             = preg_replace("/[\/_|+ -]+/", '-', $slug);
  return $slug;
}

/** SQL-Funktionen */

function pdoDbInsert($table_name, $form_data)
{
  $database             = new Database();
  $fields_data          = array_keys($form_data);
  $sql                  = "INSERT INTO " . $table_name . "
  (" . implode(', ', $fields_data) . ")
  VALUES (:" . implode(", :", $fields_data) . ")";
  $database->beginTransaction();
  $database->query($sql);
  
  foreach ($form_data as $key => $value) {
    $database->bind(":$key", $value);
  }

  $database->execute();
  $database->endTransaction();
}

function pdoDbUpdate($table_name, $form_data, $where_clause='', $whereVal)
{
  $database             = new Database();
  $whereSQL = '';
  if(!empty($where_clause)) {
    if(substr(strtoupper(trim($where_clause)), 0, 5) != 'WHERE') {
        $whereSQL       = " WHERE " . $where_clause;
    } else {
        $whereSQL       = " " . trim($where_clause);
    }
  }
  $sql                  = "UPDATE " . $table_name . " SET "; 
  $sets                 = array();
  foreach($form_data as $column => $value) {
       $sets[]          = "" . $column . " = :" . $column . "";
  }
  $sql                  .= implode(', ', $sets); 
  $sql                  .= $whereSQL;
  $database->beginTransaction();
  $database->query($sql);
  
  foreach ($form_data as $key => $value) {
    $database->bind(":$key", $value);
  }
  $stringposition       = strpos ($where_clause, ' = :');
  $whereKey             = substr($where_clause,0,$stringposition);
  if(!empty($where_clause)) {
    $database->bind(":$whereKey", $whereVal);
  }
  $database->execute();
  $database->endTransaction();
}


/** Ende SQL-Funktionen */

function makeSystemDate($Date)
//makeSystemDate($Datum)
{
  $YearSys                          = substr($Date, 6, 4);
  $MonthSys                         = substr($Date, 3, 2);
  $DaySys                           = substr($Date, 0, 2);
  $SystemDate                       = $YearSys . '-' . $MonthSys . '-' . $DaySys;
  return $SystemDate;
}

function makeLocalDate($Date, $Format)
//makeLocalDate($Datum, "DE")
{
  $YearLocal                        = substr($Date, 0, 4);
  $MonthLocal                       = substr($Date, 5, 2);
  $DayLocal                         = substr($Date, 8, 2);
  $Time                             = substr($Date, 10, 9);
  switch($Format) {
    case "DE":
      $LocalDate                    = $DayLocal . '.' . $MonthLocal . '.' . $YearLocal . $Time;
      break;
    case "ES":
      $LocalDate                    = $DayLocal . '/' . $MonthLocal . '/' . $YearLocal . $Time;
      break;
    case "EN":
      $LocalDate                    = $DayLocal . '-' . $MonthLocal . '-' . $YearLocal . $Time;
      break;
    case "US":
      $LocalDate                    = $MonthLocal . '-' . $DayLocal . '-' . $YearLocal . $Time;
      break;
  }
  return $LocalDate;
}

function createAuthKey()
{
  $Buchstaben           = array("A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
  $Zahlen               = array("2", "3", "4", "5", "6", "7", "8", "9");

  for($i                = 0, $Code = "", $AuthCode = ""; strlen($Code) < 20; $i++) {
    if(rand(0, 1)       == 0 && isset($Buchstaben)) {
      $Buchstabe        = $Buchstaben[rand(0, count($Buchstaben)-1)];
      $Code             .= $Buchstabe;
      $AuthCode          .= $Buchstabe;
    } else {
      $Zahl             = $Zahlen[rand(0, count($Zahlen)-1)];
      $Code             .= $Zahl;
      $AuthCode          .= $Zahl;
    }
  }

  $AuthCode             = trim($AuthCode);
  return $AuthCode;
}

function validateYesNoAccountLocked($val)
{
  switch ($val) { 
    case 0:
      $val                          = '<font color="#04B431"><i class="fa fa-unlock" aria-hidden="true"></i> &nbsp; Ja</font>';
      break;
    case 1:
      $val                          = '<font color="#FF0000"><i class="fa fa-lock" aria-hidden="true"></i> &nbsp; Nein</font>';
      break;
  }
  return $val;
}

function validateYesNoTxt($val)
{
  switch ($val) {
    case 0:
      $val                          = '<font color="#FF0000" size="0"><i class="fas fa-times" aria-hidden="true"></i></font>';
      break;
    case 1:
      $val                          = '<font size="+1" color="#01DF01"><i class="fas fa-check" aria-hidden="true"></i></font>';
      break;
  }
  return $val;
}

function validateYesNo($val)
{
  switch ($val) {
    case 0:
      $val                          = 'Nein';
      break;
    case 1:
      $val                          = 'Ja';
      break;
  }
  return $val;
}

function showTime($timeVal)
{
  $timeVal                          = substr($timeVal, 0, 5);
  return $timeVal;
}

function checkStringNotNull($val)
{
  if ($val                          == '') {
    $val                            = 0;
  } else {
    $val                            = $val;
  }
  return $val;
}


function getUserInitials($userID)
{
  $db                         = new Database();
  
  $sql                        = 'SELECT * FROM tbl_users WHERE uuid = :id';
  $db->query($sql);
  $db->bind(':id', $userID);
  $row                        = $db->single();
  $initial1                   = ucfirst(substr(showHtmlEntities($row['first_name']), 0, 1));
  $initial2                   = ucfirst(substr(showHtmlEntities($row['last_name']), 0, 1));
  
  $initials                   = $initial1 . $initial2;
  
  
  switch ($initial1) {
    case 'A':
      $circleColor            = '#00FFFF';
      $fontColor              = '#000';
      break;
    case 'B':
      $circleColor            = '#2E2E2E';
      $fontColor              = '#FFFFFF';
      break;
    case 'C':
      $circleColor            = '#FF00FF';
      $fontColor              = '#FFFFFF';
      break;
    case 'D':
      $circleColor            = '#0040FF';
      $fontColor              = '#FFFFFF';
      break;
    case 'E':
      $circleColor            = '#40FF00';
      $fontColor              = '#000000';
      break;
    case 'F':
      $circleColor            = '#FFFF00';
      $fontColor              = '#000000';
      break;
    case 'G':
      $circleColor            = '#FF0000';
      $fontColor              = '#FFFFFF';
      break;
    case 'H':
      $circleColor            = '#00FFFF';
      $fontColor              = '#000';
      break;
    case 'I':
      $circleColor            = '#2E2E2E';
      $fontColor              = '#FFFFFF';
      break;
    case 'J':
      $circleColor            = '#FF00FF';
      $fontColor              = '#FFFFFF';
      break;
    case 'K':
      $circleColor            = '#0040FF';
      $fontColor              = '#FFFFFF';
      break;
    case 'L':
      $circleColor            = '#40FF00';
      $fontColor              = '#000000';
      break;
    case 'M':
      $circleColor            = '#FFFF00';
      $fontColor              = '#000000';
      break;
    case 'N':
      $circleColor            = '#FF0000';
      $fontColor              = '#FFFFFF';
      break;
    case 'O':
      $circleColor            = '#00FFFF';
      $fontColor              = '#000';
      break;
    case 'P':
      $circleColor            = '#2E2E2E';
      $fontColor              = '#FFFFFF';
      break;
    case 'Q':
      $circleColor            = '#FF00FF';
      $fontColor              = '#FFFFFF';
      break;
    case 'R':
      $circleColor            = '#0040FF';
      $fontColor              = '#FFFFFF';
      break;
    case 'S':
      $circleColor            = '#40FF00';
      $fontColor              = '#0404B4';
      break;
    case 'T':
      $circleColor            = '#FFFF00';
      $fontColor              = '#000000';
      break;
    case 'U':
      $circleColor            = '#FF0000';
      $fontColor              = '#FFFFFF';
      break;
    case 'V':
      $circleColor            = '#00FFFF';
      $fontColor              = '#000';
      break;
    case 'W':
      $circleColor            = '#2E2E2E';
      $fontColor              = '#FFFFFF';
      break;
    case 'X':
      $circleColor            = '#FF00FF';
      $fontColor              = '#FFFFFF';
      break;
    case 'Y':
      $circleColor            = '#0040FF';
      $fontColor              = '#FFFFFF';
      break;
    case 'Z':
      $circleColor            = '#40FF00';
      $fontColor              = '#000000';
      break;
    default:
      $circleColor            = '#FFFFFF';
      $fontColor              = '#000000';
  }
  
  
  $userName                   = $row['first_name'] . ' ' . $row['last_name'];
  
  return '<font size="+1" color="' . $circleColor . '">
            <span class="fa-stack fa-lg">
              <i class="fa fa-circle fa-stack-2x logo-user" aria-hidden="true"></i>
              <span class="fa-stack-1x fa-inverse logo-user-initials">
                <font color="' . $fontColor . '">' . $initials . '</font>
              </span>
            </span>
          </font>';
}

function getVersion()
{
  $db                         = new Database();
  
  $sql                        = 'SELECT version FROM tbl_history ORDER BY datetime DESC';
  $db->query($sql);
  $row                        = $db->single();
  return $row['version'];
}