<?php
namespace App\User;
use App\Core\AbstractController;

class LoginController extends AbstractController {

  public function __construct(LoginService $loginService){
    $this->loginService = $loginService;
  }

  public function index(){
    $this->loginService->index();
    $this->render("user/index", []);
  }

  public function blog(){
    $this->loginService->blog();
    $this->render("user/blog", []);
  }

  public function hbc(){
    $this->loginService->hbc();
    $this->render("user/hbc", []);
  }

  public function stb(){
//    $this->loginService->stb();
    $this->loginService->check();
    $this->render("user/stb", []);
  }

  public function fotos(){
    $this->loginService->fotos();
    $this->render("user/fotos", []);
  }

  public function impressum(){
    $this->loginService->impressum();
    $this->render("user/impressum", []);
  }

  public function admin(){
    $this->loginService->check();
    //$this->loginService->admin();
    $this->render("user/admin", []);
  }

  public function dashboard(){
    //$this->loginService->check();
    $this->render("user/dashboard", []);
  }

  public function settings() {
    echo "<br><br><br>";
    $msg = "";
    if (isset($_GET['id'])) {
      $id = $_GET['id'] - 1;
      $_SESSION['id'] = $id;
    }

    if (isset($_GET['save'])) {
      $save = $_GET['save'];
      echo $msg = $this->loginService->saveOneUser();
    }
    $users = $this->loginService->getAllUsers();    // ok
    if (isset($_SESSION['id'])) {
      echo $id = $_SESSION['id'];
    }else{$id=0;}
      $user = $users[$id];

    echo "<br>";
    $this->render("user/settings", [
      'users' => $users,
      'user' => $user,
      'msg' => $msg
    ]);
  }

  public function logout() {
    $this->loginService->logout();
    $this->render("user/logout", []);
    //header("Location: user/login");        // weiterleitung zum login
  }

  public function login(){
    $error = false;
    if(!empty($_POST['username']) And !empty($_POST['password'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];
        if ($this->loginService->attempt($username, $password)) {
          if ($_SESSION['rechte'] == "admin") {
            $users = $this->loginService->getAllUsers();
            $_SESSION['login'] = $username;
            //$_SESSION['id'] = $user['id'];
            $this->render("user/admin", [
              'users' => $users
            ]);
            return;
          } else {
            header ("Location: dashboard");
            return;
          }
        } else { $error = true; }
      }
      $this->render("user/login", [
        'error' => $error               // Übergabe an view
      ]);
    }   // end login
  } // end class ?>
