<?php

class user
{
  public function __construct()
  {
    $this->Database                         = new Database();                             /** Datenbankklasse instanzieren */
    $this->pwHash                           = new pwhash(BCRYPT_HASH_ROUNDS, FALSE);      /** Bcrypt instanzieren */
  }

  public function saveUserData($values)
  {
    $insertArray                            = array(
        'uuid'                              => $values['uuid'],
        'username'                          => makeHtmlEntities($values['username']),
        'password'                          => $this->createPassword($values['password']),
        'first_name'                        => makeHtmlEntities($values['first_name']),
        'last_name'                         => makeHtmlEntities($values['last_name']),
        'address'                           => makeHtmlEntities($values['address']),
        'tel'                               => makeHtmlEntities($values['tel']),
        'email'                             => makeHtmlEntities($values['email']),
        'role'                              => $values['role'],
        'reg_by'                            => $_SESSION[ALLOW],
        'reg_datetime'                      => date("Y-m-d H:i:s"),
    );
    pdoDbInsert("tbl_users", $insertArray);
  }
  
  public function updateUserData($values)
  {
    $updateArray                            = array(
        'username'                          => makeHtmlEntities($values['username']),
        'first_name'                        => makeHtmlEntities($values['first_name']),
        'last_name'                         => makeHtmlEntities($values['last_name']),
        'address'                           => makeHtmlEntities($values['address']),
        'tel'                               => makeHtmlEntities($values['tel']),
        'email'                             => makeHtmlEntities($values['email']),
        'role'                              => $values['role'],
        'reg_by'                            => $_SESSION[ALLOW],
        'reg_datetime'                      => date("Y-m-d H:i:s"),
    );
    $whereCause                             = 'uuid = :uuid';
    $whereVal                               = $values['id'];
    pdoDbUpdate("tbl_users", $updateArray, $whereCause, $whereVal);
  }
  
  public function updateUserPw($values)
  {
    $password                               = $this->createPassword($values['password']);
    $updateArray                            = array(
        'password'                          => $password,
    );
    $whereCause                             = 'uuid = :uuid';
    $whereVal                               = $values['id'];
    pdoDbUpdate("tbl_users", $updateArray, $whereCause, $whereVal);
  }
  
  public function updateClientPw($values)
  {
    $password                               = $this->createPassword($values['password']);
    $updateArray                            = array(
        'password'                          => $password,
    );
    $whereCause                             = 'uuid = :uuid';
    $whereVal                               = $values['id'];
    pdoDbUpdate("kunden", $updateArray, $whereCause, $whereVal);
  }
  
  public function createPassword($password)
  {
    $pwHash                                 = $this->pwHash;
    $passwordBcrypt                         = $pwHash->HashPassword($password);
    return $passwordBcrypt;
  }
  
  public function checkPasswdComplexity($string, $complexity, $length)
  {
    /**
     * Komplexität = 0 -> Zahlen und Buchstaben, Gross und Klein
     * Komplexität = 1 -> Zahlen und Buchstaben, Gross und Klein, sowie Sonderzeichen
     */
    switch ($complexity) {
      case 0:
        if( preg_match( '/[[:lower:]]/', $string ) && preg_match( '/[[:upper:]]/', $string ) && preg_match( '/[[:digit:]]/', $string )) {
          $val                                = 1;
        } else {
          $val                                = 0;
          $errorMsg                           = 'La contraseña debe ser grande en minúsculas letras y números! (0-9, a-Z)';
        }
        break;
      case 1:
        if( preg_match( '/[[:lower:]]/', $string ) && preg_match( '/[[:upper:]]/', $string ) && preg_match( '/[[:digit:]]/', $string ) && preg_match( '/[[:punct:]]/', $string )) {
          $val                                = 1;
        } else {
          $val                                = 0;
          $errorMsg                           = 'La contraseña debe ser grande en minúsculas letras y números y caracteres especiales! (0-9, a-Z, ?!#@&%$=/)';
        }
        break;
    }  
    
    if (strlen($string)           < $length) {
      return false;
    } elseif ($val                == 0) {
      return false;
    } else {
      return true;
    }
  }
  
  public function generatePw($length) 
  {
    $letters                                = "abcdefghijklmnopqrstuvwxyz";
    $lettersCapital                         = strtoupper($letters);
    $numeric                                = "0123456789";
    $special                                = "?!#@&%$=/";
    $chars                                  = "";
    
    $chars                                  = $letters . $lettersCapital . $numeric . $special;
    
    $len                                    = strlen($chars);
    $pw                                     = '';
     
    for ($i                                 = 0; $i <= $length; $i++) {
      $pw                                   .= substr($chars, rand(0, $len-1), 1);
    }
    
    $specialVal                           = '?';
    $numericVal                           = '7';
    $lettersVal                           = 'u';
    $lettersCapitalVal                    = 'F';
    
    return str_shuffle($pw . $specialVal . $numericVal . $lettersVal . $lettersCapitalVal);
  }
  
  public function checkUsername($username)
  {
    $db                                   = $this->Database;
    $sql                                  = 'SELECT COUNT(username) as users FROM tbl_users WHERE username = :username';
    $db->query($sql);
    $db->bind(':username', $username);
    $row                                  = $db->single();
    $amount                               = $row['users'];
    if ($amount                           != 0) {
      return false;
    } else {
      return true;
    }
  }
  
  public function checkUsernameEdit($username, $userUUID)
  {
    $db                                   = $this->Database;
    $sql                                  = 'SELECT COUNT(username) as users FROM tbl_users WHERE username = :username AND uuid != :uuid';
    $db->query($sql);
    $db->bind(':username', $username);
    $db->bind(':uuid', $userUUID);
    $row                                  = $db->single();
    $amount                               = $row['users'];
    if ($amount                           != 0) {
      return false;
    } else {
      return true;
    }
  }
  
  public function getUserDataByUUID($uuid)
  {
    $db                                     = $this->Database;
    $sql                                    = 'SELECT * FROM tbl_users WHERE uuid = :uuid';
    $db->query($sql);
    $db->bind(':uuid', $uuid);
    return $db->single();
  }
  
  public function getUserRole()
  {
    $roleArray                              = array(
        'Admins'                            => 1,
        'Main_Users'                        => 2,
        'Standard_Users'                    => 3,
    );
    return $roleArray;
  }
  
  public function getUserRoleName($roleVal)
  {
    switch ($roleVal) {
      case 1:
        return 'Admins - alle Rechte';
        break;
      case 2:
        return 'Main_Users - kann TOM / VVT-Texte erstellen, ändern, löschen';
        break;
      case 3:
        return 'Standard_Users';
        break;
    }
  }
  
  public function getUserData($status)
  {
    $db                                     = $this->Database;
    $sql                                    = 'SELECT * FROM tbl_users WHERE account_locked = :account_locked';
    $db->query($sql);
    $db->bind(':account_locked', $status);
    return $db->resultset();
  }
  
  public function changeAccountStatus($uuid, $status)
  {
    if ($status                             == 0) {
      $newStatus                            = 1;
    } else {
      $newStatus                            = 0;
    }
    
    $updateArray                            = array(
        'account_locked'                    => $newStatus,
    );
    $whereCause                             = 'uuid = :uuid';
    $whereVal                               = $uuid;
    pdoDbUpdate("tbl_users", $updateArray, $whereCause, $whereVal);
    
  }
  
  public function checkUserPic($uuid)
  {
    $userPic                                = $this->getUserPic($uuid);
    
    if ($userPic                            != "") {
      return '<img src="' . HOME_DIR_HTML . '/users/images/' . $userPic . '" alt="" width="250" />';
    } else {
      return '<img src="' . HOME_DIR_HTML . '/images/noimg.png" alt="" />';
    }
  }
  
  public function showUserPic($uuid)
  {
    $userPic                                = $this->getUserPic($uuid);
    
    if ($userPic                            != "") {
      return '<img src="' . HOME_DIR_HTML . '/users/images/' . $userPic . '" alt="" width="150" />';
    } else {
      return '<img src="' . HOME_DIR_HTML . '/images/noimg.png" alt="" width="150" />';
    }
  }
  
  public function getUserPic($uuid)
  {
    $db                                     = $this->Database;
    $sql                                    = 'SELECT pic FROM tbl_users WHERE uuid = :uuid';
    $db->query($sql);
    $db->bind(':uuid', $uuid);
    $row                                    = $db->single();
    return $row['pic'];
  }
  
  public function showDropdownValYesNo()
  {
    $dropdownArray                          = array(
        'Nein'                              => 0,
        'Ja'                                => 1,
    );
    return $dropdownArray;
  }
  
  public function getClientDataByUUID($uuid)
  {
    $db                                     = $this->Database;
    $sql                                    = 'SELECT * FROM kunden WHERE uuid = :uuid';
    $db->query($sql);
    $db->bind(':uuid', $uuid);
    return $db->single();
  }
  
  
}

