<?php
namespace Unlockafe_Addons\Classes;

/**
 * Coupon Categories Management
 * Handles custom coupon categorization system
 */
class Coupon_Categories {

    public function __construct() {
        add_action('add_meta_boxes', [$this, 'add_coupon_category_meta_box']);
        add_action('save_post', [$this, 'save_coupon_category_meta']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
    }

    /**
     * Add meta box for coupon categories
     */
    public function add_coupon_category_meta_box() {
        add_meta_box(
            'coupon_categories_meta',
            __('Coupon Categories', 'unlock-addons-for-elementor'),
            [$this, 'render_coupon_category_meta_box'],
            'shop_coupon',
            'side',
            'default'
        );
    }

    /**
     * Render the coupon category meta box
     */
    public function render_coupon_category_meta_box($post) {
        wp_nonce_field('coupon_categories_meta_nonce', 'coupon_categories_nonce');
        
        $selected_categories = get_post_meta($post->ID, 'coupon_categories', true);
        if (!is_array($selected_categories)) {
            $selected_categories = [];
        }

        $available_categories = $this->get_available_categories();
        ?>
        <div class="coupon-categories-wrapper">
            <p><strong><?php _e('Select categories for this coupon:', 'unlock-addons-for-elementor'); ?></strong></p>
            
            <?php foreach ($available_categories as $key => $label) : ?>
                <div style="margin: 8px 0;">
                    <label style="display: flex; align-items: center; cursor: pointer;">
                        <input type="checkbox" 
                               name="coupon_categories[]" 
                               value="<?php echo esc_attr($key); ?>"
                               style="margin-right: 8px;"
                               <?php checked(in_array($key, $selected_categories)); ?>>
                        <span><?php echo esc_html($label); ?></span>
                    </label>
                </div>
            <?php endforeach; ?>
            
            <div style="margin-top: 15px; padding: 10px; background: #f9f9f9; border-radius: 4px;">
                <p style="margin: 0; font-size: 12px; color: #666;">
                    <strong><?php _e('Note:', 'unlock-addons-for-elementor'); ?></strong>
                    <?php _e('These categories will be used to filter coupons in the Advance Coupons widget.', 'unlock-addons-for-elementor'); ?>
                </p>
            </div>
            
            <!-- Debug info -->
            <div style="margin-top: 10px; font-size: 11px; color: #999;">
                <strong>Debug:</strong> Currently selected: <?php echo esc_html(implode(', ', $selected_categories)); ?>
            </div>
        </div>
        
        <style>
        .coupon-categories-wrapper input[type="checkbox"] {
            margin-right: 8px !important;
            cursor: pointer;
        }
        .coupon-categories-wrapper label {
            cursor: pointer !important;
        }
        </style>
        
        <script>
        jQuery(document).ready(function($) {
            // Debug checkbox functionality
            $('.coupon-categories-wrapper input[type="checkbox"]').on('change', function() {
                console.log('Checkbox changed:', $(this).val(), $(this).is(':checked'));
            });
            
            // Ensure checkboxes are clickable
            $('.coupon-categories-wrapper label').on('click', function(e) {
                var checkbox = $(this).find('input[type="checkbox"]');
                if (e.target !== checkbox[0]) {
                    checkbox.prop('checked', !checkbox.prop('checked')).trigger('change');
                }
            });
        });
        </script>
        <?php
    }

    /**
     * Save coupon category meta data
     */
    public function save_coupon_category_meta($post_id) {
        // Check if nonce is valid
        if (!isset($_POST['coupon_categories_nonce']) || 
            !wp_verify_nonce($_POST['coupon_categories_nonce'], 'coupon_categories_meta_nonce')) {
            return;
        }

        // Check if user has permission to edit
        if (!current_user_can('edit_post', $post_id)) {
            return;
        }

        // Check if this is an autosave
        if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        // Check if this is a shop_coupon post type
        if (get_post_type($post_id) !== 'shop_coupon') {
            return;
        }

        // Save the categories
        $categories = isset($_POST['coupon_categories']) ? array_map('sanitize_text_field', $_POST['coupon_categories']) : [];
        update_post_meta($post_id, 'coupon_categories', $categories);
    }

    /**
     * Get available coupon categories
     */
    public function get_available_categories() {
        return [
            'seasonal' => __('Seasonal', 'unlock-addons-for-elementor'),
            'new-customer' => __('New Customer', 'unlock-addons-for-elementor'),
            'loyalty' => __('Loyalty Program', 'unlock-addons-for-elementor'),
            'flash-sale' => __('Flash Sale', 'unlock-addons-for-elementor'),
            'bulk-discount' => __('Bulk Discount', 'unlock-addons-for-elementor'),
            'free-shipping' => __('Free Shipping', 'unlock-addons-for-elementor'),
            'holiday' => __('Holiday Special', 'unlock-addons-for-elementor'),
            'clearance' => __('Clearance', 'unlock-addons-for-elementor'),
            'vip' => __('VIP Members', 'unlock-addons-for-elementor'),
            'birthday' => __('Birthday Special', 'unlock-addons-for-elementor'),
        ];
    }

    /**
     * Enqueue admin scripts
     */
    public function enqueue_admin_scripts($hook) {
        global $post_type;
        
        if ($hook === 'post.php' && $post_type === 'shop_coupon') {
            // Add any admin scripts if needed
        }
    }

    /**
     * Get coupons by categories (static method for easy access)
     */
    public static function get_coupons_by_categories($categories = []) {
        $args = [
            'posts_per_page' => -1,
            'post_type' => 'shop_coupon',
            'post_status' => 'publish',
        ];

        if (!empty($categories)) {
            $args['meta_query'] = [
                [
                    'key' => 'coupon_categories',
                    'value' => $categories,
                    'compare' => 'IN',
                ],
            ];
        }

        return get_posts($args);
    }
}
