<?php

if (!defined('ABSPATH')) {
    exit;
}

class AIEO_Wishlist_PPE_Compat {

    
    private static $instance = null;

    public static function instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        
        
        
        
        add_action('wp_ajax_om_ppe_wishlist_toggle',        array($this, 'proxy_toggle'), 1);
        add_action('wp_ajax_nopriv_om_ppe_wishlist_toggle', array($this, 'proxy_toggle'), 1);

        
        
        
        
        
        add_action('wp_enqueue_scripts', array($this, 'enqueue_shim_globals'), 20);
    }

    
    public function proxy_toggle() {
        
        
        
        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if ($nonce !== '' && wp_verify_nonce($nonce, 'om-ppe-wishlist') === false
            && wp_verify_nonce($nonce, 'aieo_wishlist') === false) {
            wp_send_json_error(array('message' => 'Invalid nonce.'));
        }

        
        
        $_POST['nonce'] = wp_create_nonce('aieo_wishlist');
        if (class_exists('AIEO_Wishlist')) {
            AIEO_Wishlist::instance()->ajax_toggle();
            
        }
        wp_send_json_error(array('message' => 'Wishlist unavailable.'));
    }

    
    public function enqueue_shim_globals() {
        if (is_admin()) { return; }
        $payload = array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            
            'nonce'   => wp_create_nonce('om-ppe-wishlist'),
            'cookie'  => class_exists('AIEO_Wishlist') ? AIEO_Wishlist::COOKIE_NAME : 'woocommerce_items_in_cart_merchant_wishlist',
            
            '_aieoShim' => true,
        );
        wp_register_script('aieo-wishlist-ppe-compat', '', array(), AIEO_VERSION, false);
        wp_enqueue_script('aieo-wishlist-ppe-compat');
        wp_add_inline_script(
            'aieo-wishlist-ppe-compat',
            
            
            
            'if (typeof window.omPPEWishlist === "undefined") { window.omPPEWishlist = ' . wp_json_encode($payload) . '; }',
            'before'
        );
    }
}
