<?php

namespace Salesloo\Frontend;

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

use \Salesloo\Abstracts\Frontend;

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

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

    public function process_action($req)
    {

        global $___salesloo;

        if ('POST' != $_SERVER['REQUEST_METHOD']) return;

        if (!isset($_POST['__nonce']) || !isset($_POST['_wp_http_referer'])) return;

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

        if (wp_verify_nonce($_POST['__nonce'], 'salesloo-login')) {

            $post = $_POST;

            $alert = '';

            $user_login = isset($post['user']) ? wp_unslash($post['user']) : '';
            $user_password = isset($post['password']) ? $post['password'] : '';

            if (empty($user_login)) {
                $alert = __('Please input your username or email!', 'salesloo');
            } else if ($user_password == '') {
                $alert = __('Passwords must be filled', 'salesloo');
            }

            if (empty($alert)) {

                $credentials = [
                    'user_login' => $user_login,
                    'user_password' => $user_password,
                    'remember' => false
                ];

                $user = wp_signon($credentials);

                if (is_wp_error($user)) {
                    $alert = $user->get_error_message();
                } else {
                    $redirect = salesloo_url_dashboard();

                    if (isset($_GET['redirect'])) {
                        $page = sanitize_text_field($_GET['redirect']);
                        $redirect = site_url('/') . $page . '/';
                    }

                    wp_safe_redirect($redirect);
                    exit;
                }
            }

            $___salesloo['fail'] = $alert;
        }
    }

    public function load()
    {
        global $___salesloo;

        $___salesloo['register_success'] = isset($_COOKIE['register_success']) ? sanitize_text_field($_COOKIE['register_success']) : false;
    }
}
