<?php

/**
 * The file that defines the core plugin class
 *
 * A class definition that includes attributes and functions used across both the
 * public-facing side of the site and the admin area.
 *
 * @link       https://wwdh.de
 * @since      1.0.0
 *
 * @package    Wp_Oauth2_Client
 * @subpackage Wp_Oauth2_Client/includes
 */

use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFilter;
use WPOauth2\Client\Api_Product_Handle;
use WPOauth2\Client\OAuth2_Sync_Cronjob;
use WPOauth2\Client\Oauth_Client_Callback;
use WPOauth2\Client\WP_Oauth_Helper;

/**
 * The core plugin class.
 *
 * This is used to define internationalization, admin-specific hooks, and
 * public-facing site hooks.
 *
 * Also maintains the unique identifier of this plugin as well as the current
 * version of the plugin.
 *
 * @since      1.0.0
 * @package    Wp_Oauth2_Client
 * @subpackage Wp_Oauth2_Client/includes
 * @author     Jens Wiecker <plugin@wwdh.de>
 */
class Wp_Oauth2_Client
{

    /**
     * The loader that's responsible for maintaining and registering all hooks that power
     * the plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      Wp_Oauth2_Client_Loader $loader Maintains and registers all hooks for the plugin.
     */
    protected Wp_Oauth2_Client_Loader $loader;

    /**
     * Store plugin main class to allow public access.
     *
     * @since    1.0.0
     * @var object The main class.
     */
    protected object $main;

    /**
     * The plugin Slug Path.
     *
     * @since    1.0.0
     * @access   protected
     * @var      string $plugin_slug plugin Slug Path.
     */
    protected string $plugin_slug;

    /**
     * The current database version of the plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      string $db_version The current database version of the plugin.
     */
    protected string $db_version;

    /**
     * TWIG autoload for PHP-Template-Engine
     * the plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      Environment $twig TWIG autoload for PHP-Template-Engine
     */
    private Environment $twig;

    /**
     * The unique identifier of this plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      string $plugin_name The string used to uniquely identify this plugin.
     */
    protected string $plugin_name;

    /**
     * The current version of the plugin.
     *
     * @since    1.0.0
     * @access   protected
     * @var      string $version The current version of the plugin.
     */
    protected string $version = '';

    private int $get_oauth_save_pin;

    private array $oauth_client_settings;

    private bool $wp_disabled_cron;

    /**
     * Define the core functionality of the plugin.
     *
     * Set the plugin name and the plugin version that can be used throughout the plugin.
     * Load the dependencies, define the locale, and set the hooks for the admin area and
     * the public-facing side of the site.
     *
     * @throws LoaderError
     * @since    1.0.0
     */
    public function __construct()
    {
        $this->plugin_name = WP_OAUTH2_CLIENT_BASENAME;
        $this->plugin_slug = WP_OAUTH2_CLIENT_SLUG_PATH;
        $this->main = $this;

        if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
            $this->wp_disabled_cron = false;
        } else {
            $this->wp_disabled_cron = true;
        }

        /**
         * Currently plugin version.
         * Start at version 1.0.0 and use SemVer - https://semver.org
         * Rename this for your plugin and update it as you release new versions.
         */
        $plugin = get_file_data(plugin_dir_path(dirname(__FILE__)) . $this->plugin_name . '.php', array('Version' => 'Version'), false);
        if (!$this->version) {
            $this->version = $plugin['Version'];
        }

        if (defined('WP_OAUTH2_CLIENT_DB_VERSION')) {
            $this->db_version = WP_OAUTH2_CLIENT_DB_VERSION;
        } else {
            $this->db_version = '1.0.0';
        }
        $time = date('dm', current_time('timestamp'));
        $this->get_oauth_save_pin = $time . str_replace(['.', 'v'], '', $this->version);

        $this->check_dependencies();
        $this->load_dependencies();

        $twigAdminDir = plugin_dir_path(dirname(__FILE__)) . 'admin' . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR;
        $twig_loader = new FilesystemLoader($twigAdminDir);
        $twig_loader->addPath($twigAdminDir . 'Templates', 'templates');
        $this->twig = new Environment($twig_loader);
        $language = new TwigFilter('__', function ($value) {
            return __($value, 'wp-oauth2-client');
        });
        $this->twig->addFilter($language);

        $this->oauth2_client_helper();
        $this->register_product_api_handle();

        $this->set_locale();
        $this->oauth2_client_remote();
        $this->register_cron_oauth2_client();
        $this->define_admin_hooks();
        $this->define_public_hooks();

    }

    /**
     * Load the required dependencies for this plugin.
     *
     * Include the following files that make up the plugin:
     *
     * - Wp_Oauth2_Client_Loader. Orchestrates the hooks of the plugin.
     * - Wp_Oauth2_Client_i18n. Defines internationalization functionality.
     * - Wp_Oauth2_Client_Admin. Defines all hooks for the admin area.
     * - Wp_Oauth2_Client_Public. Defines all hooks for the public side of the site.
     *
     * Create an instance of the loader which will be used to register the hooks
     * with WordPress.
     *
     * @since    1.0.0
     * @access   private
     */
    private function load_dependencies(): void
    {

        /**
         * The class responsible for orchestrating the actions and filters of the
         * core plugin.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-wp-oauth2-client-loader.php';

        /**
         * The class responsible for defining internationalization functionality
         * of the plugin.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-wp-oauth2-client-i18n.php';

        /**
         * The Settings Trait
         * core plugin.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/OauthSettings.php';

        /**
         * Composer-Autoload
         * Composer Vendor for Theme|Plugin.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'vendor/autoload.php';

        /**
         * The Plugin Helper
         * core plugin.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/wp_oauth_helper.php';

        /**
         * The Plugin API Product Handle
         * core plugin.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/api/api_product_handle.php';

        /**
         * The Cronjob Class
         * core plugin.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'includes/Cronjob/class_oauth2_sync_cronjob.php';

        /**
         * The class responsible for defining all actions that occur in the admin area.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/class-wp-oauth2-client-admin.php';

        /**
         * The Oauth_Client_Callback Class
         * core api callback
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'admin/api/oauth_client_callback.php';

        /**
         * The class responsible for defining all actions that occur in the public-facing
         * side of the site.
         */
        require_once plugin_dir_path(dirname(__FILE__)) . 'public/class-wp-oauth2-client-public.php';

        $this->loader = new Wp_Oauth2_Client_Loader();

    }

    /**
     * Check PHP and WordPress Version
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function check_dependencies(): void
    {
        global $wp_version;
        if (version_compare(PHP_VERSION, WP_OAUTH2_CLIENT_MIN_PHP_VERSION, '<') || $wp_version < WP_OAUTH2_CLIENT_MIN_WP_VERSION) {
            $this->maybe_self_deactivate();
        }
    }

    /**
     * Self-Deactivate
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function maybe_self_deactivate(): void
    {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
        deactivate_plugins($this->plugin_slug);
        add_action('admin_notices', array($this, 'self_deactivate_notice'));
    }

    /**
     * Self-Deactivate Admin Notiz
     * of the plugin.
     *
     * @since    1.0.0
     * @access   public
     */
    public function self_deactivate_notice(): void
    {
        echo sprintf('<div class="notice notice-error is-dismissible" style="margin-top:5rem"><p>' . __('This plugin has been disabled because it requires a PHP version greater than %s and a WordPress version greater than %s. Your PHP version can be updated by your hosting provider.', 'wp-oauth2-client') . '</p></div>', WP_OAUTH2_CLIENT_MIN_PHP_VERSION, WP_OAUTH2_CLIENT_MIN_WP_VERSION);
        exit();
    }

    /**
     * Define the locale for this plugin for internationalization.
     *
     * Uses the Wp_Oauth2_Client_i18n class in order to set the domain and to register the hook
     * with WordPress.
     *
     * @since    1.0.0
     * @access   private
     */
    private function set_locale(): void
    {

        $plugin_i18n = new Wp_Oauth2_Client_i18n();

        $this->loader->add_action('plugins_loaded', $plugin_i18n, 'load_plugin_textdomain');

    }

    /**
     * Register all of the hooks related to the admin area functionality
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function define_admin_hooks(): void
    {

        $plugin_admin = new Wp_Oauth2_Client_Admin($this->get_plugin_name(), $this->get_version(), $this->main, $this->twig);
        $this->loader->add_action('admin_menu', $plugin_admin, 'register_wp_oauth2_client_admin_menu');
        $this->loader->add_action('wp_ajax_nopriv_Oauth2Client', $plugin_admin, 'admin_ajax_Oauth2Client');
        $this->loader->add_action('wp_ajax_Oauth2Client', $plugin_admin, 'admin_ajax_Oauth2Client');

        $this->loader->add_action( 'init', $plugin_admin, 'set_wp_oauth2_client_update_checker' );


		global $apiCallback;
        $apiCallback = Oauth_Client_Callback::instance($this->plugin_name, $this->main);

	    $this->loader->add_action('init', $plugin_admin, 'fn_product_lizenz_query');
	    $this->loader->add_action('template_redirect', $plugin_admin, 'fn_product_lizenz_callback_trigger');

    }

    /**
     * Register all of the hooks related to the api-remote functionality
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function oauth2_client_remote(): void
    {
        global $apiRemoteCallback;
        $apiRemoteCallback = Oauth_Client_Callback::instance($this->plugin_name, $this->main);
        //$this->loader->add_action( $this->plugin_name.'/set_access_token', $apiRemoteCallback, 'oauth_login_set_access_token' );
        $this->loader->add_filter( $this->plugin_name.'/get_access_token', $apiRemoteCallback, 'oauth_login_get_access_token' );
        $this->loader->add_action($this->plugin_name . '/remove_access_token', $apiRemoteCallback, 'oauth_login_remove_access_token');

        //API Call
        $this->loader->add_filter($this->plugin_name . '/oauth2_get_client_data', $apiRemoteCallback, 'oauth2_get_client_data', 10, 2);
        //API GET Call
        $this->loader->add_filter($this->plugin_name . '/api_get_callback', $apiRemoteCallback, 'fn_api_get_callback', 10, 2);
        $this->loader->add_filter($this->plugin_name . '/get_upload_token', $apiRemoteCallback, 'fn_get_upload_token', 10, 2);

        //API POST Call
        $this->loader->add_filter($this->plugin_name . '/api_post_callback', $apiRemoteCallback, 'fn_api_post_callback', 10, 4);
        //Download
        $this->loader->add_action($this->plugin_name . '/product_download', $apiRemoteCallback, 'fn_product_download');


        //Cronjob
        $this->loader->add_action('wp_oauth_client_sync', $apiRemoteCallback, 'fn_wp_oauth_client_sync');
    }

    /**
     * Register all of the hooks related to the api-helper functionality
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function oauth2_client_helper(): void
    {
        global $Oauth2Helper;
        $Oauth2Helper = WP_Oauth_Helper::instance($this->version, $this->plugin_name, $this->main);
        $this->loader->add_action('init', $Oauth2Helper, 'set_default_oauth2_client_data');
        $this->loader->add_filter($this->plugin_name . '/preg_whitespace', $Oauth2Helper, 'fnPregWhitespace');
        $this->loader->add_filter($this->plugin_name . '/current_theme_directory', $Oauth2Helper, 'fn_oauth2_client_current_theme_directory');
        $this->loader->add_filter($this->plugin_name . '/set_client_scopes', $Oauth2Helper, 'set_client_scopes');

    }

    /**
     * Register all of the hooks related to the api-products functionality
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */

    private function register_product_api_handle(): void
    {
        global $apiProductHandle;
        $apiProductHandle = Api_Product_Handle::instance($this->plugin_name, $this->main);
        $this->loader->add_filter($this->plugin_name . '/is_product_install', $apiProductHandle, 'fn_is_product_install');
        $this->loader->add_filter($this->plugin_name . '/is_theme_install', $apiProductHandle, 'fn_is_theme_install');
        $this->loader->add_filter($this->plugin_name . '/is_php_zip_extension', $apiProductHandle, 'fn_is_php_zip_extension');
        $this->loader->add_filter($this->plugin_name . '/get_license_product_data', $apiProductHandle, 'fn_get_license_product_data');

    }

    /**
     * Register all the hooks related to the admin area functionality
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function register_cron_oauth2_client(): void
    {

        if ($this->check_wp_cron()) {
            $oauthClientCron = new OAuth2_Sync_Cronjob($this->plugin_name, $this->main);
            $this->loader->add_filter($this->plugin_name . '/fn_oath2_client_run_schedule_task', $oauthClientCron, 'fn_oath2_client_run_schedule_task');
            $this->loader->add_filter($this->plugin_name . '/fn_oath2_client_wp_un_schedule_task', $oauthClientCron, 'fn_oath2_client_wp_un_schedule_task');
            $this->loader->add_filter($this->plugin_name . '/fn_oath2_client_wp_delete_task', $oauthClientCron, 'fn_oath2_client_wp_delete_task');
        }
    }

    /**
     * Register all of the hooks related to the public-facing functionality
     * of the plugin.
     *
     * @since    1.0.0
     * @access   private
     */
    private function define_public_hooks(): void
    {

        $plugin_public = new Wp_Oauth2_Client_Public($this->get_plugin_name(), $this->get_version());

        $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_styles');
        $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_scripts');

    }

    /**
     * Run the loader to execute all of the hooks with WordPress.
     *
     * @since    1.0.0
     */
    public function run(): void
    {
        $this->loader->run();
    }

    /**
     * The name of the plugin used to uniquely identify it within the context of
     * WordPress and to define internationalization functionality.
     *
     * @return    string    The name of the plugin.
     * @since     1.0.0
     */
    public function get_plugin_name(): string
    {
        return $this->plugin_name;
    }

    /**
     * The reference to the class that orchestrates the hooks with the plugin.
     *
     * @return    Wp_Oauth2_Client_Loader    Orchestrates the hooks of the plugin.
     * @since     1.0.0
     */
    public function get_loader(): Wp_Oauth2_Client_Loader
    {
        return $this->loader;
    }

    /**
     * Retrieve the version number of the plugin.
     *
     * @return    string    The version number of the plugin.
     * @since     1.0.0
     */
    public function get_version(): string
    {
        return $this->version;
    }

    /**
     * @return int
     */
    public function get_oauth_save_pin(): int
    {
        return $this->get_oauth_save_pin;
    }

    /**
     * @return bool
     */
    public function check_wp_cron(): bool
    {
        return $this->wp_disabled_cron;
    }

    public function url_check($url) {
        $hdrs = @get_headers($url);
        return is_array($hdrs) ? preg_match('/^HTTP\\/\\d+\\.\\d+\\s+2\\d\\d\\s+.*$/',$hdrs[0]) : false;
    }

}
