<?php
/**
 * Plugin Name:         ArchiveMaster
 * Description:         A WordPress plugin for Auto Archive Old Order for WooCommerce
 * Requires at least:   6.2
 * Require PHP:         8.0
 * Plugin URI:          https://archivemaster.pro/
 * Author:              ArchiveMaster
 * Author URI:          https://archivemaster.pro/
 * Version:             1.12.3
 * License:             GPL2 or later
 * License URI:         https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:         archive-master
 */

if ( ! defined('ABSPATH') ) {
    // phpcs:ignore Universal.PHP.RequireExitDieParentheses.Missing
    exit;
}
require_once __DIR__ . '/vendor/autoload.php';

use ARCHM\Admin;
// AnalyticsIntegration moved to Pro plugin
use ARCHM\Admin\BulkArchiveHandler;
use ARCHM\Admin\Security;
use ARCHM\DBLoader;
// Analytics classes moved to Pro plugin
use ARCHM\Features\ARCM_Export_Background_Process;
use ARCHM\Features\ARCM_Unarchive_Background_Process;
use ARCHM\Installer;
use ARCHM\Migrator\WpDbMigration;

class ArchmPluginLoader {


    /**
     * Plugin version
     *
     * @var string
     * @author Siam Maruf
     * @since 1.0
     */
    const VERSION = '1.12.3';

    /**
     * Instance of Security class
     *
     * @var ARCHM\Admin\Security
     */
    private $security;

    /**
     * Class constructor of ArchmPluginLoader.
     *
     * @author Siam Maruf
     * @since 1.0
     */
    private function __construct() {
        $this->define_constants();
        $this->init_appsero();
        $this->archm_wppool_sdk_init();
        register_activation_hook(__FILE__, [ $this, 'activate' ]);
        add_action('plugins_loaded', [ $this, 'init_plugin' ]);
        add_filter('plugin_action_links', [ $this, 'archm_add_settings_link' ], 11, 2);
        add_filter( 'wppool_plugins', [ $this, 'change_campaign_button_link' ], 10, 1 );

        // Initialize security headers early
        $this->init_security();
    }

    /**
     * Initializes a singleton instance
     *
     * @retun  ArchmPluginLoader
     * @author Siam Maruf
     * @since 1.0
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.boolFound
    public static function init() {
        static $instance = false;
        if ( ! $instance ) {
            $instance = new ArchmPluginLoader();
        }
        return $instance;
    }

    /**
     * Initialize security components
     *
     * @return void
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.voidFound
    private function init_security(): void {
        $this->security = new Security();
    }

    /**
     * Define the required plugin constance
     *
     * @retun void
     * @author Siam Maruf
     * @since 1.0
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.voidFound
    public function define_constants(): void {
        define('ARCHM_PLUGIN_VERSION', self::VERSION);
        define('ARCHM_PLUGIN_FILE', __FILE__);
        define('ARCHM_PLUGIN_PATH', __DIR__);
        define('ARCHM_PLUGIN_URL', plugins_url('', ARCHM_PLUGIN_FILE));
        define('ARCHM_PLUGIN_BUILD', ARCHM_PLUGIN_URL . '/build');
        define('ARCHM_PLUGIN_ASSETS', ARCHM_PLUGIN_URL . '/assets');
        define('ARCHM_POST_TYPE', 'shop_order_placehold');
        define('ARCHM_CHUNK_SIZE', 20);
    }

    /**
     * Add settings link beside the plugin activation or deactivation button
     *
     * @param array  $actions    An array of plugin action links.
     * @param string $plugin_file Path to the main plugin file.
     * @return array
     */
    public function archm_add_settings_link( $actions, $plugin_file ) {
        // Check if the current plugin is the one you want.
        if ( 'archive-master/archive-master.php' === $plugin_file ) {
            $settings_link = '<a href="' . admin_url('admin.php?page=master-archives#/') . '">' . esc_html__('Settings', 'archive-master') . '</a>';

            // Check if the "Settings" link is not already present in actions.
            if ( ! in_array($settings_link, $actions, true) ) {
                array_push($actions, $settings_link); // Add your settings link.
            }
        }

        return $actions;
    }

    /**
         * Changes the 'button_link' for the 'archive_master'
         * plugin data during a specified campaign period.
         * * This method is intended to be hooked into the 'wppool_plugins' filter.
         * The link is reverted to its original value after the campaign end date (December 4th).
         *
         * @param array $plugins An array containing data for all registered WP Pool plugins.
         * @return array The potentially modified array of plugin data.
         */
	public function change_campaign_button_link( $plugins ) {
		$start_date = strtotime( '2025-11-17' );
		$end_date   = strtotime( '2025-12-04' );
		$current_time = current_time( 'timestamp' );
		if ( $current_time >= $start_date && $current_time <= $end_date ) {
			$plugin_key = 'archive_master';
			$new_campaign_url = 'https://lnk.wppool.dev/5Z8hyMV';
			if ( isset( $plugins[ $plugin_key ] ) ) {
				$plugins[ $plugin_key ]['button_link'] = $new_campaign_url;

			}
		}
		return $plugins;
	}

    /**
     * Initiliaze Appsero
     *
     * @return void
     */
    public function init_appsero() {
        $plugin_list      = ( get_option('active_plugins') );
        $woocommerce_free = 'woocommerce/woocommerce.php';
        if ( ! in_array($woocommerce_free, $plugin_list, true) ) {
            return;
        }
        add_action('init', [ $this, 'archm_appsero_init_tracker' ]);
    }

    /**
     * Initialize the plugin
     *
     * @return void
     * @author Siam Maruf
     * @since 1.0
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.voidFound
    public function init_plugin(): void {
        //check php version
        if ( version_compare(PHP_VERSION, '8.0.0', '<') ) {
            add_action('admin_notices', [ $this, 'admin_notic_php_version' ]);
            return;
        }

        // Check WooCommerce
        if ( ! function_exists('is_plugin_active') ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        if ( ! is_plugin_active('woocommerce/woocommerce.php') ) {
            add_action('admin_notices', [ $this, 'admin_notic_missing_woocommerce' ]);
            return;
        }

        // Load encryption class early if Pro plugin exists (needed for background processes)
        // This ensures credentials can be decrypted even in non-admin contexts
        if ( file_exists(WP_PLUGIN_DIR . '/archive-master-pro/includes/custom-mysql/class-credential-encryption.php') ) {
            require_once WP_PLUGIN_DIR . '/archive-master-pro/includes/custom-mysql/class-credential-encryption.php';
        }

        if ( is_admin() ) {
            new Admin();
            new DBLoader();
            // AnalyticsIntegration is now loaded by Pro plugin if available
            new BulkArchiveHandler();
        }

        new WpDbMigration();
        new ARCM_Export_Background_Process();
        new ARCM_Unarchive_Background_Process();
        new \ARCHM\Admin\FlexOrderPromotion();

        // Analytics features are Pro-only - initialize only if Pro is available
        // Pro plugin will handle analytics initialization if available
        // We just ensure the integration class exists for JS enqueue

        new \ARCHM\Features\SubscriptionMembershipHandler();

        // Initialize My Account features
        new \ARCHM\Features\MyAccountArchivedOrders();
    }

    public function admin_notic_php_version() {
        echo '<div class="error"><p>The required php version for Archive Master is 8.0.0 but the PHP version of your site is lower then 8.0.0 please upgrade your php version</p></div>';
    }

    /**
     * Initialize the plugin tracker
     *
     * @return void
     */
    public function archm_appsero_init_tracker() {
        if ( ! class_exists('MasterArchive\Appsero\Client') ) {
            require_once __DIR__ . '/includes/Appsero/Client.php';
        }
        $client = new MasterArchive\Appsero\Client('a020b192-b6d3-45f1-b1c1-7ced28277011', 'ArchiveMaster', ARCHM_PLUGIN_FILE);
        // Active insights
        $client->insights()->init();
    }

    /**
     * Initiliaze appsero SDK
     *
     * @return void
     */
    public function archm_wppool_sdk_init() {
        // Require WPPOOL SDK files.
        if ( file_exists(ARCHM_PLUGIN_PATH . '/includes/wppool/class-plugin.php') ) {
            require_once ARCHM_PLUGIN_PATH . '/includes/wppool/class-plugin.php';
        }

        if ( function_exists('wppool_plugin_init') ) {
            $archm_plugin = wppool_plugin_init('archive_master', ARCHM_PLUGIN_URL . '/includes/wppool/archive-master.png');

            // Campain.
            $campain_image = ARCHM_PLUGIN_URL . '/includes/wppool/black-friday.png';

            if ( $archm_plugin && is_object($archm_plugin) && method_exists($archm_plugin, 'set_campaign') ) {
                $to   = '2025-12-04';
                $from = '2025-11-17';
                $cta_text = 'Grab Your Deals';
                $archm_plugin->set_campaign($campain_image, $to, $from, $cta_text);
            }
        }
    }

    /**
     * [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$sArchiveMaster%2$s requires %1$s"WooCommerce"%2$s plugin to be active. Please activate WooCommerce to continue.', 'archive-master'), '<strong>', '</strong>');
            $button_text = esc_html__('Activate WooCommerce', 'archive-master');
        } 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$sArchiveMaster%2$s requires %1$s"WooCommerce"%2$s plugin to be installed and activated. Please install WooCommerce to continue.', 'archive-master'), '<strong>', '</strong>');
            $button_text = esc_html__('Install WooCommerce', 'archive-master');
        }

        $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 ]);
    }

    /**
     * On plugin activation
     *
     * @retun void
     * @author Siam Maruf
     * @since 1.0
     */
    // phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.voidFound
    public function activate(): void {
        ( new Installer() )->run();
    }

    /**
     * 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'    => [],
            ],
        ];
    }
}

/**
 * Initialize the main plugin
 *
 * @retun WooArchivePluginLoader
 * @author Siam Maruf
 * @since 1.0
 */
// phpcs:ignore PHPCompatibility.FunctionDeclarations.NewReturnTypeDeclarations.boolFound
function archm_plugin_loader() {
    return ArchmPluginLoader::init();
}

//Kick Off the plugin
archm_plugin_loader();
