<?php
class Login {

  private $db;

  public function __construct() {
    $this->db = new Db_layer();
  }

  //---[CZ]: zjistíme práva přihlášeného uživatele
  public function check_rights() {
    if (isset($_COOKIE["user_check"])) {
    $sql=$this->db->query("SELECT rights FROM ".TABLE_USERS." WHERE user_check='".$this->db->escape($_COOKIE["user_check"])."'");
    $sql=$this->db->fetch_array($sql);
    return $sql["rights"];
    } else {
    return 0;
    }
  }
  
  //---[CZ]: přihlášení
  public function login() {
    $sql=$this->db->query("SELECT id FROM ".TABLE_USERS." WHERE login='".$this->db->escape($_POST["login"])."' AND password='".SHA1($_POST["password"])."'");
    $sql=$this->db->fetch_array($sql);
    if ($sql["id"]!="") {
    $check=sha1(mt_rand(0, 1000000)+time());
    
    $_SESSION["user_id"]=$sql["id"];
    setcookie("user_check", $check, time()+3600*24*30*12);
    
    $sql=$this->db->query("UPDATE ".TABLE_USERS." SET lastvisit=".time().", user_check='$check' WHERE id=".$sql["id"]);
    
    header("Location: ".$_SERVER["HTTP_REFERER"]);
    } else {
    header("Location: ".$_SERVER["HTTP_REFERER"]);
    }
  }
  
  public function autologin() {
    $sql=$this->db->query("SELECT id FROM ".TABLE_USERS." WHERE user_check='".$this->db->escape($_COOKIE["user_check"])."'");
    $sql=$this->db->fetch_array($sql);
    if ($sql["id"]!="") {
    $_SESSION["user_id"]=$sql["id"];
    }
  }
  
  //---[CZ]: odhlášení
  public function logout() {
    session_destroy();
    setcookie("user_check", "", time()-1);
    header("Location: ".$_SERVER["HTTP_REFERER"]);
  }

}
?>