<?php

namespace Salesloo\Frontend;

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

use \Salesloo\Abstracts\Frontend;

/**
 * Salesloo Register
 */
class Register extends Frontend
{

    /**
     * construct
     */
    public function __construct()
    {
        $this->id = 'register';
        $this->template = 'register.php';
        $this->target = 'guest';
        $this->title = __('Regsiter', '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'], '/register') === false) return;

        if (wp_verify_nonce($_POST['__nonce'], 'salesloo-register')) {
            $post = $_POST;

            $alert = '';

            $full_name = isset($post['full_name']) ? sanitize_text_field($post['full_name']) : '';
            $fullname  = explode(' ', $full_name);

            $fname    = isset($fullname[0]) ? $fullname[0] : '';
            $lname    = isset($fullname[1]) ? $fullname[1] : '';
            $username = isset($post['username']) ? sanitize_text_field(strtolower($post['username'])) : '';
            $email    = isset($post['email']) ? sanitize_email($post['email']) : '';
            $pass1    = isset($post['password']) ? sanitize_text_field($post['password']) : '';
            $pass2    = isset($post['password2']) ? sanitize_text_field($post['password2']) : '';

            if (empty($fname)) {
                $alert = __('Please input your name!', 'salesloo');
            } else if (username_exists($username)) {
                $alert = __('Username is not available, please choose another username', 'salesloo');
            } else if (!is_email($email)) {
                $alert = __('Email is not valid', 'salesloo');
            } else if (email_exists($email)) {
                $alert = __('There is already a user registered with this email. Login with this existing account. If you do not remember your password, you will find a recuperation link at the login form.', 'salesloo');
            } else if ($pass1 == '' || $pass1 != $pass2) {
                $alert = __('Passwords must be identical and filled', 'salesloo');
            }

            if (empty($alert)) {
                $user_id = wp_create_user($username, $pass1, $email);

                if (is_wp_error($user_id)) {
                    $alert = $user_id->get_error_message();
                } else {
                    $userdata = [
                        'ID' => $user_id
                    ];
                    $userdata['first_name'] = $fname;
                    $userdata['last_name']  = $lname;
                    if (isset($post['phone'])) {
                        $userdata['phone'] = $post['phone'];
                    }
                    wp_update_user($userdata);

                    unset($post['__nonce']);
                    unset($post['_wp_http_referer']);
                    unset($post['full_name']);
                    unset($post['email']);
                    unset($post['password']);
                    unset($post['password2']);

                    foreach ((array)$post as $key => $value) {
                        $value = is_array($value) ? $value : sanitize_text_field($value);
                        add_user_meta($user_id, sanitize_text_field($key), $value);
                    }

                    $notification_args = [
                        'event' => 'register',
                        'data' => [
                            'user_id' => $user_id
                        ]
                    ];
                    salesloo_insert_notification($notification_args);
                    salesloo_insert_event([
                        'name' => 'register',
                        'data' => [
                            'user_id' => $user_id
                        ]
                    ]);

                    $message = __('Thanks for registering, Please login!', 'salesloo');
                    setcookie('register_success', $message, time() + 60, COOKIEPATH, COOKIE_DOMAIN);

                    wp_redirect(salesloo_url_login());
                    exit;
                }
            }

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

    public function load()
    {
    }
}
