<?php

namespace EesyPHP\Auth;

use EesyPHP\App;
use EesyPHP\Auth;
use EesyPHP\Hook;
use EesyPHP\I18n;
use EesyPHP\Url;
use EesyPHP\Tpl;

class Form extends Method {

  /**
   * Initialize
   * @return boolean
   */
  public static function init() {
    // Set config default values
    App :: set_default(
      'auth.login_form',
      array(
        'display_other_methods' => array(),
        'include_navbar' => true,
        'remember_username' => true,
        'remember_username_cookie_name' => 'remember_username',
      )
    );
    Url :: add_url_handler('#^login$#', array('EesyPHP\\Auth\\Form', 'handle_login'), null, false);
    Hook :: register('logged_in', array('\\EesyPHP\\Auth\\Form', 'logged_in_hook'));
    return true;
  }

  /**
   * Log user
   * @param bool $force Force user authentication
   * @return \EesyPHP\Auth\User|null
   */
  public static function login($force=false) {
    $user = null;
    if (isset($_REQUEST['username']) && isset($_REQUEST['password'])) {
      $user = Auth :: authenticate($_REQUEST['username'], $_REQUEST['password']);
      if ($user) {
        setcookie(
          App::get('auth.login_form.remember_username_cookie_name'),
          App::get('auth.login_form.remember_username') && isset($_REQUEST['remember-username'])?
          $user->username:null
        );
      }
      else
        Tpl::add_error(_('Invalid username or password.'));
    }
    if ($force && !$user) {
      if (Url :: get_current_url() != 'login')
        Url :: redirect('login?next='.urlencode(Url :: get_current_url()));
      return null;
    }
    return $user;
  }

  /**
   * The login form view
   * @param \EesyPHP\UrlRequest $request
   * @return void
   */
  public static function handle_login($request) {
    $user = Auth :: login(false, 'Form');
    $display_other_methods = array();
    foreach (App::get('auth.login_form.display_other_methods', array(), 'array') as $method => $label)
      if (Auth::method_is_enabled($method))
        $display_other_methods[$method] = $label;
    if (
      !$user && isset($_REQUEST['method']) &&
      array_key_exists($_REQUEST['method'], $display_other_methods)
    ) {
      $user = Auth :: login($_REQUEST['method'], $_REQUEST['method']);
    }
    if ($user)
      Url :: redirect(isset($_REQUEST['next'])?urldecode($_REQUEST['next']):null);

    $remember_username = App::get('auth.login_form.remember_username', null, 'bool');
    Tpl :: assign('remember_username', $remember_username);
    if ($remember_username) {
      $cookie_name = App::get('auth.login_form.remember_username_cookie_name');
      Tpl :: assign('username', isset($_COOKIE[$cookie_name])?$_COOKIE[$cookie_name]:null);
    }

    Tpl :: assign('next', isset($_REQUEST['next'])?urldecode($_REQUEST['next']):'');
    Tpl :: assign('display_other_methods', $display_other_methods);
    Tpl :: assign('include_navbar', App::get('auth.login_form.include_navbar', null, 'bool'));
    Tpl :: display('login.tpl', I18n::_('Sign in'));
  }

  /**
   * Logged in hook
   * @param \EesyPHP\HookEvent $event
   * @return void
   */
  public static function logged_in_hook($event) {
    if ($event->method == 'Form' && isset($_REQUEST['next']))
      Url :: redirect(urldecode($_REQUEST['next']));
  }
}
