<?php

namespace CouponsPlus\App\Handlers;

use CouponsPlus\Original\Environment\Env;
use CouponsPlus\Original\Events\Handler\EventHandler;

#[\AllowDynamicProperties]
Class BlockCartAutoAppliedCouponsClientDataRegistratorHandler extends EventHandler
{
    protected $priority = 10;

    public function execute()
    {
        // Get list of auto-applied coupon codes
        $auto_applied_coupons = $this->getAutoAppliedCoupons();
        
        // Pass to JavaScript
        wp_localize_script(
            Env::getWithPrefix('block-cart-hide-remove-button'),
            'couponsPlus',
            array(
                'autoAppliedCoupons' => $auto_applied_coupons,
            )
        );
    }

    /**
     * Get list of auto-applied coupon codes
     *
     * @return array List of coupon codes that are auto-applied
     */
    protected function getAutoAppliedCoupons()
    {
        $auto_applied = array();
        
        // Get applied coupons from WooCommerce cart
        if (WC()->cart) {
            $applied_coupons = WC()->cart->get_applied_coupons();
            
            foreach ($applied_coupons as $coupon_code) {
                $coupon_id = wc_get_coupon_id_by_code($coupon_code);
                
                if ($coupon_id && $this->isAutoAppliedCoupon($coupon_id)) {
                    $auto_applied[] = $coupon_code;
                }
            }
        }
        
        return $auto_applied;
    }

    /**
     * Check if a coupon is auto-applied based on your plugin's logic
     *
     * @param int $coupon_id Coupon post ID
     * @return bool True if auto-applied
     */
    protected function isAutoAppliedCoupon($coupon_id): bool
    {
        return get_post_meta($coupon_id, Env::getWithPrefix('coupon_auto_apply_is_enabled'), true) === 'yes';
    }
}
