<?php
class FormFmRestorePassword extends CDController{

  public function __construct() {
    $this->view = 'fm/partials/forms/form-restore-password.twig';

    CDAjaxHandler::localize_js_object(
      'creativedog_timber_theme-main',
      'restore_password_controller_object',
      'form_fm_restore_password',
      'restore_password'
    );



  }


  public static function ajax_restore_password(){
    check_ajax_referer( 'restore_password', '_nonce' );

  	$email = $_POST['email'];

    if( email_exists( $email ) ){
      $user = get_user_by( 'email', $email );
      $new_password = wp_generate_password();
      wp_set_password( $new_password, $user->ID );

      $is_sent = self::send_new_password_notification($email, $new_password);

      $response = json_encode(
        array(
          "success" => true,
          'is_sent' => $is_sent
        )
      );
    }else{
      $response =  json_encode(array("error" => true, "message" => 'No se ha encontrado el usuario relacionado con el email.'));
      exit();
    }

    echo $response;
    exit();
  }

  private static function send_new_password_notification($email, $new_password){

    $notification = new Notification();

    $email_data = $notification->restorePassword($email, $new_password);

    return $email_data;
  }

}
