<?php
namespace AIFI;

/**
 * Heads-up notice shown when the official WordPress.org "AI" plugin is active
 * AND its image generation feature is turned on. In that case both plugins add
 * a "Generate" button to the editor, so we let the user know they may see two.
 *
 * The check reads the "AI" plugin's own option keys. It is written defensively:
 * if those options are missing or renamed in a future version of that plugin,
 * the worst case is that this notice simply never appears — it can never error
 * out or show a false alarm.
 *
 * @package AIFI
 */
class Compatibility_Notice {

    /**
     * Constant the "AI" plugin defines on load. Used to confirm the plugin is
     * genuinely active (not just leftover options from a removed install).
     */
    const AI_PLUGIN_MARKER = 'WPAI_VERSION';

    /**
     * "AI" plugin global master toggle option.
     */
    const AI_GLOBAL_OPTION = 'wpai_features_enabled';

    /**
     * "AI" plugin per-feature toggle for image generation (feature id:
     * "image-generation").
     */
    const AI_IMAGE_FEATURE_OPTION = 'wpai_feature_image-generation_enabled';

    /**
     * Per-user meta flag recording that the notice has been dismissed.
     */
    const DISMISS_META = 'aifi_ai_compat_notice_dismissed';

    /**
     * Query var used by the dismiss link.
     */
    const DISMISS_ACTION = 'aifi_dismiss_ai_compat';

    /**
     * Settings instance, used to detect AIFIG-relevant editor screens.
     *
     * @var Settings
     */
    private $settings;

    /**
     * @param Settings $settings
     */
    public function __construct($settings) {
        $this->settings = $settings;

        add_action('admin_init', array($this, 'maybe_handle_dismiss'));
        add_action('admin_notices', array($this, 'render_notice'));
    }

    /**
     * True when the "AI" plugin is active and its image generation feature is
     * enabled. Mirrors that plugin's own is_enabled() logic: the global toggle
     * must be on first, then the per-feature toggle.
     *
     * @return bool
     */
    private function ai_image_generation_active() {
        if (!defined(self::AI_PLUGIN_MARKER)) {
            return false;
        }
        if (!get_option(self::AI_GLOBAL_OPTION, false)) {
            return false;
        }
        if (!get_option(self::AI_IMAGE_FEATURE_OPTION, false)) {
            return false;
        }
        return true;
    }

    /**
     * Decide whether the notice should appear on the current screen.
     *
     * @return bool
     */
    private function should_display() {
        if (!current_user_can('manage_options')) {
            return false;
        }
        if (get_user_meta(get_current_user_id(), self::DISMISS_META, true)) {
            return false;
        }
        if (!$this->ai_image_generation_active()) {
            return false;
        }
        return $this->is_aifi_screen();
    }

    /**
     * True if we're on an AIFIG-relevant admin screen — the settings page or a
     * post-edit screen for an enabled post type (where the duplicate button
     * actually appears).
     *
     * @return bool
     */
    private function is_aifi_screen() {
        if (!function_exists('get_current_screen')) {
            return false;
        }
        $screen = get_current_screen();
        if (!$screen) {
            return false;
        }

        if ($screen->id === 'toplevel_page_ai-featured-image-generator') {
            return true;
        }

        if (in_array($screen->base, array('post'), true)) {
            $enabled = $this->settings->get_enabled_post_types();
            if (!empty($screen->post_type) && in_array($screen->post_type, $enabled, true)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Render the compatibility notice.
     */
    public function render_notice() {
        if (!$this->should_display()) {
            return;
        }

        $dismiss_url = wp_nonce_url(
            add_query_arg(self::DISMISS_ACTION, '1'),
            self::DISMISS_ACTION
        );
        ?>
        <div class="notice notice-info">
            <p>
                <strong><?php esc_html_e('AI Featured Image Generator:', 'ai-featured-image-generator'); ?></strong>
                <?php esc_html_e('The official "AI" plugin is active and has image generation turned on, so you may see two different "Generate" buttons in the editor. They work differently.', 'ai-featured-image-generator'); ?>
                <a href="<?php echo esc_url($dismiss_url); ?>"><?php esc_html_e('Dismiss', 'ai-featured-image-generator'); ?></a>
            </p>
        </div>
        <?php
    }

    /**
     * Handle the dismiss link click: persist the dismissal for this user and
     * redirect back to a clean URL.
     */
    public function maybe_handle_dismiss() {
        if (!isset($_GET[self::DISMISS_ACTION])) {
            return;
        }
        if (!current_user_can('manage_options')) {
            return;
        }
        check_admin_referer(self::DISMISS_ACTION);

        update_user_meta(get_current_user_id(), self::DISMISS_META, 1);

        wp_safe_redirect(remove_query_arg(array(self::DISMISS_ACTION, '_wpnonce')));
        exit;
    }
}
