<?php

namespace Dolphy\Plugin\Security;

use Dolphy\Plugin\Exceptions\Exception;
use Dolphy\Plugin\Helpers\DB;
use Dolphy\Plugin\Helpers\User;
use WP_User;

final class Login {

  public static function actions(WP_User $user) {
    $actions = apply_filters('dolphy_login_actions', array(), $user);
    if (!is_array($actions)) $actions = array();
    return $actions;
  }

  public static function verifyActions(WP_User $user, $code) {
    $verified = apply_filters('dolphy_login_verify_actions', true, $user, $code);
    if (!is_bool($verified)) $verified = false;
    return $verified;
  }

  public static function completeActions(WP_User $user, $code) {
    do_action('dolphy_login_complete_actions', $user, $code);
  }

  /**
   * Complete Login
   *
   * @param string $code
   *  DPLC Code
   *
   * @return mixed
   */
  public static function complete($code) {
    if (!($dplc = DPLC::findByCode($code))) {
      throw new Exception('Invalid DPLC code.', 400);
    }

    if (!($user = User::findBy('id', $dplc->userId))) {
      throw new Exception('No such user', 400);
    }

    if (!self::verifyActions($user, $dplc->code)) {
      throw new Exception('Unable to sign in. Please try again later.');
    }

    $remember = (bool)$dplc->remember;
    $secure = (bool)$dplc->secure;

    wp_set_auth_cookie($user->ID, $remember, $secure);

    DPLC::removeBy('code', $dplc->code);

    self::completeActions($user, $dplc->code);
  }

}
