<?php

namespace CouponsPlus\App\Handlers;

use CouponsPlus\App\Coupon\Coupon;
use CouponsPlus\App\Coupon\CouponOffersTracker;
use CouponsPlus\Original\Environment\Env;
use CouponsPlus\Original\Events\Handler\EventHandler;

#[\AllowDynamicProperties]
Class AutoApplyPostCustomColumnHandler extends EventHandler
{
    protected $numberOfArguments = 1;
    protected $priority = 10;

    public function execute()
    {
        add_action('manage_shop_coupon_posts_columns', [$this, 'registerColumn'], 10000);
        add_action('manage_shop_coupon_posts_custom_column', [$this, 'renderColumn'], 10, 2);
    }

    public function registerColumn(array $columns) : array
    {
        $columns[$this->getCoumnId()] = __('Apply Type', 'coupons-plus-for-woocommerce');

        return $columns;
    }

    public function renderColumn(string $columnName, int $couponId)
    {
        if ($columnName !== $this->getCoumnId()) {
            return;
        }

        (object) $coupon = new Coupon(
            new \WC_Coupon($couponId), 
            CouponOffersTracker::getInstance()
        );

        if ($coupon->canBeAutoApplied()) {
            (string) $auto = __('Auto', 'coupons-plus-for-woocommerce');
            print wp_kses_post("<span class=\"cp-auto-apply-enabled\">{$auto}</span>");
        } else {
            print esc_html(__('Manual', 'coupons-plus-for-woocommerce'));
        }
    }

    protected function getCoumnId() : string
    {
        return Env::getWithPrefix('auto_apply');
    }
}