<?php

namespace Unlockafe_Addons\Classes;

class Coupons_Controller
{
    private $reporting_controller;

    public function __construct()
    {
        // Register AJAX actions for coupon operations
        add_action('wp_ajax_unlockafe_apply_coupon', [$this, 'apply_coupon']);
        add_action('wp_ajax_nopriv_unlockafe_apply_coupon', [$this, 'apply_coupon']);

        add_action('wp_ajax_unlockafe_remove_coupon', [$this, 'remove_coupon']);
        add_action('wp_ajax_nopriv_unlockafe_remove_coupon', [$this, 'remove_coupon']);

        // Register coupon validation hooks directly
        add_filter('woocommerce_coupon_is_valid', [$this, 'debug_coupon_validation'], 1, 3);
        add_filter('woocommerce_coupon_is_valid', [$this, 'force_validate_stackable_coupon'], 5, 2);
        add_filter('woocommerce_coupon_is_valid', [$this, 'validate_and_redeem_gift_card'], 10, 3);
        add_filter('woocommerce_coupon_is_valid', [$this, 'validate_time_period_usage_limit'], 15, 2);
        add_filter('woocommerce_coupon_is_valid', [$this, 'validate_user_role_usage_limit'], 20, 2);
        add_filter('woocommerce_coupon_is_valid', [$this, 'validate_strict_one_time_use'], 25, 3);
        add_filter('woocommerce_coupon_is_valid', [$this, 'validate_advanced_restrictions'], 30, 3);
        add_filter('woocommerce_coupon_is_valid', [$this, 'prevent_individual_use_conflict'], 35, 2);

        add_action('admin_menu', [$this, 'register_admin_menu'], 10);

        add_action('woocommerce_coupon_options_usage_limit', [$this, 'add_usage_restriction_fields']);
        
        // Initialize reporting dashboard controller to register AJAX actions
        $this->reporting_controller = new \Unlockafe_Addons\Classes\Reporting_Dashboard_Controller();

        add_filter('woocommerce_coupon_data_tabs', [$this, 'add_coupon_data_tabs']);
        add_action('woocommerce_coupon_data_panels', [$this, 'add_coupon_data_panels']);

        add_action('woocommerce_coupon_options_save', [$this, 'save_coupon_meta_data'], 10, 1);

        // Hook to add advanced restriction fields to our new tab
        add_action('unlockafe_advanced_restrictions_panel', [$this, 'add_advanced_restriction_fields']);

        // Hook to add BOGO fields to our new tab
        add_action('unlockafe_bogo_deals_panel', [$this, 'add_bogo_deal_fields']);

        // Coupon validation filters - ordered by priority for proper execution
        add_filter('woocommerce_coupon_is_valid', [$this, 'force_validate_stackable_coupon'], 5, 2);
        add_filter('woocommerce_coupon_is_valid', [$this, 'validate_and_redeem_gift_card'], 10, 3);
        add_filter('woocommerce_coupon_is_valid', [$this, 'validate_time_period_usage_limit'], 15, 2);
        add_filter('woocommerce_coupon_is_valid', [$this, 'validate_user_role_usage_limit'], 20, 2);
        add_filter('woocommerce_coupon_is_valid', [$this, 'validate_strict_one_time_use'], 25, 3);
        add_filter('woocommerce_coupon_is_valid', [$this, 'validate_advanced_restrictions'], 30, 3);
        add_filter('woocommerce_coupon_is_valid', [$this, 'prevent_individual_use_conflict'], 35, 2);
        
        // Discount amount filters
        add_filter('woocommerce_coupon_get_discount_amount', [$this, 'apply_max_discount_limit'], 10, 5);
        add_filter('woocommerce_coupon_get_discount_amount', [$this, 'apply_bogo_discount'], 10, 5);
        
        // BOGO deal application
        add_action('woocommerce_applied_coupon', [$this, 'apply_bogo_deal']);

        // Display hooks
        add_action('woocommerce_before_cart', [$this, 'display_available_coupons']);
        add_action('woocommerce_before_checkout_form', [$this, 'display_available_coupons']);
        add_action('woocommerce_before_cart', [$this, 'display_coupon_notices']);
        add_action('woocommerce_before_checkout_form', [$this, 'display_coupon_notices']);

        // Message customization
        add_filter('woocommerce_coupon_message', [$this, 'custom_coupon_message'], 10, 3);

        // Auto apply coupons
        add_action('woocommerce_before_cart', [$this, 'maybe_auto_apply_coupons'], 10);


        // Register Coupon Category Taxonomy
        add_action('init', [$this, 'register_coupon_category_taxonomy']);
        add_action('wp_loaded', [$this, 'handle_coupon_url']);

    }

    public function display_coupon_notices()
    {
        if (is_admin() || !function_exists('WC') || !WC()->cart) {
            return;
        }

        $args = [
            'posts_per_page' => -1,
            'post_type'      => 'shop_coupon',
            'post_status'    => 'publish',
            'meta_query'     => [
                [
                    'key'     => 'unlockafe_display_notice',
                    'value'   => '',
                    'compare' => '!='
                ]
            ]
        ];

        $coupon_posts = get_posts($args);

        if (empty($coupon_posts)) {
            return;
        }

        foreach ($coupon_posts as $post) {
            $coupon = new \WC_Coupon($post->ID);
            $notice = $coupon->get_meta('unlockafe_display_notice');

            if ($coupon && $coupon->is_valid() && !WC()->cart->has_coupon($coupon->get_code()) && !empty($notice)) {
                wc_add_notice(esc_html($notice), 'notice');
            }
        }
    }

    public function custom_coupon_message($msg, $msg_code, $coupon)
    {
        $custom_message = $coupon->get_meta('unlockafe_custom_success_message');
        if ($msg_code === \WC_Coupon::WC_COUPON_SUCCESS && !empty($custom_message)) {
            return esc_html($custom_message);
        }
        return $msg;
    }


    public function handle_coupon_url()
    {
        if (isset($_GET['apply_coupon'])) {
            $coupon_code = sanitize_text_field(wp_unslash($_GET['apply_coupon']));

            if (is_admin() || !function_exists('WC') || !WC()->cart) {
                return;
            }

            if (WC()->cart->has_coupon($coupon_code)) {
                $redirect_url = remove_query_arg('apply_coupon', wc_get_cart_url());
                wp_safe_redirect($redirect_url);
                exit;
            }

            if (wc_get_coupon_id_by_code($coupon_code)) {
                WC()->cart->apply_coupon($coupon_code);
                $redirect_url = remove_query_arg('apply_coupon', wc_get_cart_url());
                wp_safe_redirect($redirect_url);
                exit;
            }
        }
    }

    /**
     * Register Coupon Category Taxonomy
     */
    public function register_coupon_category_taxonomy()
    {
        $labels = array(
            'name'              => _x('Coupon Categories', 'taxonomy general name', 'unlock-addons-for-elementor'),
            'singular_name'     => _x('Coupon Category', 'taxonomy singular name', 'unlock-addons-for-elementor'),
            'search_items'      => __('Search Coupon Categories', 'unlock-addons-for-elementor'),
            'all_items'         => __('All Coupon Categories', 'unlock-addons-for-elementor'),
            'parent_item'       => __('Parent Coupon Category', 'unlock-addons-for-elementor'),
            'parent_item_colon' => __('Parent Coupon Category:', 'unlock-addons-for-elementor'),
            'edit_item'         => __('Edit Coupon Category', 'unlock-addons-for-elementor'),
            'update_item'       => __('Update Coupon Category', 'unlock-addons-for-elementor'),
            'add_new_item'      => __('Add New Coupon Category', 'unlock-addons-for-elementor'),
            'new_item_name'     => __('New Coupon Category Name', 'unlock-addons-for-elementor'),
            'menu_name'         => __('Coupon Categories', 'unlock-addons-for-elementor'),
        );

        $args = array(
            'hierarchical'      => true,
            'labels'            => $labels,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'rewrite'           => array('slug' => 'coupon-category'),
        );

        register_taxonomy('coupon_category', array('shop_coupon'), $args);
    }

    public function maybe_auto_apply_coupons()
    {
        if (!function_exists('WC') || !WC()->cart || WC()->cart->is_empty()) {
            return;
        }

        if (is_admin()) {
            return;
        }

        $args = [
            'posts_per_page' => -1,
            'post_type'      => 'shop_coupon',
            'post_status'    => 'publish',
            'meta_query'     => [
                [
                    'key'   => 'unlockafe_auto_apply_coupon',
                    'value' => 'yes',
                ]
            ]
        ];

        $coupon_posts = get_posts($args);

        if (empty($coupon_posts)) {
            return;
        }

        $best_coupon = null;
        $max_discount = 0;

        // Create a temporary cart object to calculate discounts without affecting the main cart
        $temp_cart = clone WC()->cart;

        foreach ($coupon_posts as $post) {
            $coupon = new \WC_Coupon($post->ID);

            if ($coupon && $coupon->is_valid() && !WC()->cart->has_coupon($coupon->get_code())) {
                // Use a clone of the cart to calculate the discount for each coupon
                $cart_for_calc = clone $temp_cart;
                $cart_for_calc->add_coupon($coupon->get_code());

                $discount = $cart_for_calc->get_coupon_discount_amount($coupon->get_code());
                $cart_for_calc->remove_coupon($coupon->get_code());

                if ($discount > $max_discount) {
                    $max_discount = $discount;
                    $best_coupon = $coupon;
                }
            }
        }

        if ($best_coupon) {
            WC()->cart->apply_coupon($best_coupon->get_code());
            wc_add_notice(sprintf(__('Coupon "%s" has been automatically applied.', 'unlock-addons-for-elementor'), $best_coupon->get_code()));
        }
    }

    public function force_validate_stackable_coupon($is_valid, $coupon)
    {
        error_log('UNLOCKAFE DEBUG: force_validate_stackable_coupon - Coupon: ' . $coupon->get_code() . ', Initial valid: ' . ($is_valid ? 'true' : 'false'));
        
        if ($coupon->get_meta('_unlockafe_is_stackable') === 'yes') {
            error_log('UNLOCKAFE DEBUG: Coupon is stackable, forcing valid');
            return true; // This coupon is stackable, so force it to be valid.
        }
        
        error_log('UNLOCKAFE DEBUG: force_validate_stackable_coupon result: ' . ($is_valid ? 'true' : 'false'));
        return $is_valid;
    }

    public function prevent_individual_use_conflict($is_valid, $coupon)
    {
        // If a previous filter has already determined validity, respect it.
        if ($is_valid !== true) {
            return $is_valid;
        }

        if (is_null(WC()->cart)) {
            return $is_valid;
        }
        
        $cart_coupons = WC()->cart->get_applied_coupons();

        // No coupons in cart yet, so no conflict is possible.
        if (empty($cart_coupons)) {
            return $is_valid;
        }

        // Check 1: If the coupon being applied is individual use (and not stackable).
        if ($coupon->get_individual_use() && $coupon->get_meta('_unlockafe_is_stackable') !== 'yes') {
            throw new \Exception(__('This coupon cannot be used with other coupons.', 'unlock-addons-for-elementor'), 108);
        }

        // Check 2: If any coupon already in the cart is individual use (and not stackable).
        foreach ($cart_coupons as $code) {
            $cart_coupon = new \WC_Coupon($code);
            if ($cart_coupon->get_individual_use() && $cart_coupon->get_meta('_unlockafe_is_stackable') !== 'yes') {
                throw new \Exception(
                    sprintf(
                        /* translators: %s: coupon code */
                        __('The coupon "%s" is for individual use and cannot be used with other coupons.', 'unlock-addons-for-elementor'),
                        $cart_coupon->get_code()
                    ),
                    108
                );
            }
        }

        // return $is_valid;
        return true;
    }


    public function validate_and_redeem_gift_card($is_valid, $coupon, $discount)
    {
        error_log('UNLOCKAFE DEBUG: validate_and_redeem_gift_card - Coupon: ' . $coupon->get_code() . ', Initial valid: ' . ($is_valid ? 'true' : 'false'));
        
        if (!$is_valid) {
            error_log('UNLOCKAFE DEBUG: Already invalid, returning false');
            return $is_valid;
        }
        
        if ($coupon->get_meta('_is_gift_card') !== 'yes') {
            error_log('UNLOCKAFE DEBUG: Not a gift card, returning: ' . ($is_valid ? 'true' : 'false'));
            return $is_valid;
        }

        error_log('UNLOCKAFE DEBUG: Is a gift card, validating...');

        if (!is_user_logged_in()) {
            error_log('UNLOCKAFE DEBUG: FAILED - User not logged in for gift card');
            throw new \Exception(__('You must be logged in to redeem a gift card.', 'unlock-addons-for-elementor'));
        }

        // Prevent applying if cart total is zero
        if (WC()->cart->get_cart_contents_total() <= 0) {
            error_log('UNLOCKAFE DEBUG: FAILED - Cart total is zero for gift card');
            throw new \Exception(__('Gift cards cannot be redeemed on an empty cart.', 'unlock-addons-for-elementor'));
        }

        error_log('UNLOCKAFE DEBUG: Gift card validation passed, returning: true');
        return true; // Gift card is valid, but don't process redemption during validation
    }

    public function display_available_coupons()
    {
        $available_coupons = $this->get_available_coupons();

        if (empty($available_coupons)) {
            return;
        }

        echo '<div class="unlockafe-available-coupons">';
        echo '<h3>' . esc_html__('Available Coupons', 'unlock-addons-for-elementor') . '</h3>';
        echo '<ul>';

        foreach ($available_coupons as $coupon) {
            echo '<li>';
            echo '<strong>' . esc_html($coupon->get_code()) . '</strong>: ' . esc_html($coupon->get_description());
            echo ' <a href="#" class="unlockafe-apply-coupon-link" data-coupon-code="' . esc_attr($coupon->get_code()) . '">' . esc_html__('Apply', 'unlock-addons-for-elementor') . '</a>';
            echo '</li>';
        }

        echo '</ul>';
        echo '</div>';
    }

    public function apply_coupon()
    {
        error_log('UNLOCKAFE DEBUG: apply_coupon method called');
        
        // Check if WooCommerce is available
        if (!function_exists('WC') || !WC()->cart) {
            error_log('UNLOCKAFE DEBUG: WooCommerce or cart not available');
            wp_send_json_error(['message' => __('WooCommerce cart not available.', 'unlock-addons-for-elementor')]);
            return;
        }
        
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'unlockafe_coupon_nonce')) {
            error_log('UNLOCKAFE DEBUG: Invalid nonce');
            wp_send_json_error(['message' => __('Invalid nonce.', 'unlock-addons-for-elementor')]);
            return;
        }

        if (!isset($_POST['coupon_code'])) {
            error_log('UNLOCKAFE DEBUG: No coupon code provided');
            wp_send_json_error(['message' => __('Coupon code not provided.', 'unlock-addons-for-elementor')]);
            return;
        }

        $coupon_code = sanitize_text_field(wp_unslash($_POST['coupon_code']));
        error_log('UNLOCKAFE DEBUG: Attempting to apply coupon: ' . $coupon_code);
        
        // Initialize WooCommerce cart session if needed
        if (WC()->cart->is_empty() && !WC()->session->get('cart')) {
            error_log('UNLOCKAFE DEBUG: Cart is empty, initializing session');
            WC()->cart->set_session();
        }
        
        $coupon = new \WC_Coupon($coupon_code);
        error_log('UNLOCKAFE DEBUG: Coupon object created - ID: ' . $coupon->get_id() . ', Code: ' . $coupon->get_code() . ', Status: ' . $coupon->get_status());

        if (!$coupon->get_code()) {
            error_log('UNLOCKAFE DEBUG: Coupon does not exist or has no code');
            wp_send_json_error(['message' => __('Coupon does not exist.', 'unlock-addons-for-elementor')]);
            return;
        }

        if (WC()->cart->has_coupon($coupon_code)) {
            error_log('UNLOCKAFE DEBUG: Coupon already applied to cart');
            wp_send_json_error(['message' => __('Coupon already applied.', 'unlock-addons-for-elementor')]);
            return;
        }

        error_log('UNLOCKAFE DEBUG: Calling WC()->cart->apply_coupon()');
        
        // Clear any existing notices
        wc_clear_notices();
        
        if (WC()->cart->apply_coupon($coupon_code)) {
            error_log('UNLOCKAFE DEBUG: Coupon applied successfully');
            wp_send_json_success(['message' => __('Coupon applied successfully.', 'unlock-addons-for-elementor')]);
        } else {
            // Get WooCommerce error notices
            $notices = wc_get_notices('error');
            error_log('UNLOCKAFE DEBUG: Failed to apply coupon');
            error_log('UNLOCKAFE DEBUG: Error notices: ' . print_r($notices, true));
            
            // Get the specific error message from WooCommerce
            $error_message = __('Failed to apply coupon.', 'unlock-addons-for-elementor');
            if (!empty($notices)) {
                $last_notice = end($notices);
                if (isset($last_notice['notice'])) {
                    $error_message = $last_notice['notice'];
                } elseif (is_string($last_notice)) {
                    $error_message = $last_notice;
                }
            }
            
            // Clear notices to prevent them from showing elsewhere
            wc_clear_notices();
            
            wp_send_json_error(['message' => $error_message]);
        }
    }

    public function remove_coupon()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'unlockafe_coupon_nonce')) {
            wp_send_json_error(['message' => __('Invalid nonce.', 'unlock-addons-for-elementor')]);
            return;
        }

        if (!isset($_POST['coupon_code'])) {
            wp_send_json_error(['message' => __('Coupon code not provided.', 'unlock-addons-for-elementor')]);
            return;
        }

        $coupon_code = sanitize_text_field(wp_unslash($_POST['coupon_code']));

        if (WC()->cart->remove_coupon($coupon_code)) {
            wp_send_json_success(['message' => __('Coupon removed successfully.', 'unlock-addons-for-elementor')]);
        } else {
            wp_send_json_error(['message' => __('Failed to remove coupon.', 'unlock-addons-for-elementor')]);
        }
    }

    public function get_available_coupons($categories = [])
    {
        $args = [
            'posts_per_page' => -1,
            'post_type'      => 'shop_coupon',
            'post_status'    => 'publish',
        ];

        if (!empty($categories)) {
            // For multiple categories, we need to use OR logic with individual LIKE queries
            if (count($categories) > 1) {
                $meta_query = ['relation' => 'OR'];
                foreach ($categories as $category) {
                    $meta_query[] = [
                        'key'     => 'coupon_categories',
                        'value'   => serialize($category),
                        'compare' => 'LIKE',
                    ];
                }
                $args['meta_query'] = $meta_query;
            } else {
                // Single category
                $args['meta_query'] = [
                    [
                        'key'     => 'coupon_categories',
                        'value'   => serialize($categories[0]),
                        'compare' => 'LIKE',
                    ],
                ];
            }
        }

        $coupon_posts = get_posts($args);
        $available_coupons = [];

        foreach ($coupon_posts as $post) {
            $coupon = new \WC_Coupon($post->ID);
            if ($coupon->is_valid()) {
                // If categories are specified, double-check the meta field
                if (!empty($categories)) {
                    $coupon_categories = get_post_meta($post->ID, 'coupon_categories', true);
                    if (is_array($coupon_categories)) {
                        $has_match = false;
                        foreach ($categories as $category) {
                            if (in_array($category, $coupon_categories)) {
                                $has_match = true;
                                break;
                            }
                        }
                        if (!$has_match) {
                            continue;
                        }
                    }
                }
                $available_coupons[] = $coupon;
            }
        }

        return $available_coupons;
    }

    public function register_admin_menu()
    {
        // Register Parent Menu
        add_menu_page(
            __('Advanced Coupons', 'unlock-addons-for-elementor'),
            __('Advanced Coupons', 'unlock-addons-for-elementor'),
            'manage_woocommerce',
            'unlockafe-advanced-coupons',
            [$this, 'render_settings_page'], // Default page
            'dashicons-tickets-alt',
            58.2
        );

        // Register Dashboard Submenu (as the default page)
        add_submenu_page(
            'unlockafe-advanced-coupons',
            __('Dashboard', 'unlock-addons-for-elementor'),
            __('Dashboard', 'unlock-addons-for-elementor'),
            'manage_woocommerce',
            'unlockafe-advanced-coupons', // Same slug as parent
            [$this, 'render_settings_page']
        );

        // Register Store Credit Submenu
        add_submenu_page(
            'unlockafe-advanced-coupons',
            __('Store Credit', 'unlock-addons-for-elementor'),
            __('Store Credit', 'unlock-addons-for-elementor'),
            'manage_woocommerce',
            'unlock-gift-cards',
            [\Unlockafe_Addons\Admin\Store_Credit_Admin::instance(), 'render_admin_page']
        );

        // Register Reporting Submenu
        add_submenu_page(
            'unlockafe-advanced-coupons',
            __('Reporting', 'unlock-addons-for-elementor'),
            __('Reporting', 'unlock-addons-for-elementor'),
            'manage_woocommerce',
            'unlockafe-coupons-reporting',
            [new \Unlockafe_Addons\Classes\Reporting_Dashboard_Controller(), 'render_reporting_page']
        );
    }

    public function render_settings_page()
    {
        ?>
        <style>
            .wp-admin-theme-dark .welcome-panel-content h2,
            .wp-admin-theme-dark .welcome-panel-content p,
            .wp-admin-theme-dark .welcome-panel-column h4,
            .wp-admin-theme-dark .welcome-panel-column ul li a {
                color: #fff !important;
            }
        </style>
        <div class="wrap">
            <h1><?php echo esc_html__('Advanced Coupons', 'unlock-addons-for-elementor'); ?></h1>
            <p><?php echo esc_html__('Manage your advanced coupon features from this central dashboard.', 'unlock-addons-for-elementor'); ?></p>

            <div class="welcome-panel">
                <div class="welcome-panel-content">
                    <h2 style="color: #fff !important; margin-left: 15px;"><?php echo esc_html__('Quick Links', 'unlock-addons-for-elementor'); ?></h2>
                    <p style="color: #fff !important; margin-left: 15px;" class="about-description"><?php echo esc_html__('Use these links to quickly access coupon features.', 'unlock-addons-for-elementor'); ?></p>
                    <div class="welcome-panel-column-container">
                        <div class="welcome-panel-column">
                            <h4><?php echo esc_html__('Manage Coupons', 'unlock-addons-for-elementor'); ?></h4>
                            <ul>
                                <li><a href="<?php echo esc_url(admin_url('edit.php?post_type=shop_coupon')); ?>" class="welcome-icon welcome-view-site"><?php echo esc_html__('View All Coupons', 'unlock-addons-for-elementor'); ?></a></li>
                                <li><a href="<?php echo esc_url(admin_url('post-new.php?post_type=shop_coupon')); ?>" class="welcome-icon welcome-add-page"><?php echo esc_html__('Add New Coupon', 'unlock-addons-for-elementor'); ?></a></li>
                            </ul>
                        </div>
                        <div class="welcome-panel-column">
                            <h4><?php echo esc_html__('Features', 'unlock-addons-for-elementor'); ?></h4>
                            <ul>
                                <li><a href="<?php echo esc_url(admin_url('admin.php?page=unlock-gift-cards')); ?>" class="welcome-icon welcome-widgets-menus"><?php echo esc_html__('Store Credit', 'unlock-addons-for-elementor'); ?></a></li>
                                <li><a href="<?php echo esc_url(admin_url('admin.php?page=unlockafe-coupons-reporting')); ?>" class="welcome-icon welcome-learn-more"><?php echo esc_html__('Reporting', 'unlock-addons-for-elementor'); ?></a></li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    public function add_usage_restriction_fields()
    {
        global $post;
        $coupon = new \WC_Coupon($post->ID);

        echo '<div class="options_group">';

        // Is Gift Card
        woocommerce_wp_checkbox([
            'id'          => '_is_gift_card',
            'label'       => __('This is a Gift Card', 'unlock-addons-for-elementor'),
            'description' => __('If checked, this coupon will add its amount to the user\'s store credit balance instead of applying a discount to the cart.', 'unlock-addons-for-elementor'),
            'value'       => $coupon->get_meta('_is_gift_card'),
            'cbvalue'     => 'yes',
            'desc_tip'    => true,
        ]);

        // Allow with other coupons (Stackable)
        woocommerce_wp_checkbox([
            'id'          => '_unlockafe_is_stackable',
            'label'       => __('Allow with other coupons', 'unlock-addons-for-elementor'),
            'description' => __('Check this box to allow this coupon to be used in conjunction with other coupons.', 'unlock-addons-for-elementor'),
            'value'       => $coupon->get_meta('_unlockafe_is_stackable'),
            'cbvalue'     => 'yes',
            'desc_tip'    => true,
        ]);

        // Maximum Discount
        echo '<h4>' . __('Discount Cap', 'unlock-addons-for-elementor') . '</h4>';
        woocommerce_wp_text_input([
            'id'          => 'unlockafe_max_discount_amount',
            'label'       => __('Maximum Discount Amount', 'unlock-addons-for-elementor'),
            'placeholder' => __('e.g., 50', 'unlock-addons-for-elementor'),
            'description' => __('Set a maximum discount amount for percentage-based coupons. Leave blank for no limit.', 'unlock-addons-for-elementor'),
            'type'        => 'number',
            'desc_tip'    => true,
            'value'       => $coupon->get_meta('unlockafe_max_discount_amount'),
            'custom_attributes' => ['step' => '0.01'],
        ]);
        echo '</div>';

        echo '<div class="options_group">';
        echo '<h4>' . __('Advanced Usage Limits', 'unlock-addons-for-elementor') . '</h4>';
        woocommerce_wp_select([
            'id'          => 'unlockafe_limit_usage_per_time_period',
            'label'       => __('Limit usage per time period', 'unlock-addons-for-elementor'),
            'options'     => [
                ''       => __('No limit', 'unlock-addons-for-elementor'),
                'day'    => __('Once per day', 'unlock-addons-for-elementor'),
                'week'   => __('Once per week', 'unlock-addons-for-elementor'),
                'month'  => __('Once per month', 'unlock-addons-for-elementor'),
                'year'   => __('Once per year', 'unlock-addons-for-elementor'),
            ],
            'description' => __('Allows the coupon to be used once per selected time period by the same user.', 'unlock-addons-for-elementor'),
            'desc_tip'    => true,
            'value'       => $coupon->get_meta('unlockafe_limit_usage_per_time_period'),
        ]);

        woocommerce_wp_checkbox([
            'id'          => 'unlockafe_strict_one_time_use',
            'label'       => __('Strict one-time use per user', 'unlock-addons-for-elementor'),
            'description' => __('Enforces a strict one-time use policy by checking against the logged-in user ID, not just the billing email. Prevents users from bypassing limits by using different email addresses.', 'unlock-addons-for-elementor'),
            'value'       => $coupon->get_meta('unlockafe_strict_one_time_use') === 'yes' ? 'yes' : '',
            'cbvalue'     => 'yes',
            'desc_tip'    => true,
        ]);
        echo '</div>';

        echo '<div class="options_group">';
        echo '<h4>' . __('Reset Usage Counter', 'unlock-addons-for-elementor') . '</h4>';
        echo '<p class="form-field">';
        echo '<label for="unlockafe_reset_usage_button">' . esc_html__('Reset Usage Data', 'unlock-addons-for-elementor') . '</label>';
        echo '<button type="button" class="button button-secondary" id="unlockafe_reset_usage_button" data-coupon-id="' . esc_attr($coupon->get_id()) . '" data-nonce="' . wp_create_nonce('unlockafe_reset_coupon_usage_nonce') . '">' . esc_html__('Reset Now', 'unlock-addons-for-elementor') . '</button>';
        echo '<span class="description">' . esc_html__('This will reset the usage count and clear the list of users who have used this coupon.', 'unlock-addons-for-elementor') . '</span>';
        echo '<span id="unlockafe-reset-spinner" class="spinner" style="float: none; visibility: hidden;"></span>';
        echo '<span id="unlockafe-reset-message" style="display: block; margin-top: 5px;"></span>';
        echo '</p>';
        echo '</div>';
    }

    public function add_advanced_restriction_fields($coupon)
    {
        echo '<div class="options_group">';
        echo '<h4>' . __('Cart Restrictions', 'unlock-addons-for-elementor') . '</h4>';
        woocommerce_wp_text_input([
            'id'          => 'unlockafe_min_cart_subtotal',
            'label'       => __('Minimum Cart Subtotal', 'unlock-addons-for-elementor'),
            'placeholder' => __('e.g., 100', 'unlock-addons-for-elementor'),
            'description' => __('The minimum subtotal required to use this coupon.', 'unlock-addons-for-elementor'),
            'type'        => 'number',
            'desc_tip'    => true,
            'value'       => $coupon->get_meta('unlockafe_min_cart_subtotal'),
        ]);

        woocommerce_wp_text_input([
            'id'          => 'unlockafe_max_cart_subtotal',
            'label'       => __('Maximum Cart Subtotal', 'unlock-addons-for-elementor'),
            'placeholder' => __('e.g., 500', 'unlock-addons-for-elementor'),
            'description' => __('The maximum subtotal allowed to use this coupon.', 'unlock-addons-for-elementor'),
            'type'        => 'number',
            'desc_tip'    => true,
            'value'       => $coupon->get_meta('unlockafe_max_cart_subtotal'),
        ]);

        woocommerce_wp_checkbox([
            'id'          => 'unlockafe_first_time_customer',
            'label'       => __('First Time Customer Only', 'unlock-addons-for-elementor'),
            'description' => __('Check this box to limit the coupon to customers who have not completed an order before.', 'unlock-addons-for-elementor'),
            'value'       => $coupon->get_meta('unlockafe_first_time_customer'),
            'cbvalue'     => 'yes',
            'desc_tip'    => true,
        ]);

        // User Role Restriction
        $user_roles = get_editable_roles();
        $roles = [];
        foreach ($user_roles as $role => $details) {
            $roles[$role] = translate_user_role($details['name']);
        }
        woocommerce_wp_select([
            'id'          => 'unlockafe_user_role',
            'label'       => __('Allowed User Roles', 'unlock-addons-for-elementor'),
            'options'     => $roles,
            'class'       => 'wc-enhanced-select',
            'value'       => $coupon->get_meta('unlockafe_user_role'),
            'custom_attributes' => ['multiple' => 'multiple'],
        ]);
        echo '</div>';

        echo '<div class="options_group">';
        // Payment Method Restriction
        $payment_gateways = WC()->payment_gateways->get_available_payment_gateways();
        $gateways = [];
        foreach ($payment_gateways as $gateway) {
            $gateways[$gateway->id] = $gateway->get_title();
        }
        woocommerce_wp_select([
            'id'          => 'unlockafe_payment_method',
            'label'       => __('Allowed Payment Methods', 'unlock-addons-for-elementor'),
            'options'     => $gateways,
            'class'       => 'wc-enhanced-select',
            'value'       => $coupon->get_meta('unlockafe_payment_method'),
            'custom_attributes' => ['multiple' => 'multiple'],
        ]);

        // Shipping Method Restriction
        $shipping_methods = WC()->shipping->get_shipping_methods();
        $methods = [];
        foreach ($shipping_methods as $method) {
            $methods[$method->id] = $method->get_method_title();
        }
        woocommerce_wp_select([
            'id'          => 'unlockafe_shipping_method',
            'label'       => __('Allowed Shipping Methods', 'unlock-addons-for-elementor'),
            'options'     => $methods,
            'class'       => 'wc-enhanced-select',
            'value'       => $coupon->get_meta('unlockafe_shipping_method'),
            'custom_attributes' => ['multiple' => 'multiple'],
        ]);
        echo '</div>';

        echo '<div class="options_group">';
        // Location Restrictions
        echo '<h4>' . __('Location Restrictions', 'unlock-addons-for-elementor') . '</h4>';

        // Country Restriction
        $countries = WC()->countries->get_countries();
        woocommerce_wp_select([
            'id'          => 'unlockafe_allowed_countries',
            'label'       => __('Allowed Countries', 'unlock-addons-for-elementor'),
            'options'     => ['' => __('All Countries', 'unlock-addons-for-elementor')] + $countries,
            'class'       => 'wc-enhanced-select',
            'value'       => $coupon->get_meta('unlockafe_allowed_countries'),
            'custom_attributes' => ['multiple' => 'multiple'],
        ]);

        // State/Region Restriction
        woocommerce_wp_text_input([
            'id'          => 'unlockafe_allowed_states',
            'label'       => __('Allowed States/Regions', 'unlock-addons-for-elementor'),
            'placeholder' => __('e.g., CA, NY', 'unlock-addons-for-elementor'),
            'description' => __('Comma-separated list of state codes.', 'unlock-addons-for-elementor'),
            'desc_tip'    => true,
            'value'       => is_array($coupon->get_meta('unlockafe_allowed_states')) ? implode(', ', $coupon->get_meta('unlockafe_allowed_states')) : '',
        ]);

        // Postcode Restriction
        woocommerce_wp_text_input([
            'id'          => 'unlockafe_allowed_postcodes',
            'label'       => __('Allowed Postcodes', 'unlock-addons-for-elementor'),
            'placeholder' => __('e.g., 90210, 10001', 'unlock-addons-for-elementor'),
            'description' => __('Comma-separated list of postcodes.', 'unlock-addons-for-elementor'),
            'desc_tip'    => true,
            'value'       => is_array($coupon->get_meta('unlockafe_allowed_postcodes')) ? implode(', ', $coupon->get_meta('unlockafe_allowed_postcodes')) : '',
        ]);
        echo '</div>';

        echo '<div class="options_group">';
        // Schedule Restrictions
        echo '<h4>' . __('Schedule Restrictions', 'unlock-addons-for-elementor') . '</h4>';
        $days_of_week = [
            'monday'    => __('Monday', 'unlock-addons-for-elementor'),
            'tuesday'   => __('Tuesday', 'unlock-addons-for-elementor'),
            'wednesday' => __('Wednesday', 'unlock-addons-for-elementor'),
            'thursday'  => __('Thursday', 'unlock-addons-for-elementor'),
            'friday'    => __('Friday', 'unlock-addons-for-elementor'),
            'saturday'  => __('Saturday', 'unlock-addons-for-elementor'),
            'sunday'    => __('Sunday', 'unlock-addons-for-elementor'),
        ];
        woocommerce_wp_select([
            'id'          => 'unlockafe_allowed_days',
            'label'       => __('Allowed Days of the Week', 'unlock-addons-for-elementor'),
            'options'     => $days_of_week,
            'class'       => 'wc-enhanced-select',
            'value'       => $coupon->get_meta('unlockafe_allowed_days'),
            'custom_attributes' => ['multiple' => 'multiple'],
        ]);
        echo '</div>';

        echo '<div class="options_group">';
        // Taxonomy Restrictions
        echo '<h4>' . __('Taxonomy Restrictions', 'unlock-addons-for-elementor') . '</h4>';
        echo '<p class="form-field"><label>' . __('Allowed Product Tags', 'unlock-addons-for-elementor') . '</label><select class="wc-taxonomy-search" multiple="multiple" style="width: 50%;" name="unlockafe_allowed_tags[]" data-placeholder="' . esc_attr__('Search for a tag…', 'woocommerce') . '" data-taxonomy="product_tag">';
        $allowed_tags = $coupon->get_meta('unlockafe_allowed_tags');
        if (!empty($allowed_tags) && is_array($allowed_tags)) {
            $tag_options = $this->get_terms_for_select($allowed_tags, 'product_tag');
            foreach ($tag_options as $id => $name) {
                echo '<option value="' . esc_attr($id) . '" selected="selected">' . esc_html($name) . '</option>';
            }
        }
        echo '</select></p>';
        echo '</div>';
    }

    public function add_bogo_deal_fields($coupon)
    {
        echo '<div class="options_group">';
        echo '<h4>' . __('Buy X', 'unlock-addons-for-elementor') . '</h4>';
        woocommerce_wp_text_input([
            'id'          => 'unlockafe_bogo_buy_quantity',
            'label'       => __('Quantity', 'unlock-addons-for-elementor'),
            'type'        => 'number',
            'custom_attributes' => ['min' => 1],
            'value'       => $coupon->get_meta('unlockafe_bogo_buy_quantity') ?: 1,
        ]);
        echo '<p class="form-field"><label>' . __('Products', 'unlock-addons-for-elementor') . '</label><select class="wc-product-search" multiple="multiple" style="width: 50%;" name="unlockafe_bogo_buy_product_ids[]" data-placeholder="' . esc_attr__('Search for a product…', 'woocommerce') . '">';
        $buy_product_ids = $coupon->get_meta('unlockafe_bogo_buy_product_ids');
        $product_options = $this->get_products_for_select($buy_product_ids);
        foreach ($product_options as $id => $name) {
            echo '<option value="' . esc_attr($id) . '" selected="selected">' . esc_html($name) . '</option>';
        }
        echo '</select></p>';

        echo '<p class="form-field"><label>' . __('Categories', 'unlock-addons-for-elementor') . '</label><select class="wc-category-search" multiple="multiple" style="width: 50%;" name="unlockafe_bogo_buy_category_ids[]" data-placeholder="' . esc_attr__('Search for a category…', 'woocommerce') . '">';
        $buy_category_ids = $coupon->get_meta('unlockafe_bogo_buy_category_ids');
        $category_options = $this->get_categories_for_select($buy_category_ids);
        foreach ($category_options as $id => $name) {
            echo '<option value="' . esc_attr($id) . '" selected="selected">' . esc_html($name) . '</option>';
        }
        echo '</select></p>';
        echo '</div>';

        echo '<div class="options_group">';
        echo '<h4>' . __('Get Y', 'unlock-addons-for-elementor') . '</h4>';
        woocommerce_wp_text_input([
            'id'          => 'unlockafe_bogo_get_quantity',
            'label'       => __('Quantity', 'unlock-addons-for-elementor'),
            'type'        => 'number',
            'custom_attributes' => ['min' => 1],
            'value'       => $coupon->get_meta('unlockafe_bogo_get_quantity') ?: 1,
        ]);
        echo '<p class="form-field"><label>' . __('Products', 'unlock-addons-for-elementor') . '</label><select class="wc-product-search" multiple="multiple" style="width: 50%;" name="unlockafe_bogo_get_product_ids[]" data-placeholder="' . esc_attr__('Search for a product…', 'woocommerce') . '">';
        $get_product_ids = $coupon->get_meta('unlockafe_bogo_get_product_ids');
        $product_options = $this->get_products_for_select($get_product_ids);
        foreach ($product_options as $id => $name) {
            echo '<option value="' . esc_attr($id) . '" selected="selected">' . esc_html($name) . '</option>';
        }
        echo '</select></p>';

        echo '<p class="form-field"><label>' . __('Categories', 'unlock-addons-for-elementor') . '</label><select class="wc-category-search" multiple="multiple" style="width: 50%;" name="unlockafe_bogo_get_category_ids[]" data-placeholder="' . esc_attr__('Search for a category…', 'woocommerce') . '">';
        $get_category_ids = $coupon->get_meta('unlockafe_bogo_get_category_ids');
        $category_options = $this->get_categories_for_select($get_category_ids);
        foreach ($category_options as $id => $name) {
            echo '<option value="' . esc_attr($id) . '" selected="selected">' . esc_html($name) . '</option>';
        }
        echo '</select></p>';

        woocommerce_wp_select([
            'id'      => 'unlockafe_bogo_get_selection',
            'label'   => __('Apply to', 'unlock-addons-for-elementor'),
            'options' => [
                'first'    => __('First matching item', 'unlock-addons-for-elementor'),
                'cheapest' => __('Cheapest matching item', 'unlock-addons-for-elementor'),
            ],
            'value'   => $coupon->get_meta('unlockafe_bogo_get_selection'),
        ]);

        woocommerce_wp_select([
            'id'      => 'unlockafe_bogo_discount_type',
            'label'   => __('Discount Type', 'unlock-addons-for-elementor'),
            'options' => [
                'free'       => __('Free', 'unlock-addons-for-elementor'),
                'percentage' => __('Percentage Discount', 'unlock-addons-for-elementor'),
                'fixed'      => __('Fixed Discount', 'unlock-addons-for-elementor'),
            ],
            'value'   => $coupon->get_meta('unlockafe_bogo_discount_type'),
        ]);

        woocommerce_wp_text_input([
            'id'          => 'unlockafe_bogo_discount_amount',
            'label'       => __('Discount Amount', 'unlock-addons-for-elementor'),
            'type'        => 'number',
            'custom_attributes' => ['step' => '0.01'],
            'value'       => $coupon->get_meta('unlockafe_bogo_discount_amount'),
        ]);
        echo '</div>';
    }

    public function add_coupon_data_tabs($tabs)
    {
        $tabs['unlockafe_advanced_restrictions'] = [
            'label'  => __('Advanced Restrictions', 'unlock-addons-for-elementor'),
            'target' => 'unlockafe_advanced_restrictions_data',
            'class'  => 'unlockafe_advanced_restrictions_tab',
        ];

        $tabs['unlockafe_bogo_deals'] = [
            'label'  => __('BOGO Deals', 'unlock-addons-for-elementor'),
            'target' => 'unlockafe_bogo_deals_data',
            'class'  => 'unlockafe_bogo_deals_tab',
        ];

        $tabs['unlockafe_actions_display'] = [
            'label'  => __('Actions & Display', 'unlock-addons-for-elementor'),
            'target' => 'unlockafe_actions_display_data',
            'class'  => 'unlockafe_actions_display_tab',
        ];
        return $tabs;
    }

    public function add_coupon_data_panels()
    {
        global $post;
        $coupon = new \WC_Coupon($post->ID);

        // Advanced Restrictions Panel
        echo '<div id="unlockafe_advanced_restrictions_data" class="panel woocommerce_options_panel hidden">';
        do_action('unlockafe_advanced_restrictions_panel', $coupon);
        echo '</div>';

        // BOGO Deals Panel
        echo '<div id="unlockafe_bogo_deals_data" class="panel woocommerce_options_panel hidden">';
        do_action('unlockafe_bogo_deals_panel', $coupon);
        echo '</div>';

        // Actions & Display Panel
        echo '<div id="unlockafe_actions_display_data" class="panel woocommerce_options_panel hidden">';

        woocommerce_wp_checkbox([
            'id'          => 'unlockafe_auto_apply_coupon',
            'label'       => __('Auto-Apply Coupon', 'unlock-addons-for-elementor'),
            'description' => __('When enabled, this coupon will automatically apply to a customer\'s cart if its conditions are met. The system will apply the best available auto-apply coupon.', 'unlock-addons-for-elementor'),
            'value'       => $coupon->get_meta('unlockafe_auto_apply_coupon') === 'yes' ? 'yes' : '',
            'cbvalue'     => 'yes',
            'desc_tip'    => true,
        ]);

        woocommerce_wp_text_input([
            'id'          => 'unlockafe_coupon_priority',
            'label'       => __('Coupon Priority', 'unlock-addons-for-elementor'),
            'description' => __('Set a priority for this coupon. Lower numbers run first. This is important for auto-applied coupons.', 'unlock-addons-for-elementor'),
            'type'        => 'number',
            'value'       => $coupon->get_meta('unlockafe_coupon_priority', true, 'edit'),
            'desc_tip'    => true,
        ]);

        woocommerce_wp_text_input([
            'id'          => 'unlockafe_custom_coupon_url',
            'label'       => __('Custom Coupon URL', 'unlock-addons-for-elementor'),
            'description' => __('Create a custom URL to apply this coupon. e.g., yourstore.com/coupon/special-deal', 'unlock-addons-for-elementor'),
            'value'       => $coupon->get_meta('unlockafe_custom_coupon_url'),
            'desc_tip'    => true,
        ]);

        $coupon_url = $this->get_coupon_url($coupon);
        if ($coupon_url) {
            woocommerce_wp_text_input([
                'id'          => 'unlockafe_shareable_coupon_url',
                'label'       => __('Shareable Coupon URL', 'unlock-addons-for-elementor'),
                'description' => __('Share this URL to automatically apply the coupon. Perfect for email campaigns.', 'unlock-addons-for-elementor'),
                'desc_tip'    => true,
                'value'       => $coupon_url,
                'custom_attributes' => ['readonly' => 'readonly'],
            ]);
        }

        echo '</div>';
    }

    private function get_coupon_url($coupon)
    {
        if (!is_a($coupon, 'WC_Coupon')) {
            return '';
        }

        $coupon_code = $coupon->get_code();
        $custom_slug = $coupon->get_meta('unlockafe_custom_coupon_url');

        if (!empty($custom_slug)) {
            // Assuming a rewrite rule is set up for /coupon/[slug]/
            return home_url('/coupon/' . $custom_slug . '/');
        } else {
            return add_query_arg('apply_coupon', $coupon_code, home_url());
        }
    }

    public function display_reset_usage_button($coupon_id)
    {
        ?>
        <p class="form-field">
            <label for="unlockafe_reset_usage_button"><?php esc_html_e('Reset Usage Data', 'unlock-addons-for-elementor'); ?></label>
            <button type="button" class="button button-secondary" id="unlockafe_reset_usage_button" data-coupon-id="<?php echo esc_attr($coupon_id); ?>" data-nonce="<?php echo wp_create_nonce('unlockafe_reset_coupon_usage_nonce'); ?>"><?php esc_html_e('Reset Now', 'unlock-addons-for-elementor'); ?></button>
            <span class="description"><?php esc_html_e('This will reset the usage count and clear the list of users who have used this coupon.', 'unlock-addons-for-elementor'); ?></span>
            <span id="unlockafe-reset-spinner" class="spinner" style="float: none; visibility: hidden;"></span>
            <span id="unlockafe-reset-message" style="display: block; margin-top: 5px;"></span>
        </p>
        <script type="text/javascript">
            jQuery(document).ready(function($) {
                $('#unlockafe_reset_usage_button').on('click', function() {
                    var button = $(this);
                    var couponId = button.data('coupon-id');
                    var nonce = button.data('nonce');
                    var spinner = $('#unlockafe-reset-spinner');
                    var messageContainer = $('#unlockafe-reset-message');

                    spinner.css('visibility', 'visible');

                    $.ajax({
                        url: '<?php echo admin_url('admin-ajax.php'); ?>',
                        type: 'POST',
                        data: {
                            action: 'unlockafe_reset_coupon_usage',
                            coupon_id: couponId,
                            nonce: nonce
                        },
                        success: function(response) {
                            spinner.css('visibility', 'hidden');
                            if (response.success) {
                                messageContainer.css('color', 'green').text(response.data.message);
                            } else {
                                messageContainer.css('color', 'red').text(response.data.message);
                            }
                        },
                        error: function() {
                            spinner.css('visibility', 'hidden');
                            messageContainer.css('color', 'red').text('An error occurred.');
                        }
                    });
                });
            });
        </script>
        <?php

    } // End add_coupon_data_panels

    public function validate_coupon_for_bogo($is_valid, $coupon)
    {
        if (!$is_valid) {
            return $is_valid;
        }

        $buy_product_ids = $coupon->get_meta('unlockafe_bogo_buy_product_ids');
        $buy_category_ids = $coupon->get_meta('unlockafe_bogo_buy_category_ids');

        // If it's not a BOGO coupon, skip validation.
        if (empty($buy_product_ids) && empty($buy_category_ids)) {
            return $is_valid;
        }

        $buy_quantity = (int) $coupon->get_meta('unlockafe_bogo_buy_quantity') ?: 1;
        $get_quantity = (int) $coupon->get_meta('unlockafe_bogo_get_quantity') ?: 1;
        $get_product_ids = $coupon->get_meta('unlockafe_bogo_get_product_ids');
        $get_category_ids = $coupon->get_meta('unlockafe_bogo_get_category_ids');

        // Not a valid BOGO if no "get" items are defined.
        if (empty($get_product_ids) && empty($get_category_ids)) {
            return $is_valid;
        }

        $cart_items = WC()->cart->get_cart();
        $buy_items_quantity = 0;
        $get_items_quantity = 0;

        foreach ($cart_items as $cart_item) {
            $product_id = $cart_item['product_id'];
            $variation_id = $cart_item['variation_id'];

            $is_buy_item = !empty($buy_product_ids) && (in_array($product_id, $buy_product_ids) || in_array($variation_id, $buy_product_ids));
            if (!$is_buy_item && !empty($buy_category_ids)) {
                if (has_term($buy_category_ids, 'product_cat', $product_id)) {
                    $is_buy_item = true;
                }
            }
            if ($is_buy_item) {
                $buy_items_quantity += $cart_item['quantity'];
            }

            $is_get_item = !empty($get_product_ids) && (in_array($product_id, $get_product_ids) || in_array($variation_id, $get_product_ids));
            if (!$is_get_item && !empty($get_category_ids)) {
                if (has_term($get_category_ids, 'product_cat', $product_id)) {
                    $is_get_item = true;
                }
            }
            if ($is_get_item) {
                $get_items_quantity += $cart_item['quantity'];
            }
        }

        if ($buy_items_quantity < $buy_quantity) {
            throw new \Exception(sprintf(__('To use this coupon, you need to purchase at least %d of the required items.', 'unlock-addons-for-elementor'), $buy_quantity));
        }

        if ($get_items_quantity < $get_quantity) {
            throw new \Exception(sprintf(__('To use this coupon, you need to have at least %d of the free/discounted items in your cart.', 'unlock-addons-for-elementor'), $get_quantity));
        }

        return $is_valid;
    }

    /**
     * Validate Time Period Usage Limit
     *
     * @param boolean $is_valid
     * @param \WC_Coupon $coupon
     * @return boolean|\WP_Error
     */
    public function validate_time_period_usage_limit($is_valid, $coupon)
    {
        error_log('UNLOCKAFE DEBUG: validate_time_period_usage_limit - Coupon: ' . $coupon->get_code() . ', Initial valid: ' . ($is_valid ? 'true' : 'false'));

        if (!$is_valid) {
            error_log('UNLOCKAFE DEBUG: Already invalid, returning false');
            return $is_valid;
        }

        $coupon_id = $coupon->get_id();
        $limit_period = get_post_meta($coupon_id, 'unlockafe_limit_usage_per_time_period', true);

        if (empty($limit_period)) {
            error_log('UNLOCKAFE DEBUG: No time period limit set, returning: ' . ($is_valid ? 'true' : 'false'));
            return $is_valid; // No time limit set
        }

        if (!is_user_logged_in()) {
            return $is_valid; // Cannot check usage for guests
        }

        $user_id = get_current_user_id();
        $start_date = '';

        switch ($limit_period) {
            case 'day':
                $start_date = date('Y-m-d 00:00:00');
                break;
            case 'week':
                $start_date = date('Y-m-d 00:00:00', strtotime('monday this week'));
                break;
            case 'month':
                $start_date = date('Y-m-01 00:00:00');
                break;
            case 'year':
                $start_date = date('Y-01-01 00:00:00');
                break;
        }

        if (empty($start_date)) {
            return $is_valid;
        }

        $orders = wc_get_orders([
            'customer_id' => $user_id,
            'status'      => wc_get_is_paid_statuses(),
            'date_after'  => $start_date,
            'limit'       => -1,
        ]);

        foreach ($orders as $order) {
            if (in_array($coupon->get_code(), $order->get_coupon_codes(), true)) {
                // translators: %s: coupon code
                throw new \Exception(sprintf(__('You have already used this coupon in the current %s.', 'unlock-addons-for-elementor'), $limit_period));
            }
        }

        return $is_valid;
    }

    /**
     * Validate User Role Usage Limit
     *
     * @param boolean $is_valid
     * @param \WC_Coupon $coupon
     * @return boolean|\WP_Error
     */
    public function validate_user_role_usage_limit($is_valid, $coupon)
    {

        if (!$is_valid) {
            return $is_valid;
        }

        $coupon_id = $coupon->get_id();
        $allowed_roles = get_post_meta($coupon_id, 'unlockafe_allowed_user_roles_usage', true);

        if (empty($allowed_roles)) {
            return $is_valid; // No role restriction
        }

        if (!is_user_logged_in()) {
            // translators: %s: coupon code
            throw new \Exception(sprintf(__('This coupon is only available to logged-in users with specific roles.', 'unlock-addons-for-elementor')));
        }

        $user = wp_get_current_user();
        $user_roles = (array) $user->roles;

        $is_allowed = (bool) count(array_intersect($user_roles, $allowed_roles));

        if (!$is_allowed) {
            // translators: %s: coupon code
            throw new \Exception(sprintf(__('Sorry, this coupon is not valid for your user role.', 'unlock-addons-for-elementor')));
        }

        return $is_valid;
    }

    /**
     * Validate Strict One-Time Use per Email
     *
     * @param boolean $is_valid
     * @param \WC_Coupon $coupon
     * @param \WC_Discounts $discounts
     * @return boolean|\WP_Error
     */
    public function validate_strict_one_time_use($is_valid, $coupon, $discounts)
    {
        error_log('UNLOCKAFE DEBUG: validate_strict_one_time_use - Coupon: ' . $coupon->get_code() . ', Initial valid: ' . ($is_valid ? 'true' : 'false'));
        
        if (!$is_valid) {
            error_log('UNLOCKAFE DEBUG: Already invalid, returning false');
            return $is_valid;
        }

        $coupon_id = $coupon->get_id();
        $is_strict = get_post_meta($coupon_id, 'unlockafe_strict_one_time_use', true);

        if ('yes' !== $is_strict) {
            error_log('UNLOCKAFE DEBUG: Not strict one-time use, returning: ' . ($is_valid ? 'true' : 'false'));
            return $is_valid;
        }

        $billing_email = '';
        if (is_user_logged_in()) {
            $user = wp_get_current_user();
            $billing_email = $user->billing_email;
        }

        if (empty($billing_email) && is_object($discounts) && is_callable([$discounts, 'get_customer']) && $discounts->get_customer()) {
            $billing_email = $discounts->get_customer()->get_billing_email();
        }

        if (empty($billing_email)) {
            return $is_valid;
        }

        global $wpdb;
        $usage_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(p.ID) FROM {$wpdb->posts} p INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id WHERE p.post_type = 'shop_order' AND p.post_status IN ('" . implode("','", wc_get_is_paid_statuses()) . "') AND pm.meta_key = '_billing_email' AND pm.meta_value = %s AND p.ID IN (SELECT order_id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_item_type = 'coupon' AND order_item_name = %s)", $billing_email, $coupon->get_code()));

        if ($usage_count > 0) {
            throw new \Exception(__('This coupon has already been used with your email address.', 'unlock-addons-for-elementor'));
        }

        return $is_valid;
    }

    public function reset_coupon_usage_data()
    {
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'unlockafe_reset_coupon_usage_nonce')) {
            wp_send_json_error(['message' => __('Invalid nonce.', 'unlock-addons-for-elementor')]);
        }

        if (!current_user_can('edit_shop_coupons')) {
            wp_send_json_error(['message' => __('You do not have permission to perform this action.', 'unlock-addons-for-elementor')]);
        }

        if (empty($_POST['coupon_id'])) {
            wp_send_json_error(['message' => __('Coupon ID is missing.', 'unlock-addons-for-elementor')]);
        }

        $coupon_id = intval($_POST['coupon_id']);
        $coupon = new \WC_Coupon($coupon_id);

        if (!$coupon->get_id()) {
            wp_send_json_error(['message' => __('Invalid Coupon ID.', 'unlock-addons-for-elementor')]);
        }

        // Reset usage count and used_by meta
        delete_post_meta($coupon_id, '_used_by');
        update_post_meta($coupon_id, 'usage_count', 0);

        wp_send_json_success(['message' => __('Coupon usage data has been reset successfully.', 'unlock-addons-for-elementor')]);
    }

    public function save_coupon_meta_data($post_id)
    {
        $coupon = new \WC_Coupon($post_id);
        $is_gift_card = isset($_POST['_is_gift_card']) ? 'yes' : 'no';
        $coupon->update_meta_data('_is_gift_card', $is_gift_card);

        // Save stackable option
        $is_stackable = isset($_POST['_unlockafe_is_stackable']) && $_POST['_unlockafe_is_stackable'] === 'yes' ? 'yes' : 'no';
        $coupon->update_meta_data('_unlockafe_is_stackable', $is_stackable);


        // BOGO Deals
        $coupon->update_meta_data('unlockafe_bogo_buy_quantity', isset($_POST['unlockafe_bogo_buy_quantity']) ? absint($_POST['unlockafe_bogo_buy_quantity']) : 1);
        $coupon->update_meta_data('unlockafe_bogo_buy_product_ids', isset($_POST['unlockafe_bogo_buy_product_ids']) ? array_map('intval', (array) $_POST['unlockafe_bogo_buy_product_ids']) : []);
        $coupon->update_meta_data('unlockafe_bogo_buy_category_ids', isset($_POST['unlockafe_bogo_buy_category_ids']) ? array_map('intval', (array) $_POST['unlockafe_bogo_buy_category_ids']) : []);
        $coupon->update_meta_data('unlockafe_bogo_get_quantity', isset($_POST['unlockafe_bogo_get_quantity']) ? absint($_POST['unlockafe_bogo_get_quantity']) : 1);
        $coupon->update_meta_data('unlockafe_bogo_get_product_ids', isset($_POST['unlockafe_bogo_get_product_ids']) ? array_map('intval', (array) $_POST['unlockafe_bogo_get_product_ids']) : []);
        $coupon->update_meta_data('unlockafe_bogo_get_category_ids', isset($_POST['unlockafe_bogo_get_category_ids']) ? array_map('intval', (array) $_POST['unlockafe_bogo_get_category_ids']) : []);
        $coupon->update_meta_data('unlockafe_bogo_get_selection', isset($_POST['unlockafe_bogo_get_selection']) ? sanitize_text_field(wp_unslash($_POST['unlockafe_bogo_get_selection'])) : 'first');
        $coupon->update_meta_data('unlockafe_bogo_discount_type', isset($_POST['unlockafe_bogo_discount_type']) ? sanitize_text_field(wp_unslash($_POST['unlockafe_bogo_discount_type'])) : 'free');
        $coupon->update_meta_data('unlockafe_bogo_discount_amount', isset($_POST['unlockafe_bogo_discount_amount']) ? wc_format_decimal(wp_unslash($_POST['unlockafe_bogo_discount_amount'])) : '');

        // Advanced Restrictions
        $coupon->update_meta_data('unlockafe_min_cart_subtotal', isset($_POST['unlockafe_min_cart_subtotal']) ? wc_format_decimal(wp_unslash($_POST['unlockafe_min_cart_subtotal'])) : '');
        $coupon->update_meta_data('unlockafe_max_cart_subtotal', isset($_POST['unlockafe_max_cart_subtotal']) ? wc_format_decimal(wp_unslash($_POST['unlockafe_max_cart_subtotal'])) : '');
        $coupon->update_meta_data('unlockafe_max_discount_amount', isset($_POST['unlockafe_max_discount_amount']) ? wc_format_decimal(wp_unslash($_POST['unlockafe_max_discount_amount'])) : '');

        $coupon->update_meta_data('unlockafe_payment_method', isset($_POST['unlockafe_payment_method']) ? array_map('sanitize_text_field', (array) $_POST['unlockafe_payment_method']) : []);
        $coupon->update_meta_data('unlockafe_shipping_method', isset($_POST['unlockafe_shipping_method']) ? array_map('sanitize_text_field', (array) $_POST['unlockafe_shipping_method']) : []);
        $coupon->update_meta_data('unlockafe_user_role', isset($_POST['unlockafe_user_role']) ? array_map('sanitize_text_field', (array) $_POST['unlockafe_user_role']) : []);

        // Location
        $coupon->update_meta_data('unlockafe_allowed_countries', isset($_POST['unlockafe_allowed_countries']) ? array_map('sanitize_text_field', (array) $_POST['unlockafe_allowed_countries']) : []);
        $coupon->update_meta_data('unlockafe_allowed_states', isset($_POST['unlockafe_allowed_states']) ? sanitize_textarea_field(wp_unslash($_POST['unlockafe_allowed_states'])) : '');
        $coupon->update_meta_data('unlockafe_allowed_postcodes', isset($_POST['unlockafe_allowed_postcodes']) ? sanitize_textarea_field(wp_unslash($_POST['unlockafe_allowed_postcodes'])) : '');

        // Schedule
        $coupon->update_meta_data('unlockafe_allowed_days', isset($_POST['unlockafe_allowed_days']) ? array_map('sanitize_text_field', (array) $_POST['unlockafe_allowed_days']) : []);

        // Usage Restrictions
        $coupon->update_meta_data('unlockafe_limit_usage_per_time_period', isset($_POST['unlockafe_limit_usage_per_time_period']) ? sanitize_text_field(wp_unslash($_POST['unlockafe_limit_usage_per_time_period'])) : '');
        $coupon->update_meta_data('unlockafe_strict_one_time_use', isset($_POST['unlockafe_strict_one_time_use']) ? 'yes' : 'no');
        
        // Actions & Display
        $coupon->update_meta_data('unlockafe_auto_apply_coupon', isset($_POST['unlockafe_auto_apply_coupon']) ? 'yes' : 'no');
        $coupon->update_meta_data('unlockafe_coupon_priority', isset($_POST['unlockafe_coupon_priority']) ? absint($_POST['unlockafe_coupon_priority']) : 0);
        $coupon->update_meta_data('unlockafe_custom_coupon_url', isset($_POST['unlockafe_custom_coupon_url']) ? sanitize_text_field(wp_unslash($_POST['unlockafe_custom_coupon_url'])) : '');

        // Other
        $coupon->update_meta_data('unlockafe_first_time_customer', isset($_POST['unlockafe_first_time_customer']) ? 'yes' : 'no');
        $coupon->update_meta_data('unlockafe_allow_multiple_coupons', isset($_POST['unlockafe_allow_multiple_coupons']) ? 'yes' : 'no');

        // Taxonomy
        $coupon->update_meta_data('unlockafe_allowed_tags', isset($_POST['unlockafe_allowed_tags']) ? array_map('intval', (array) $_POST['unlockafe_allowed_tags']) : []);
        $coupon->update_meta_data('unlockafe_excluded_tags', isset($_POST['unlockafe_excluded_tags']) ? array_map('intval', (array) $_POST['unlockafe_excluded_tags']) : []);

        $coupon->save();
    }

    public function apply_max_discount_limit($discount, $discounting_amount, $cart_item, $single, $coupon)
    {
        $max_discount = $coupon->get_meta('unlockafe_max_discount_amount');

        if ($coupon->is_type('percent') && !empty($max_discount) && is_numeric($max_discount)) {
            if ($discount > $max_discount) {
                return $max_discount;
            }
        }

        return $discount;
    }

    public function validate_advanced_restrictions($valid, $coupon, $discounts)
    {
        error_log('UNLOCKAFE DEBUG: validate_advanced_restrictions - Coupon: ' . $coupon->get_code() . ', Initial valid: ' . ($valid ? 'true' : 'false'));
        
        // If already invalid, don't process further
        if (!$valid) {
            error_log('UNLOCKAFE DEBUG: Already invalid, returning false');
            return $valid;
        }

        if (is_null(WC()->cart)) {
            error_log('UNLOCKAFE DEBUG: Cart is null, returning: ' . ($valid ? 'true' : 'false'));
            return $valid;
        }

        try {
            error_log('UNLOCKAFE DEBUG: Starting advanced restrictions validation');
            
            $min_subtotal = (float) $coupon->get_meta('unlockafe_min_cart_subtotal');
            error_log('UNLOCKAFE DEBUG: Min subtotal check - Required: ' . $min_subtotal . ', Cart: ' . WC()->cart->get_subtotal());
            if ($min_subtotal > 0 && WC()->cart->get_subtotal() < $min_subtotal) {
                error_log('UNLOCKAFE DEBUG: FAILED - Min subtotal not met');
                throw new \Exception(__('The minimum required cart subtotal for this coupon is not met.', 'unlock-addons-for-elementor'));
            }

            $max_subtotal = (float) $coupon->get_meta('unlockafe_max_cart_subtotal');
            error_log('UNLOCKAFE DEBUG: Max subtotal check - Limit: ' . $max_subtotal . ', Cart: ' . WC()->cart->get_subtotal());
            if ($max_subtotal > 0 && WC()->cart->get_subtotal() > $max_subtotal) {
                error_log('UNLOCKAFE DEBUG: FAILED - Max subtotal exceeded');
                throw new \Exception(__('The maximum allowed cart subtotal for this coupon is exceeded.', 'unlock-addons-for-elementor'));
            }

            $allowed_payment_methods = $coupon->get_meta('unlockafe_allowed_payment_methods');
            error_log('UNLOCKAFE DEBUG: Payment method check - Allowed: ' . print_r($allowed_payment_methods, true));
            if (!empty($allowed_payment_methods) && is_array($allowed_payment_methods)) {
                $chosen_payment_method = WC()->session->get('chosen_payment_method');
                error_log('UNLOCKAFE DEBUG: Chosen payment method: ' . $chosen_payment_method);
                if (!in_array($chosen_payment_method, $allowed_payment_methods, true)) {
                    error_log('UNLOCKAFE DEBUG: FAILED - Payment method not allowed');
                    throw new \Exception(__('This coupon is not valid for the selected payment method.', 'unlock-addons-for-elementor'));
                }
            }

            $allowed_user_roles = $coupon->get_meta('unlockafe_allowed_user_roles');
            error_log('UNLOCKAFE DEBUG: User role check - Allowed: ' . print_r($allowed_user_roles, true));
            if (!empty($allowed_user_roles) && is_array($allowed_user_roles)) {
                $user = wp_get_current_user();
                error_log('UNLOCKAFE DEBUG: Current user roles: ' . print_r($user->roles, true));
                if (!$user || !array_intersect($user->roles, $allowed_user_roles)) {
                    error_log('UNLOCKAFE DEBUG: FAILED - User role not allowed');
                    throw new \Exception(__('This coupon is not valid for your user role.', 'unlock-addons-for-elementor'));
                }
            }

            $first_time_customer_only = $coupon->get_meta('unlockafe_first_time_customer_only');
            error_log('UNLOCKAFE DEBUG: First-time customer check: ' . $first_time_customer_only);
            if ('yes' === $first_time_customer_only) {
                $user = wp_get_current_user();
                if ($user && $user->ID > 0) {
                    $customer_orders = wc_get_orders([
                        'customer' => $user->ID,
                        'status' => ['completed', 'processing'],
                        'limit' => 1,
                    ]);
                    error_log('UNLOCKAFE DEBUG: Customer orders count: ' . count($customer_orders));
                    if (!empty($customer_orders)) {
                        error_log('UNLOCKAFE DEBUG: FAILED - Not first-time customer');
                        throw new \Exception(__('This coupon is only valid for first-time customers.', 'unlock-addons-for-elementor'));
                    }
                }
            }

            $allowed_countries = $coupon->get_meta('unlockafe_allowed_countries');
            error_log('UNLOCKAFE DEBUG: Country check - Allowed: ' . print_r($allowed_countries, true));
            if (!empty($allowed_countries) && is_array($allowed_countries)) {
                // Filter out empty values from the allowed countries array
                $allowed_countries = array_filter($allowed_countries, function($country) {
                    return !empty(trim($country));
                });
                
                // Only apply country restriction if there are actual countries specified
                if (!empty($allowed_countries)) {
                    $customer_country = WC()->customer->get_billing_country();
                    error_log('UNLOCKAFE DEBUG: Customer country: ' . $customer_country);
                    error_log('UNLOCKAFE DEBUG: Filtered allowed countries: ' . print_r($allowed_countries, true));
                    if (!in_array($customer_country, $allowed_countries, true)) {
                        error_log('UNLOCKAFE DEBUG: FAILED - Country not allowed');
                        throw new \Exception(__('This coupon is not valid for your location.', 'unlock-addons-for-elementor'));
                    }
                } else {
                    error_log('UNLOCKAFE DEBUG: No valid countries specified, allowing all countries');
                }
            }

            $allowed_shipping_methods = $coupon->get_meta('unlockafe_allowed_shipping_methods');
            error_log('UNLOCKAFE DEBUG: Shipping method check - Allowed: ' . print_r($allowed_shipping_methods, true));
            if (!empty($allowed_shipping_methods) && is_array($allowed_shipping_methods)) {
                $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
                error_log('UNLOCKAFE DEBUG: Chosen shipping methods: ' . print_r($chosen_shipping_methods, true));
                if (empty($chosen_shipping_methods) || !array_intersect($chosen_shipping_methods, $allowed_shipping_methods)) {
                    error_log('UNLOCKAFE DEBUG: FAILED - Shipping method not allowed');
                    throw new \Exception(__('This coupon is not valid for the selected shipping method.', 'unlock-addons-for-elementor'));
                }
            }

            $schedule_start = $coupon->get_meta('unlockafe_schedule_start');
            $schedule_end = $coupon->get_meta('unlockafe_schedule_end');
            error_log('UNLOCKAFE DEBUG: Schedule check - Start: ' . $schedule_start . ', End: ' . $schedule_end);
            if (!empty($schedule_start) || !empty($schedule_end)) {
                $current_time = current_time('timestamp');
                error_log('UNLOCKAFE DEBUG: Current time: ' . $current_time);
                if (!empty($schedule_start) && $current_time < strtotime($schedule_start)) {
                    error_log('UNLOCKAFE DEBUG: FAILED - Coupon not yet active');
                    throw new \Exception(__('This coupon is not yet active.', 'unlock-addons-for-elementor'));
                }
                if (!empty($schedule_end) && $current_time > strtotime($schedule_end)) {
                    error_log('UNLOCKAFE DEBUG: FAILED - Coupon expired');
                    throw new \Exception(__('This coupon has expired.', 'unlock-addons-for-elementor'));
                }
            }

            $allowed_categories = $coupon->get_meta('unlockafe_allowed_categories');
            error_log('UNLOCKAFE DEBUG: Category check - Allowed: ' . print_r($allowed_categories, true));
            if (!empty($allowed_categories) && is_array($allowed_categories)) {
                // Filter out empty values from allowed categories
                $allowed_categories = array_filter($allowed_categories, function($category) {
                    return !empty(trim($category));
                });
                
                // Only apply category restriction if there are actual categories specified
                if (!empty($allowed_categories)) {
                    $cart_has_allowed_category = false;
                    foreach (WC()->cart->get_cart() as $cart_item) {
                        $product_categories = wp_get_post_terms($cart_item['product_id'], 'product_cat', ['fields' => 'ids']);
                        if (array_intersect($product_categories, $allowed_categories)) {
                            $cart_has_allowed_category = true;
                            break;
                        }
                    }
                    error_log('UNLOCKAFE DEBUG: Cart has allowed category: ' . ($cart_has_allowed_category ? 'yes' : 'no'));
                    if (!$cart_has_allowed_category) {
                        error_log('UNLOCKAFE DEBUG: FAILED - No allowed categories in cart');
                        throw new \Exception(__('This coupon is not valid for the products in your cart.', 'unlock-addons-for-elementor'));
                    }
                } else {
                    error_log('UNLOCKAFE DEBUG: No valid categories specified, allowing all products');
                }
            }

            $excluded_categories = $coupon->get_meta('unlockafe_excluded_categories');
            error_log('UNLOCKAFE DEBUG: Excluded category check: ' . print_r($excluded_categories, true));
            if (!empty($excluded_categories) && is_array($excluded_categories)) {
                // Filter out empty values from excluded categories
                $excluded_categories = array_filter($excluded_categories, function($category) {
                    return !empty(trim($category));
                });
                
                // Only apply exclusion if there are actual categories specified
                if (!empty($excluded_categories)) {
                    foreach (WC()->cart->get_cart() as $cart_item) {
                        $product_categories = wp_get_post_terms($cart_item['product_id'], 'product_cat', ['fields' => 'ids']);
                        if (array_intersect($product_categories, $excluded_categories)) {
                            error_log('UNLOCKAFE DEBUG: FAILED - Excluded category found in cart');
                            throw new \Exception(__('This coupon cannot be used with some products in your cart.', 'unlock-addons-for-elementor'));
                        }
                    }
                } else {
                    error_log('UNLOCKAFE DEBUG: No valid excluded categories specified, no exclusions applied');
                }
            }
            
            error_log('UNLOCKAFE DEBUG: All advanced restrictions passed, returning: ' . ($valid ? 'true' : 'false'));
        } catch (\Exception $e) {
            error_log('UNLOCKAFE DEBUG: Exception caught: ' . $e->getMessage());
            wc_add_notice($e->getMessage(), 'error');
            return false;
        }

        return $valid;
    }

    /**
     * Debug method to capture all coupon validation attempts
     */
    public function debug_coupon_validation($valid, $coupon, $discounts)
    {
        error_log('UNLOCKAFE DEBUG: === COUPON VALIDATION START ===');
        error_log('UNLOCKAFE DEBUG: Coupon Code: ' . $coupon->get_code());
        error_log('UNLOCKAFE DEBUG: Coupon ID: ' . $coupon->get_id());
        error_log('UNLOCKAFE DEBUG: Initial Valid State: ' . ($valid ? 'true' : 'false'));
        error_log('UNLOCKAFE DEBUG: Coupon Status: ' . $coupon->get_status());
        error_log('UNLOCKAFE DEBUG: Coupon Type: ' . $coupon->get_discount_type());
        error_log('UNLOCKAFE DEBUG: Coupon Amount: ' . $coupon->get_amount());
        error_log('UNLOCKAFE DEBUG: Usage Limit: ' . $coupon->get_usage_limit());
        error_log('UNLOCKAFE DEBUG: Usage Count: ' . $coupon->get_usage_count());
        error_log('UNLOCKAFE DEBUG: Date Expires: ' . $coupon->get_date_expires());
        
        // Check if cart exists
        if (is_null(WC()->cart)) {
            error_log('UNLOCKAFE DEBUG: WooCommerce cart is NULL');
        } else {
            error_log('UNLOCKAFE DEBUG: Cart subtotal: ' . WC()->cart->get_subtotal());
            error_log('UNLOCKAFE DEBUG: Cart total: ' . WC()->cart->get_total(''));
            error_log('UNLOCKAFE DEBUG: Cart item count: ' . WC()->cart->get_cart_contents_count());
        }
        
        error_log('UNLOCKAFE DEBUG: === COUPON VALIDATION END ===');
        
        return $valid;
    }

    private function validate_location_restrictions($coupon)
    {
        $customer = WC()->customer;
        if (!$customer) {
            return;
        }

        $allowed_countries = $coupon->get_meta('unlockafe_allowed_countries');
        $allowed_states = array_map('trim', explode(',', $coupon->get_meta('unlockafe_allowed_states')));
        $allowed_postcodes = array_map('trim', explode(',', $coupon->get_meta('unlockafe_allowed_postcodes')));

        // Filter out empty values from allowed countries and only apply restriction if valid countries exist
        if (!empty($allowed_countries) && is_array($allowed_countries)) {
            $allowed_countries = array_filter($allowed_countries, function($country) {
                return !empty(trim($country));
            });
            
            if (!empty($allowed_countries) && !in_array($customer->get_shipping_country(), $allowed_countries)) {
                throw new \Exception(__('This coupon is not valid for your country.', 'unlock-addons-for-elementor'));
            }
        }

        if (!empty(array_filter($allowed_states)) && !in_array($customer->get_shipping_state(), $allowed_states)) {
            throw new \Exception(__('This coupon is not valid for your state/region.', 'unlock-addons-for-elementor'));
        }

        if (!empty(array_filter($allowed_postcodes)) && !in_array($customer->get_shipping_postcode(), $allowed_postcodes)) {
            throw new \Exception(__('This coupon is not valid for your postcode.', 'unlock-addons-for-elementor'));
        }

        return true;
    }

    private function validate_schedule_restrictions($coupon)
    {
        $allowed_days = $coupon->get_meta('unlockafe_allowed_days');
        if (!empty($allowed_days)) {
            $current_day = strtolower(date('l'));
            if (!in_array($current_day, $allowed_days)) {
                throw new \Exception(__('This coupon is not valid today.', 'unlock-addons-for-elementor'));
            }
        }
        return true;
    }

    private function validate_shipping_method_restrictions($coupon)
    {
        $shipping_method_restriction = $coupon->get_meta('unlockafe_shipping_method');
        if (empty($shipping_method_restriction) || !is_array($shipping_method_restriction)) {
            return true;
        }

        $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
        if (empty($chosen_shipping_methods)) {
            return true; // Cannot validate if no method is chosen yet
        }

        $is_allowed = false;
        foreach ($chosen_shipping_methods as $chosen_method) {
            // $chosen_method can be in format 'flat_rate:1', we only need 'flat_rate'
            $method_id = explode(':', $chosen_method)[0];
            if (in_array($method_id, $shipping_method_restriction)) {
                $is_allowed = true;
                break;
            }
        }

        if (!$is_allowed) {
            throw new \Exception(__('This coupon is not valid for the selected shipping method.', 'unlock-addons-for-elementor'));
        }

        return true;
    }

    private function get_categories_for_select($category_ids = [])
    {
        $categories = [];
        if (!empty($category_ids) && is_array($category_ids)) {
            foreach ($category_ids as $category_id) {
                $term = get_term($category_id, 'product_cat');
                if ($term && !is_wp_error($term)) {
                    $categories[$category_id] = $term->name;
                }
            }
        }
        return $categories;
    }

    private function get_products_for_select($product_ids = [])
    {
        $products = [];
        if (!empty($product_ids) && is_array($product_ids)) {
            foreach ($product_ids as $product_id) {
                $product = wc_get_product($product_id);
                if ($product) {
                    $products[$product_id] = $product->get_formatted_name();
                }
            }
        }
        return $products;
    }

    private function validate_taxonomy_restrictions($coupon)
    {
        $allowed_tags = $coupon->get_meta('unlockafe_allowed_tags');
        $excluded_tags = $coupon->get_meta('unlockafe_excluded_tags');

        if (empty($allowed_tags) && empty($excluded_tags)) {
            return;
        }

        $cart_product_tags = [];
        foreach (WC()->cart->get_cart() as $cart_item) {
            $product_id = $cart_item['product_id'];
            $terms = get_the_terms($product_id, 'product_tag');
            if (is_array($terms)) {
                foreach ($terms as $term) {
                    $cart_product_tags[] = $term->term_id;
                }
            }
        }
        $cart_product_tags = array_unique($cart_product_tags);

        if (!empty($allowed_tags) && count(array_intersect($allowed_tags, $cart_product_tags)) == 0) {
            throw new \Exception(__('This coupon requires specific product tags to be in your cart.', 'unlock-addons-for-elementor'));
        }

        if (!empty($excluded_tags) && count(array_intersect($excluded_tags, $cart_product_tags)) > 0) {
            throw new \Exception(__('This coupon is not valid for some products in your cart.', 'unlock-addons-for-elementor'));
        }

        return true;
    }

    public function apply_bogo_deal($coupon_code)
    {
        $coupon = new \WC_Coupon($coupon_code);

        $buy_product_ids = $coupon->get_meta('unlockafe_bogo_buy_product_ids');
        $buy_category_ids = $coupon->get_meta('unlockafe_bogo_buy_category_ids');
        $buy_quantity = (int) $coupon->get_meta('unlockafe_bogo_buy_quantity') ?: 1;
        $get_product_ids = $coupon->get_meta('unlockafe_bogo_get_product_ids');
        $get_category_ids = $coupon->get_meta('unlockafe_bogo_get_category_ids');
        $get_quantity = (int) $coupon->get_meta('unlockafe_bogo_get_quantity') ?: 1;

        if ((empty($buy_product_ids) && empty($buy_category_ids)) || (empty($get_product_ids) && empty($get_category_ids))) {
            return;
        }

        $buy_items_in_cart = [];
        $get_items_in_cart = [];
        $cart_contents = WC()->cart->get_cart();

        // Separate buy and get items from the cart
        foreach ($cart_contents as $cart_item_key => $cart_item) {
            $product_id = $cart_item['product_id'];
            $variation_id = $cart_item['variation_id'];

            $is_buy_item = !empty($buy_product_ids) && (in_array($product_id, $buy_product_ids) || in_array($variation_id, $buy_product_ids));
            if (!$is_buy_item && !empty($buy_category_ids) && has_term($buy_category_ids, 'product_cat', $product_id)) {
                $is_buy_item = true;
            }
            if ($is_buy_item) {
                $buy_items_in_cart[$cart_item_key] = $cart_item;
            }

            $is_get_item = !empty($get_product_ids) && (in_array($product_id, $get_product_ids) || in_array($variation_id, $get_product_ids));
            if (!$is_get_item && !empty($get_category_ids) && has_term($get_category_ids, 'product_cat', $product_id)) {
                $is_get_item = true;
            }
            if ($is_get_item) {
                // Exclude items that are also buy items to avoid double-counting
                if (!$is_buy_item) {
                    $get_items_in_cart[$cart_item_key] = $cart_item;
                }
            }
        }

        $buy_items_quantity = array_sum(wp_list_pluck($buy_items_in_cart, 'quantity'));

        if ($buy_items_quantity < $buy_quantity) {
            return;
        }

        // Determine how many sets of BOGO deals can be applied
        $bogo_sets = floor($buy_items_quantity / $buy_quantity);
        $total_get_items_to_discount = $bogo_sets * $get_quantity;

        if (empty($get_items_in_cart) || $total_get_items_to_discount <= 0) {
            return;
        }

        // Sort get items by price if needed
        $get_selection = $coupon->get_meta('unlockafe_bogo_get_selection') ?: 'first';
        if ($get_selection === 'cheapest') {
            uasort($get_items_in_cart, function ($a, $b) {
                return $a['data']->get_price() <=> $b['data']->get_price();
            });
        }

        // Mark items for discount
        $discounted_count = 0;
        foreach ($get_items_in_cart as $cart_item_key => $cart_item) {
            if ($discounted_count >= $total_get_items_to_discount) {
                break;
            }
            WC()->cart->cart_contents[$cart_item_key]['unlockafe_bogo_discount_applied'] = true;
            $discounted_count++;
        }
    }

    public function apply_bogo_discount($discount, $price_to_discount, $cart_item, $single, $coupon)
    {
        $is_bogo_coupon = !empty($coupon->get_meta('unlockafe_bogo_buy_product_ids')) || !empty($coupon->get_meta('unlockafe_bogo_buy_category_ids'));

        if ($is_bogo_coupon && isset($cart_item['unlockafe_bogo_discount_applied']) && $cart_item['unlockafe_bogo_discount_applied'] === true) {
            $discount_type = $coupon->get_meta('unlockafe_bogo_discount_type') ?: 'free';
            $discount_amount = (float) $coupon->get_meta('unlockafe_bogo_discount_amount');
            $item_price = (float) $cart_item['data']->get_price();
            $calculated_discount = 0;

            switch ($discount_type) {
                case 'percentage':
                    $calculated_discount = ($item_price * $discount_amount) / 100;
                    break;
                case 'fixed':
                    $calculated_discount = $discount_amount;
                    break;
                case 'free':
                default:
                    $calculated_discount = $item_price;
                    break;
            }

            // Ensure discount does not exceed the item price
            $final_discount = min($calculated_discount, $item_price);

            // Unset the flag to prevent re-application on subsequent calculations
            unset(WC()->cart->cart_contents[$cart_item['key']]['unlockafe_bogo_discount_applied']);

            return $final_discount;
        }

        return $discount;
    }



    private function render_taxonomy_selection_field($id, $label, $taxonomy, $description)
    {
        $terms = get_terms(['taxonomy' => $taxonomy, 'hide_empty' => false]);
        $options = [];
        if (!is_wp_error($terms) && !empty($terms)) {
            foreach ($terms as $term) {
                $options[$term->term_id] = $term->name;
            }
        }

        woocommerce_wp_select(
            [
                'id'          => $id,
                'label'       => $label,
                'options'     => $options,
                'description' => $description,
                'desc_tip'    => true,
                'multiple'    => true,
                'class'       => 'wc-enhanced-select',
            ]
        );
    }

    private function get_payment_methods()
    {
        if (!function_exists('WC')) {
            return [];
        }
        $payment_gateways = WC()->payment_gateways->get_available_payment_gateways();
        $options = ['' => __('Any Payment Method', 'unlock-addons-for-elementor')];
        foreach ($payment_gateways as $gateway) {
            $options[$gateway->id] = $gateway->get_title();
        }
        return $options;
    }

    private function get_shipping_methods()
    {
        if (!function_exists('WC') || !WC()->shipping) {
            return [];
        }

        $shipping_methods = WC()->shipping->get_shipping_methods();
        $options = ['' => __('Any Shipping Method', 'unlock-addons-for-elementor')];
        foreach ($shipping_methods as $method) {
            $options[$method->id] = $method->get_method_title();
        }
        return $options;
    }

    private function get_user_roles()
    {
        global $wp_roles;
        $roles = $wp_roles->get_names();
        $options = ['' => __('Any User Role', 'unlock-addons-for-elementor')];
        foreach ($roles as $role_key => $role_name) {
            $options[$role_key] = $role_name;
        }
        return $options;
    }

    public function validate_coupon_stacking($valid, $coupon)
    {
        $cart = WC()->cart;
        if (!$cart) {
            return $valid;
        }

        $applied_coupons = $cart->get_applied_coupons();

        // If no other coupons are applied, this one is valid to try.
        if (empty($applied_coupons)) {
            return $valid;
        }

        // If this coupon is already applied, let it be.
        if (in_array($coupon->get_code(), $applied_coupons, true)) {
            return $valid;
        }

        $is_stackable = $coupon->get_meta('unlockafe_allow_multiple_coupons') === 'yes';

        // If the current coupon is stackable, it can be used with any other coupon.
        if ($is_stackable) {
            return $valid;
        }

        // If the current coupon is NOT stackable, check if any applied coupons are also not stackable.
        foreach ($applied_coupons as $applied_coupon_code) {
            $applied_coupon = new \WC_Coupon($applied_coupon_code);
            if ($applied_coupon->get_meta('unlockafe_allow_multiple_coupons') !== 'yes') {
                // Found a non-stackable coupon in the cart, so this new one can't be added.
                throw new \Exception(__('This coupon cannot be used with another non-stackable coupon.', 'unlock-addons-for-elementor'));
            }
        }

        return $valid;
    }
}