<?php
/**
 * Handles plugin activation and deactivation.
 *
 * @since 1.3.0
 * @package RVIOR
 */

// Namespace.
namespace RVIOR;

// Exit if accessed directly.
defined('ABSPATH') || exit(1);

if ( ! class_exists(__NAMESPACE__ . '\Install') ) {

    /**
     * Class Adjustment
     */
    class Install extends \RVIOR\Base\Controller {


        // Use helper traits.
        use \RVIOR\Traits\Utilities;

        /**
         * Register hooks
         *
         * @return void
         */
        public function register_hooks() {
            // Plugin activation.
            register_activation_hook(RVIOR_FILE, [ $this, 'activate' ]);

            // Plugin deactivation.
            register_deactivation_hook(RVIOR_FILE, [ $this, 'deactivate' ]);

            // redirect to admin page on activation this plugin.
            add_action('admin_init', [ $this, 'redirect_to_admin_page' ]);

            // plugin action links.
            add_action('plugin_action_links_' . plugin_basename(RVIOR_FILE), [ $this, 'plugin_action_links' ]);

            // author uri.
            add_filter('plugin_row_meta', [ $this, 'plugin_row_meta' ], 10, 2);
        }

        /**
         * Calls on plugin activation
         *
         * @return void
         */
        public function activate() {
            // Init options.
            $this->init_options();
        }

        /**
         * Calls on plugin deactivation
         *
         * @return void
         */
        public function deactivate() {
            // Removed redirect option.
            $this->option()->delete('redirected');
        }

        /**
         * Init options
         */
        public function init_options() {
            $default_options = $this->option()->get_defaults();

            foreach ( $default_options as $key => $value ) {
                add_option($this->option()->prefix . $key, $value);
            }
        }

        /**
         * Redirects user to admin page right after plugin activation
         *
         * @return void
         */
        public function redirect_to_admin_page() {
            if ( ! is_plugin_active('woocommerce/woocommerce.php') ) {
                add_action('admin_notices', [ $this, 'admin_notic_missing_woocommerce' ]);
                return;
            }

            $redirected_after_activation = $this->option()->get('redirected', false);

            if ( ! $redirected_after_activation ) {
                // Updates option.
                $this->option()->update('redirected', 1);

                // Redirects to admin page.
                wp_safe_redirect(admin_url('admin.php?page=revio'));
                exit;
            }
        }

        /**
         * [admin_notic_missing_woocommerce] Admin Notice For missing WooCommerce
         *
         * @return [void]
         */
        // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.voidFound
        public function admin_notic_missing_woocommerce(): void {
            $woocommerce = 'woocommerce/woocommerce.php';

            if ( $this->is_wc_plugin_active($woocommerce) ) {
                if ( ! current_user_can('activate_plugins') ) {
                    return;
                }

                $activation_url = wp_nonce_url(
                    'plugins.php?action=activate&amp;plugin=' . $woocommerce . '&amp;plugin_status=all&amp;paged=1&amp;s',
                    'activate-plugin_' . $woocommerce
                );

                // Translators: %1$s and %2$s are HTML tags for strong emphasis.
                $message     = sprintf(esc_html__('%1$sRevio Review%2$s requires %1$s"WooCommerce"%2$s plugin to be active. Please activate WooCommerce to continue.', 'revio-reviews'), '<strong>', '</strong>');
                $button_text = esc_html__('Activate WooCommerce', 'revio-reviews');
            } else {
                if ( ! current_user_can('activate_plugins') ) {
                    return;
                }

                $activation_url = wp_nonce_url(
                    self_admin_url('update.php?action=install-plugin&plugin=woocommerce'),
                    'install-plugin_woocommerce'
                );

                // Translators: %1$s and %2$s are HTML tags for strong emphasis.
                $message     = sprintf(esc_html__('%1$sRevio Review%2$s requires %1$s"WooCommerce"%2$s plugin to be installed and activated. Please install WooCommerce to continue.', 'revio-reviews'), '<strong>', '</strong>');
                $button_text = esc_html__('Install WooCommerce', 'revio-reviews');
            }

            $button = sprintf(
                '<p><a href="%s" class="button-primary">%s</a></p>',
                esc_url($activation_url),
                esc_html($button_text)
            );

            $notice = sprintf('<div class="error"><p>%s</p>%s</div>', $message, $button);
            echo wp_kses($notice, $this->get_allowed_html());
        }

        /**
         * [is_wc_plugin_active] Check Plugin is Installed or not
         *
         * @param  [string]  $pl_file_path plugin file path
         * @return boolean  true|false
         */
        public function is_wc_plugin_active( $pl_file_path = null ) {
            $installed_plugins_list = get_plugins();
            return isset($installed_plugins_list[ $pl_file_path ]);
        }

        /**
         * Get allowed HTML tag function
         *
         * @return array
         */
        // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.arrayFound
        private function get_allowed_html(): array {
            return [
                'div'    => [
                    'class' => [],
                    'id'    => [],
                ],
                'p'      => [],
                'strong' => [],
                'a'      => [
                    'href'  => [],
                    'class' => [],
                    'id'    => [],
                ],
                'button' => [
                    'class' => [],
                    'id'    => [],
                ],
            ];
        }

        /**
         * Plugin action links
         *
         * @param array $links Plugin action links.
         * @return array
         */
        public function plugin_action_links( $links ) {

            if ( $this->client()->has_valid_token() ) {
                $reviews_link = wp_sprintf('<a href="%s">%s</a>', esc_url(add_query_arg('page', 'revio', get_admin_url() . 'admin.php')), esc_html__('Reviews', 'revio-reviews'));
                $setting_link = wp_sprintf('<a href="%s">%s</a>', esc_url(add_query_arg('page', 'rvior-review-settings', get_admin_url() . 'admin.php')), esc_html__('Settings', 'revio-reviews'));

                array_unshift($links, wp_kses_post($setting_link));
                array_unshift($links, wp_kses_post($reviews_link));
            }

            return $links;
        }

        /**
         * Plugin row meta links
         *
         * @param array  $links Plugin row meta links.
         * @param string $file Plugin file.
         * @return array
         */
        public function plugin_row_meta( $links, $file ) {
            if ( plugin_basename(RVIOR_FILE) === $file ) {
                $row_meta = [
                    'docs' => wp_sprintf('<a href="%s" target="_blank">%s</a>', esc_url('https://wppool.dev/docs-category/rvior-for-woocommerce-docs/'), esc_html__('Docs', 'revio-reviews')),
                ];

                return array_merge($links, $row_meta);
            }

            return $links;
        }
    }

    // Instantiate the class.
    Install::init();
}
