<?php

namespace Salesloo\Rest_Api;

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

use \Salesloo\Abstracts\Rest_Api;


/**
 * Payment Method
 */
class User extends Rest_Api
{
    protected $version = 'v1';

    protected $route = 'user';

    /**
     * register new route
     * 
     */
    public function register_routes()
    {
        register_rest_route(
            $this->namespace,
            '/' . $this->version . '/' . $this->route . '/check-email',
            [
                'methods'             => \WP_REST_Server::CREATABLE,
                'callback'            => [$this, 'check_email'],
                'permission_callback' => [$this, 'permissions_check_email'],
            ],
        );
    }

    /**
     * check email method permissions
     */
    public function permissions_check_email(\WP_REST_Request $request)
    {
        $params = $request->get_params();

        if (isset($params['nonce']) && salesloo_verify_nonce($params['nonce'])) {
            return true;
        }

        return false;
    }

    /**
     * check email
     */
    public function check_email(\WP_REST_Request $request)
    {
        $params = $request->get_params();

        $respons = [
            'message' => __('Bad or Invalid Request', 'salesloo')
        ];

        if (!isset($params['value']) || !isset($_COOKIE['wp_salesloo_cart'])) {
            return new \WP_REST_Response($respons, 400);
        }

        if (!$params['value']) {
            $respons = [
                'message' => __('Please type your email address', 'salesloo')
            ];
            return new \WP_REST_Response($respons, 400);
        }

        $cart_key = sanitize_text_field($_COOKIE['wp_salesloo_cart']);
        $cookie   = json_decode(salesloo_decrypt($cart_key), true);

        if (!isset($cookie[0]) || !isset($cookie[1])) {
            return new \WP_REST_Response($respons, 400);
        }

        $email = sanitize_email($params['value']);

        if (!is_email($email)) {
            $respons = [
                'message' => __('Please insert a valid email address', 'salesloo'),
            ];

            return new \WP_REST_Response($respons, 400);
        }

        if (email_exists($email)) {
            $respons = [
                'message' => sprintf(__('"%s" has been registered, please loggedin or use another email address', 'salesloo'), $email),
            ];

            return new \WP_REST_Response($respons, 404);
        }


        $respons = [
            'message' => sprintf(__('Congratulation, Your email "%s" has not been registered', 'salesloo'), $email),
        ];

        return new \WP_REST_Response($respons, 200);
    }



    /**
     * Settings Constructor
     */
    public function __construct()
    {

        add_action('salesloo/rest_api/init', [$this, 'register_route']);
    }
}
