<?php
namespace nur\v\vp;

use nur\A;
use nur\authz;
use nur\config;
use nur\F;
use nur\v\base\AbstractPage;
use nur\v\page;

class AppExtauthPage extends AbstractPage {
  /**
   * @var bool faut-il afficher les variables au lieu de rediriger vers
   * $ret_url?
   */
  const DEBUG = false;

  function isDebug(): bool {
    if (!config::is_devel()) return false;
    return static::DEBUG || F::get("D");
  }

  /** @var string nom de l'utilisateur connecté */
  private $user;

  function setup() {
    $destUrl = null;
    $user = false;
    if ($user === false) $user = A::get($_SERVER, "REMOTE_USER", false);
    if ($user === false) $user = A::get($_SERVER, "HTTP_REMOTE_USER", false);
    if ($user === false) $user = A::get($_SERVER, "HTTP_X_REMOTE_USER", false);
    if ($user) {
      if (authz::manager()->extLogin($user)) {
        $destUrl = F::get("d");
        if ($destUrl && !$this->isDebug()) page::redirect($destUrl);
      }
    } else {
      $user = "NONE";
    }

    $this->user = $user;
    $this->destUrl = $destUrl;
  }

  private $destUrl;

  function print(): void {
    page::content_type("text/plain");
    page::no_cache();
    if ($this->isDebug()) {
      echo "destUrl: $this->destUrl\n";
      echo "--- \$_SERVER\n\n";
      foreach ($_SERVER as $name => $value) {
        echo "$name: $value\n";
      }
      echo "\n--- \$_REQUEST\n\n";
      foreach ($_REQUEST as $name => $value) {
        echo "$name: $value\n";
      }
      echo "\n--- \$_SESSION\n\n";
      foreach ($_SESSION as $name => $value) {
        echo "$name: ".var_export($value, true)."\n";
      }
    } else {
      echo $this->user;
    }
  }
}
