<?php

namespace Salesloo\Frontend;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

use \Salesloo\Abstracts\Frontend;

/**
 * Salesloo Login
 */
class Reset_Password extends Frontend
{

    /**
     * construction
     */
    public function __construct()
    {
        $this->id = 'login/reset-password';
        $this->template = 'reset-password.php';
        $this->target = 'guest';
        $this->title = __('Reset Password', 'salesloo');
    }

    /**
     * process action
     */
    public function process_action($req)
    {

        if (isset($_POST['_wp_http_referer']) && strpos($_POST['_wp_http_referer'], '/login/lostpassword' === false)) return;

        if (isset($_POST['__nonce']) && wp_verify_nonce($_POST['__nonce'], 'salesloo-reset-password')) {

            if (isset($_POST['user_login'])) {

                $reset = \retrieve_password();

                if (is_wp_error($reset)) {

                    $alert = $reset->get_error_message();
                    setcookie('reset_failed', $alert, time() + 60, COOKIEPATH, COOKIE_DOMAIN);
                } else {

                    $message = __('Password reset email has been sent. Please check your email and follow reset password instruction', 'salesloo');
                    setcookie('reset_success', $message, time() + 60, COOKIEPATH, COOKIE_DOMAIN);
                }
            }

            wp_redirect(salesloo_url_login() . 'lostpassword');
            exit;
        }
    }

    public function load()
    {
        global $salesloo_data;

        $salesloo_data['alert'] = (object)[
            'resetFailed' => isset($_COOKIE['reset_failed']) ? sanitize_text_field($_COOKIE['reset_failed']) : false,
            'resetSuccess' => isset($_COOKIE['reset_success']) ? sanitize_text_field($_COOKIE['reset_success']) : false,
        ];
    }
}
