<?php
namespace ARCHM\Features;

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

/**
 * Subscription and Membership Plugin Handler
 *
 * Handles automatic enabling of exclusion options when subscription and membership plugins are activated
 */
class SubscriptionMembershipHandler {


    /**
     * Constructor
     */
    public function __construct() {
        add_action('activated_plugin', [ $this, 'handle_plugin_activation' ], 10, 2);
        add_action('deactivated_plugin', [ $this, 'handle_plugin_deactivation' ], 10, 2);
    }

    /**
     * Handle plugin activation
     *
     * @param string $plugin Plugin file path
     * @param bool $network_wide Whether the plugin was activated network-wide
     */
    public function handle_plugin_activation( $plugin, $network_wide ) {
        // Check if activated plugin is a subscription plugin
        if ( $this->is_subscription_plugin($plugin) ) {
            $this->enable_subscription_exclusion();
        }

        // Check if activated plugin is a membership plugin
        if ( $this->is_membership_plugin($plugin) ) {
            $this->enable_membership_exclusion();
        }
    }

    /**
     * Handle plugin deactivation
     *
     * @param string $plugin Plugin file path
     * @param bool $network_wide Whether the plugin was deactivated network-wide
     */
    public function handle_plugin_deactivation( $plugin, $network_wide ) {
        // Check if deactivated plugin is a subscription plugin
        if ( $this->is_subscription_plugin($plugin) ) {
            $this->check_and_disable_subscription_exclusion();
        }

        // Check if deactivated plugin is a membership plugin
        if ( $this->is_membership_plugin($plugin) ) {
            $this->check_and_disable_membership_exclusion();
        }
    }

    /**
     * Check if plugin is a subscription plugin
     *
     * @param string $plugin Plugin file path
     * @return bool
     */
    private function is_subscription_plugin( $plugin ) {
        $subscription_plugins = [
            'woocommerce-subscriptions/woocommerce-subscriptions.php',
            'subscriptions-for-woocommerce/subscriptions-for-woocommerce.php',
            'yith-woocommerce-subscription/init.php',
        ];

        return in_array($plugin, $subscription_plugins);
    }

    /**
     * Check if plugin is a membership plugin
     *
     * @param string $plugin Plugin file path
     * @return bool
     */
    private function is_membership_plugin( $plugin ) {
        $membership_plugins = [
            'woocommerce-memberships/woocommerce-memberships.php',
            'membership-for-woocommerce/membership-for-woocommerce.php',
        ];

        return in_array($plugin, $membership_plugins);
    }

    /**
     * Enable subscription exclusion
     */
    private function enable_subscription_exclusion() {
        $current_setting = get_option('archm_exclude_subscriptions', false);

        if ( ! $current_setting ) {
            update_option('archm_exclude_subscriptions', true);

            // Log the change - commented out empty IF block to fix PHPCS error
            /*
            if ( class_exists('\ARCHM\Helpers\Logger') ) {
                // \ARCHM\Helpers\Logger::logMessage('Subscription exclusion automatically enabled due to subscription plugin activation');
                // Logger class available but logging disabled
            }
            */

            // Show admin notice
            $this->show_admin_notice('subscription');
        }
    }

    /**
     * Enable membership exclusion
     */
    private function enable_membership_exclusion() {
        $current_setting = get_option('archm_exclude_memberships', false);

        if ( ! $current_setting ) {
            update_option('archm_exclude_memberships', true);

            // Log the change - commented out empty IF block to fix PHPCS error
            /*
            if ( class_exists('\ARCHM\Helpers\Logger') ) {
                // \ARCHM\Helpers\Logger::logMessage('Membership exclusion automatically enabled due to membership plugin activation');
                // Logger class available but logging disabled
            }
            */

            // Show admin notice
            $this->show_admin_notice('membership');
        }
    }

    /**
     * Check and disable subscription exclusion if no subscription plugins are active
     */
    private function check_and_disable_subscription_exclusion() {
        $current_setting = get_option('archm_exclude_subscriptions', false);

        if ( $current_setting ) {
            update_option('archm_exclude_subscriptions', false);

            // Log the change - commented out empty IF block to fix PHPCS error
            /*
            if ( class_exists('\ARCHM\Helpers\Logger') ) {
                // \ARCHM\Helpers\Logger::logMessage('Subscription exclusion automatically disabled - no subscription plugins active');
                // Logger class available but logging disabled
            }
            */

            // Show admin notice
            $this->show_admin_notice('subscription_disabled');
        }
    }

    /**
     * Check and disable membership exclusion if no membership plugins are active
     */
    private function check_and_disable_membership_exclusion() {
        $current_setting = get_option('archm_exclude_memberships', false);

        if ( $current_setting ) {
            update_option('archm_exclude_memberships', false);

            // Log the change - commented out empty IF block to fix PHPCS error
            /*
            if ( class_exists('\ARCHM\Helpers\Logger') ) {
                // \ARCHM\Helpers\Logger::logMessage('Membership exclusion automatically disabled - no membership plugins active');
                // Logger class available but logging disabled
            }
            */

            // Show admin notice
            $this->show_admin_notice('membership_disabled');
        }
    }

    /**
     * Show admin notice when exclusion settings are automatically enabled/disabled
     *
     * @param string $type Type of exclusion ('subscription', 'membership', 'subscription_disabled', 'membership_disabled')
     */
    private function show_admin_notice( $type ) {
        $notice_key = 'archm_' . $type . '_exclusion_notice';

        // Set a transient to show the notice
        set_transient($notice_key, true, DAY_IN_SECONDS);

        // Add action to display the notice
        add_action('admin_notices', [ $this, 'display_exclusion_notice' ]);
    }

    /**
     * Display admin notice for exclusion settings
     *
     * @param string $type Type of exclusion ('subscription', 'membership', 'subscription_disabled', 'membership_disabled')
     */
    public function display_exclusion_notice() {
        $type = $this->get_current_notice_type();
        $notice_key = 'archm_' . $type . '_exclusion_notice';

        if ( get_transient($notice_key) ) {
            delete_transient($notice_key);

            $message = $this->get_exclusion_notice_message($type);

            if ( $message ) {
                echo wp_kses($message, [
                    'div'    => [
                        'class' => [],
                    ],
                    'p'      => [],
                    'strong' => [],
                ]);
            }
        }
    }

    /**
     * Get the current notice type from the transient
     *
     * @return string
     */
    private function get_current_notice_type() {
        $notice_types = [ 'subscription', 'membership', 'subscription_disabled', 'membership_disabled' ];

        foreach ( $notice_types as $type ) {
            $notice_key = 'archm_' . $type . '_exclusion_notice';
            if ( get_transient($notice_key) ) {
                return $type;
            }
        }

        return '';
    }

    /**
     * Get the notice message based on type
     *
     * @param string $type Type of exclusion
     * @return string
     */
    private function get_exclusion_notice_message( $type ) {
        switch ( $type ) {
            case 'subscription':
                return '<div class="notice notice-info is-dismissible"><p><strong>Archive Master:</strong> Subscription exclusion has been automatically enabled because a subscription plugin was detected. This prevents subscription orders from being archived to maintain functionality.</p></div>';
            case 'membership':
                return '<div class="notice notice-info is-dismissible"><p><strong>Archive Master:</strong> Membership exclusion has been automatically enabled because a membership plugin was detected. This prevents membership orders from being archived to maintain functionality.</p></div>';
            case 'subscription_disabled':
                return '<div class="notice notice-warning is-dismissible"><p><strong>Archive Master:</strong> Subscription exclusion has been automatically disabled because no subscription plugins are currently active.</p></div>';
            case 'membership_disabled':
                return '<div class="notice notice-warning is-dismissible"><p><strong>Archive Master:</strong> Membership exclusion has been automatically disabled because no membership plugins are currently active.</p></div>';
            default:
                return '';
        }
    }
}
