<?php
namespace WTC_CHECKOUT\Modules\Coupons\Services;
defined('ABSPATH') || exit;
class CouponManager {
    private static $instance = null;
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function get_user_special_coupons($user_id) {
        $user = get_userdata($user_id);
        if (!$user) return [];
        $user_email = strtolower($user->user_email);
        $valid_coupons = [];
        $args = array(
            'post_type'      => 'shop_coupon',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
        );
        $coupons = get_posts($args);
        foreach ($coupons as $post) {
            $coupon = new \WC_Coupon($post->ID);
            if ($coupon->get_date_expires() && $coupon->get_date_expires()->getTimestamp() < time()) {
                continue;
            }
            $allowed_emails = $coupon->get_email_restrictions();
            $show_public = get_option('wtc_show_public_coupons', 'yes') === 'yes';
            if (empty($allowed_emails)) {
                if ($show_public) {
                    $valid_coupons[] = $coupon;
                }
            } else {
                $is_match = false;
                foreach ($allowed_emails as $email_pattern) {
                    $pattern = strtolower($email_pattern);
                    if (str_contains($pattern, '*')) {
                        $regex = '/^' . str_replace('\*', '.*', preg_quote($pattern, '/')) . '$/i';
                        if (preg_match($regex, $user_email)) {
                            $is_match = true;
                            break;
                        }
                    } elseif ($pattern === $user_email) {
                        $is_match = true;
                        break;
                    }
                }
                if ($is_match) {
                    $valid_coupons[] = $coupon;
                }
            }
        }
        return $valid_coupons;
    }
    public function get_user_special_coupons_count($user_id) {
        $coupons = $this->get_user_special_coupons($user_id);
        return count($coupons);
    }
}