<?php

use Dolphy\Plugin\Ajax\Action;
use Dolphy\Plugin\Ajax\Request;
use Dolphy\Plugin\Ajax\Response;
use Dolphy\Plugin\Helpers\User;
use Dolphy\Plugin\Security\DPLC;
use Dolphy\Plugin\Security\Login;

defined('DOLPHY_PLUGIN') or die('Access Denied!');

// LOGIN
Action::add('post', 'login', function (Request $request) {
  $username = sanitize_user($request->input('username'));
  $password = sanitize_text_field($request->input('password'));
  $remember = $request->input('remember', false);
  if (!is_bool($remember)) $remember = false;

  $user = wp_authenticate($username, $password);

  if (is_wp_error($user)) {
    $response = strip_tags($user->get_error_message());
    Response::send($response, 400);
  }

  $credentials['user_login'] = $user->user_login;
  $credentials['user_password'] = $password;
  $credentials['remember'] = $remember;

  $secure = is_ssl();
  $secure = apply_filters('secure_signon_cookie', $secure, $credentials);

  $dplc = DPLC::create($user->ID, $remember, $secure);

  $data['redirect'] = $request->input('redirect', admin_url('/'));
  $data['actions'] = Login::actions($user);
  $data['dplc'] = $dplc->code;

  Response::send($data);
});

// POST LOGIN
Action::add('post', 'post_login', function (Request $request) {
  $code = sanitize_text_field($request->input('dplc'));

  Login::complete($code);

  Response::send('Login Successful!');
});


// FORGOT PASSWORD
Action::add('post', 'forgot_password', function (Request $request) {
  $username = $request->input('username');

  if (strpos($username, '@')) {
    $username = sanitize_email($username);
    $field = 'email';
  } else {
    $username = sanitize_user($username);
    $field = 'login';
  }

  if (!($user = User::findBy($field, $username))) {
    throw new Exception('No such user', 404);
  }

  $errors = new WP_Error();

  do_action('lostpassword_post', $errors, $user);

  $errors = apply_filters('lostpassword_errors', $errors, $user);

  if ($errors->has_errors()) {
    $response = strip_tags($errors->get_error_message());
    Response::send($response, 400);
  }

  // Redefining user_login ensures we return the right case in the email.
  $user_login = $user->user_login;
  $user_email = $user->user_email;
  $key = get_password_reset_key($user);

  if (is_wp_error($key)) {
    $response = strip_tags($key->get_error_message());
    Response::send($response, 400);
  }

  if (is_multisite()) {
    $site_name = get_network()->site_name;
  } else {
    $site_name = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
  }

  $message = __('Someone has requested a password reset for the following account:') . "\r\n\r\n";
  /* translators: %s: Site name. */
  $message .= sprintf(__('Site Name: %s'), $site_name) . "\r\n\r\n";
  /* translators: %s: User login. */
  $message .= sprintf( __('Username: %s'), $user_login) . "\r\n\r\n";
  $message .= __('If this was a mistake, ignore this email and nothing will happen.') . "\r\n\r\n";
  $message .= __('To reset your password, visit the following address:') . "\r\n\r\n";
  $message .= network_site_url(DOLPHY_RESETPASSWORD_PATH."?key={$key}&login=".rawurlencode($user_login), 'login') . "\r\n\r\n";

  if ($requester_ip = $_SERVER['REMOTE_ADDR']) {
    $message .= sprintf(
      /* translators: %s: IP address of password reset requester. */
      __('This password reset request originated from the IP address %s.'),
      $requester_ip
    ) . "\r\n";
  }

  /* translators: Password reset notification email subject. %s: Site title. */
  $title = sprintf(__('[%s] Password Reset'), $site_name);
  $title = apply_filters('retrieve_password_title', $title, $user_login, $user);

  $message = apply_filters('retrieve_password_message', $message, $key, $user_login, $user);

  if ($message && !wp_mail($user_email, wp_specialchars_decode($title), $message)) {
    $errors->add(
      'retrieve_password_email_failure',
      __('Error: The email could not be sent. Your site may not be correctly configured to send emails.')
    );

    $response = strip_tags($errors->get_error_message());
    Response::send($response, 500);
  }

  $response = "A message has been sent to the email associated with this account.";
  $response .= " Kindly follow the instructions to recover your account.";
  Response::send($response);
});


Action::add('post', 'reset_password', function (Request $request) {
  $password = sanitize_text_field($request->input('password'));
  $login = sanitize_user($request->input('login'));
  $key = sanitize_key($request->input('key'));

  if (empty($login) || empty($password)) {
    Response::send('Invalid request', 400);
  }

  $user = check_password_reset_key($key, $login);

  if (is_wp_error($user)) {
    $response = strip_tags($user->get_error_message());
    Response::send($response, 400);
  }

  reset_password($user, $password);

  $data['message'] = 'Password Successfully Changed!';
  $data['redirect'] = wp_login_url();

  Response::send($data);
});


Action::add('post', 'signup', function (Request $request) {
  $email = sanitize_email($request->input('email'));
  $username = sanitize_user($request->input('username'));
  $password = sanitize_text_field($request->input('password'));

  if (empty($email)) Response::send('Email address is required', 400);
  if (!is_email($email)) Response::send('Email address does not appear to be valid', 400);
  if (empty($username)) Response::send('Username is required', 400);
  if (empty($password)) Response::send('Password is required', 400);

  $userId = wp_create_user($username, $password, $email);

  if (is_wp_error($userId)) {
    $response = strip_tags($userId->get_error_message());
    Response::send($response, 400);
  }

  $data['message'] = 'Registration Successful!';
  $data['redirect'] = wp_login_url();

  Response::send($data);
});
