<?php

namespace Persian_Flatsome;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;

class Activator
{

    /**
     * The single instance of the class.
     *
     * @var Activator
     */
    protected static $_instance = null;
    public static $terms_url = 'https://mojtaba.dev/terms/';
    public $token;
    private static $version;
    private $title;
    private $path;
    private $url;
    private $parent_slug;
    private $text_domain = 'flatsome-activator';
    private $page_title;
    private $menu_title;
    private $is_licensed;
    public static $option_name;
    private static $requester;

    private function __construct($product_token, $product_title, $version, $parent_slug, $is_licensed)
    {
        $this->token = $product_token;
        $this->title = $product_title;
        self::$version = $version;
        $this->path = plugin_dir_path(__FILE__);
        $this->url = plugin_dir_url(__FILE__);
        $this->parent_slug = $parent_slug;
        $this->is_licensed = $is_licensed;
        self::$option_name = 'fls_lncs_data';
        require_once($this->path . 'libraries/Request.php');
        self::$requester = new Request();

        add_action('plugins_loaded', [$this, 'localization']);
        add_action('admin_menu', [$this, 'admin_menu'], 99);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('wp_ajax_guard_flatsome_activator', [$this, 'activate']);
        add_action('wp_ajax_guard_flatsome_deactivator', [$this, 'deactivate']);
        add_action('admin_notices', [$this, 'show_activation_messages'], 15);
    }

    /**
     * Main Instance.
     *
     * Ensures only one instance of WP_Products_Controller is loaded or can be loaded.
     *
     * @static
     * @return Activator - Main instance.
     */
    public static function instance($product_token, $product_title, $version, $parent_slug, $is_licensed = false)
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self($product_token, $product_title, $version, $parent_slug, $is_licensed);
        }

        return self::$_instance;
    }

    /**
     * Make plugin translatable
     */
    public function localization()
    {
        $plugin_rel_path = plugin_basename($this->path) . '/languages';
        load_plugin_textdomain($this->text_domain, false, $plugin_rel_path);
        $this->page_title = sprintf(__('Activate %s', $this->text_domain), $this->title);
        $this->menu_title = __('Activate', $this->text_domain);
        $this->title = __('Flatsome WooCommerce Theme', $this->text_domain);
    }

    public function enqueue_scripts($hook)
    {
        $current_page = str_replace('page_', '', strstr($hook, 'page_'));
        if ($current_page === 'activate-flatsome' || $current_page === sprintf('%s-promotion', $this->parent_slug)) {
            wp_enqueue_style('guard-flatsome-style', $this->url . 'assets/css/guard.css', [], '1.0.0', $media = 'all');
            wp_enqueue_script('guard-flatsome-js', $this->url . 'assets/js/guard.js', ['jquery'], '1.0.0', true);
        }
    }

    /**
     * Add submenu page for display registration form
     */
    public function admin_menu()
    {
        add_submenu_page(
            $this->parent_slug,
            $this->page_title,
            $this->menu_title,
            'manage_options',
            'activate-flatsome',
            [$this, 'menu_content']
        );
    }

    public function menu_content()
    {
        include $this->path . 'view/menu-content.php';
    }


    public function activate()
    {
        $license = (isset($_POST['license']) && !empty($_POST['license'])) ? sanitize_text_field($_POST['license']) : '';
        if ($this->is_licensed && !$license) {
            wp_send_json_error(__('Please enter license code', $this->text_domain));
        }

        $install = self::$requester->install($license, $this->token);
        if ($install->success) {
            update_option(self::$option_name, [
                'time' => time(),
                'license' => $license,
            ]);
            wp_send_json_success(__('Product activated successfully', $this->text_domain));
        } else {
            wp_send_json_error($install->message);
        }
    }

    public function deactivate()
    {
        $delete = delete_option(self::$option_name);
        if ($delete) {
            wp_send_json_success(__('Product deactivated successfully', $this->text_domain));
        }

        wp_send_json_error(__('Deactivation failed! please try again.', $this->text_domain));
    }

    public static function is_active()
    {
        $data = get_option(self::$option_name);

        if (!$data) {
            return false;
        }

        if (time() - $data['time'] > WEEK_IN_SECONDS) {
            $is_active = self::$requester->isValid($data['license']);
            if ($is_active->success) {
                $data['time'] = time();
                update_option(self::$option_name, $data);
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }


    public function show_activation_messages()
    {
        $class = 'notice notice-error';
        $message = sprintf(__('There is something wrong with your <strong>%s</strong> theme. please check it', $this->text_domain), $this->title);
        $is_active = self::is_active();
        if (!$is_active) {
            printf(
                '<div class="%1$s"><p>%2$s <a href="%3$s" class="button-primary">%4$s</a></p></div>',
                esc_attr($class),
                $message,
                admin_url('admin.php?page=activate-flatsome'),
                __('Check status', $this->text_domain)
            );
        }
    }

}
