<?php

namespace Drupal\loginregisterblock\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Symfony\Component\HttpFoundation\RedirectResponse;
// use RedirectDestinationTrait;

/**
 * Provides a 'login register' Block.
 *
 * @Block(
 *   id = "login_register_block",
 *   admin_label = @Translation("Login register block"),
 *   category = @Translation("Loginregister"),
 * )
 */
class LoginRegisterBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $user = \Drupal::currentUser();
    if ($user->id() === 0) {
      $loginform = \Drupal::formBuilder()->getForm('Drupal\user\Form\UserLoginForm');
      $newuser = \Drupal::entityTypeManager()->getStorage('user')->create();
      $registerform = \Drupal::service('entity.form_builder')->getForm($newuser, 'register');
      
      return [
        'login' => [
          '#markup' => '<h1>' . $this->t('Se connecter') . '</h1>',
          'form' => $loginform,
        ],
        'register' => [
          '#markup' => '<h1>' . $this->t('ou créer un nouveau compte') . '</h1>',
          'form' => $registerform
        ]
      ];
    } else {
      $destination = \Drupal::service('redirect.destination')->getAsArray();
      $response = new RedirectResponse($destination['destination']);
      $response->send();
    }
  }


  
}