<?php
namespace nur\v\vp;

use nur\authz;
use nur\config;
use nur\F;
use nur\msg;
use nur\P;
use nur\v\fo;
use nur\v\icon;
use nur\v\ly;
use nur\v\page;
use nur\v\plugins\navigatePlugin;
use nur\v\v;
use nur\v\vo;

trait TTwoLoginPage {
  function TLoginPage_prepare(): void {
    $this->addPlugin(navigatePlugin::class);
  }
  function prepare(): void {
    parent::prepare();
    $this->TLoginPage_prepare();
  }

  function TLoginPage_afterConfig(): void {
    # initialiser la session avant setup. ainsi, dans les fonction beforeSetup(),
    # setup() et afterSetup(), la session est disponible
    $username = P::get("u");
    $password = P::get("p");
    $destPage = F::get("d", $this->getMainUrl());
    $this->ensureFormLoginAndRedirect($username, $password, $destPage);
    $this->flDestPage = $destPage;

    authz::manager()->checkSession($flcUsername, $flcAuthType);
    if ($flcAuthType === "cas" && F::get("a")) {
      # autologin
      $casauthUrl = config::k("url")."/".$this->getCasauthUrl();
      page::redirect(page::bu($this->getCasLoginUrl(), [
        "service" => page::bu($casauthUrl, [
          "r" => $this->getLoginUrl(),
          "d" => $this->flDestPage,
        ])
      ]));
    }
    $this->flcUsername = $flcUsername;
    $this->flcAuthType = $flcAuthType;
  }
  function afterConfig(): void {
    $this->TLoginPage_afterConfig();
    parent::afterConfig();
  }

  function TLoginPage_setup(): void {
    $casLogin = false;
    $casLayout = null;
    $formLogin = false;
    $formLayout = null;
    switch (config::k("auth_type")) {
    case "cas":
      $casLogin = true;
      $casLayout = ["sm" => 6, "sm-push" => 3];
      break;
    case "form":
      $formLogin = true;
      $formLayout = ["sm" => 6, "sm-push" => 3];
      break;
    case "both":
    default:
      $casLogin = true;
      $casLayout = ["sm" => 6, "sm-push" => 6];
      $formLogin = true;
      $formLayout = ["sm" => 6, "sm-pull" => 6];
      break;
    }
    $this->casLogin = $casLogin;
    $this->casLayout = $casLayout;
    $this->formLogin = $formLogin;
    $this->formLayout = $formLayout;
  }
  function setup(): void {
    parent::setup();
    $this->TLoginPage_setup();
  }

  private $flDestPage = null;
  private $flcUsername = null;
  private $flcAuthType = null;

  private $casLogin, $casLayout;
  private $formLogin, $formLayout;

  function getUseCasContext(): ?array {
    return v::p("Si vous avez un compte à l'université, vous DEVEZ vous connecter via CAS");
  }

  function getUseFormContext(): ?array {
    return v::p("La connexion par formulaire est réservée pour les cas particulier (vacataires, etc.)");
  }

  function print(): void {
    page::no_cache();
    $username = P::get("u");
    $password = P::get("p");

    ly::row();

    $this->printTitle();
    $status = authz::get_status();
    switch ($status) {
    case authz::DISCONNECTED:
      msg::warning("Vous avez été déconnecté. Veuillez vous reconnecter");
      break;
    case authz::UNAUTHORIZED:
      msg::error(["user" => [
        "Connecté en tant que ",
        v::b(authz::get_auth()),
        ", vous n'êtes pas autorisé à accéder à la page que vous avez demandé.",
      ]]);
      break;
    }

    if ($this->casLogin) {
      ly::col($this->casLayout);
      ly::panel("Connexion par CAS");
      $useCasContext = $this->getUseCasContext();
      if ($useCasContext !== null) vo::p($useCasContext);
      if ($this->isDevauthAllowed()) {
        fo::start([
          "type" => "basic",
          "action" => $this->getCasauthUrl(),
          "method" => "get",
        ]);
        fo::hidden("r", $this->getLoginUrl());
        fo::hidden("d", $this->flDestPage);
      } else {
        fo::start([
          "type" => "basic",
          "action" => $this->getCasLoginUrl(),
          "method" => "get",
        ]);
        $casauthUrl = config::k("url")."/".$this->getCasauthUrl();
        fo::hidden("service", page::bu($casauthUrl, [
          "r" => $this->getLoginUrl(),
          "d" => $this->flDestPage,
        ]));
      }
      if (authz::is_auth() && $this->flcAuthType === "cas") {
        if ($status != authz::UNAUTHORIZED) {
          msg::warning(["user" => [
            "Connecté en tant que ",
            v::b(authz::get_auth()),
            ", vous n'êtes pas autorisé à accéder à cette application.",
          ]]);
        }
        fo::submit([icon::logout("Vous déconnecter"),
          "formaction" => $this->getLogoutUrl(),
          "accesskey" => "z",
        ]);
        fo::hidden("renew", "true");
        fo::submit([
          icon::login("Changer de compte"),
          "accesskey" => "r",
        ]);
      } else {
        fo::submit(["Connexion par CAS", "accesskey" => "r"]);
      }
      fo::end();
    }

    if ($this->formLogin) {
      ly::col($this->formLayout);
      ly::panel("Connexion avec identifiant/mot de passe");
      $useFormContext = $this->getUseFormContext();
      if ($useFormContext !== null) vo::p($useFormContext);
      fo::start([
        "type" => "basic",
        "action" => "",
        "method" => "post",
      ]);
      fo::hidden("ret_url", $this->getLoginUrl());
      fo::text("Identifiant", "u", $username?: $this->flcUsername, [
        "accesskey" => "q",
        "placeholder" => "Votre identifiant",
      ]);
      fo::password("Mot de passe", "p", $password, [
        "placeholder" => "Votre mot de passe",
      ]);
      if ($username || $password) {
        msg::error("$username: Votre identifiant et/ou votre mot de passe sont incorrects");
      } elseif ($username === "") {
        msg::error("Vous devez saisir votre identifiant");
      } elseif ($password === "") {
        msg::error("Vous devez saisir votre mot de passe");
      }
      fo::submit(["Connexion", "accesskey" => "f"]);
      if (authz::is_auth() && $this->flcAuthType === "form") {
        msg::warning(["user" => [
          "Connecté en tant que ",
          v::b(authz::get_auth()),
          ", vous n'êtes pas autorisé à accéder à cette application.",
        ]]);
        fo::submit([
          "Vous déconnecter", "accesskey" => "z",
          "formmethod" => "get", "formaction" => $this->getLogoutUrl(),
        ]);
      }
      fo::end();
    }

    ly::end();
  }
}
