<?php

namespace CouponsPlus\App\Handlers;

use CouponsPlus\Original\Events\Handler\EventHandler;
use CouponsPlus\App\Data\NoticesData;

#[\AllowDynamicProperties]
Class RemoveStaleNoticesHandler extends EventHandler
{
    protected $priority = 25;

    public function execute()
    {
        // Register on multiple hooks to ensure stale notices are cleaned up
        add_action('woocommerce_init', array($this, 'cleanupStaleNotices'), 25);
        add_action('woocommerce_after_calculate_totals', array($this, 'cleanupStaleNotices'), 25);
        add_action('woocommerce_applied_coupon', array($this, 'cleanupStaleNotices'), 25);
        add_action('woocommerce_removed_coupon', array($this, 'cleanupStaleNotices'), 25);
    }

    /**
     * Clean up stale notices that no longer exist in NoticesData
     */
    public function cleanupStaleNotices()
    {
        // Get current valid notice IDs from NoticesData
        $current_notices = NoticesData::getNotices();
        $valid_ids = array();
        
        foreach ($current_notices as $notice) {
            if (isset($notice['id'])) {
                $valid_ids[] = $notice['id'];
            }
        }
        
        // Get all WooCommerce notices
        $all_notices = wc_get_notices();
        $notices_to_keep = array();
        $removed_any = false;
        
        // Filter out our notices that are no longer valid
        foreach ($all_notices as $type => $notices) {
            if (!isset($notices_to_keep[$type])) {
                $notices_to_keep[$type] = array();
            }
            
            foreach ($notices as $notice) {
                // If it's one of our notices, check if the ID is still valid
                if (isset($notice['data']['coupons_plus_id'])) {
                    $notice_id = $notice['data']['coupons_plus_id'];
                    
                    // Only keep if ID is in the valid list
                    if (in_array($notice_id, $valid_ids)) {
                        $notices_to_keep[$type][] = $notice;
                    } else {
                        $removed_any = true;
                    }
                } else {
                    // Not our notice, keep it
                    $notices_to_keep[$type][] = $notice;
                }
            }
        }
        
        // Only clear and re-add if we actually removed something
        if ($removed_any) {
            wc_clear_notices();
            
            foreach ($notices_to_keep as $type => $notices) {
                foreach ($notices as $notice) {
                    $data = isset($notice['data']) ? $notice['data'] : array();
                    wc_add_notice($notice['notice'], $type, $data);
                }
            }
        }
    }
}
