<?php
/**
 * Coupon Post Type
 *
 * @author    Wpayme <hi@wpayme.com>
 * @copyright 2024-2025 Wpayme
 * @license   GPL-3.0-or-later
 * @package   Wpayme\WordPress\Pay\Forms
 */

namespace Wpayme\WordPress\Pay\Forms;

use WP_Post;

/**
 * Coupon Post Type
 *
 * @since 1.0.0
 */
class CouponPostType {
    /**
     * Post type.
     *
     * @var string
     */
    const POST_TYPE = 'wpayme_coupon';

    /**
     * Whether we're currently saving a coupon.
     *
     * @var bool
     */
    private static $saving_coupon = false;
    
    /**
     * Whether hooks have been registered.
     *
     * @var bool
     */
    private static $hooks_registered = false;
    
    /**
     * Instance of this class.
     *
     * @var self
     */
    private static $instance = null;

    /**
     * Get the singleton instance.
     *
     * @return self
     */
    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * Construct coupon post type object.
     */
    private function __construct() {
        // Only register hooks once
        if (self::$hooks_registered) {
            return;
        }
        
        // Register post type
        \add_action('init', array($this, 'register_post_type'), 0); // Highest priority
        
        // Add meta boxes
        \add_action('add_meta_boxes', array($this, 'add_meta_boxes'));
        
        // Save post meta data
        \add_action('save_post_' . self::POST_TYPE, array($this, 'save_post'));
        
        // Add custom columns to the post list
        \add_filter('manage_' . self::POST_TYPE . '_posts_columns', array($this, 'add_columns'));
        \add_action('manage_' . self::POST_TYPE . '_posts_custom_column', array($this, 'render_column'), 10, 2);
        
        // Add sortable columns
        \add_filter('manage_edit-' . self::POST_TYPE . '_sortable_columns', array($this, 'sortable_columns'));
        
        // Add custom row actions
        \add_filter('post_row_actions', array($this, 'row_actions'), 10, 2);

        // Handle custom sorting for columns
        \add_action('pre_get_posts', array($this, 'handle_custom_sorting'));

        // Enqueue admin styles and scripts
        \add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
        
        // Mark hooks as registered
        self::$hooks_registered = true;
    }

    /**
     * Register post type.
     */
    public function register_post_type() {
        $labels = array(
            'name'               => \__('Coupons', 'wpayme'),
            'singular_name'      => \__('Coupon', 'wpayme'),
            'menu_name'          => \__('Coupons', 'wpayme'),
            'add_new'            => \__('Add New', 'wpayme'),
            'add_new_item'       => \__('Add New Coupon', 'wpayme'),
            'edit_item'          => \__('Edit Coupon', 'wpayme'),
            'new_item'           => \__('New Coupon', 'wpayme'),
            'view_item'          => \__('View Coupon', 'wpayme'),
            'search_items'       => \__('Search Coupons', 'wpayme'),
            'not_found'          => \__('No coupons found', 'wpayme'),
            'not_found_in_trash' => \__('No coupons found in Trash', 'wpayme'),
        );

        $args = array(
            'labels'             => $labels,
            'public'             => true,  // This is important for visibility
            'publicly_queryable' => true,
            'show_ui'            => true,
            'show_in_menu'       => false, // Will be added as submenu by Plugin class
            'query_var'          => true,
            'rewrite'            => array('slug' => 'coupon'),
            'capability_type'    => 'post',
            'has_archive'        => false,
            'hierarchical'       => false,
            'menu_position'      => null,
            'map_meta_cap'       => true,
            'supports'           => array('title'),
            'show_in_admin_bar'  => true,
        );

        \register_post_type(self::POST_TYPE, $args);
    }

    /**
     * Add meta boxes.
     *
     * @param WP_Post $post The post object.
     */
    public function add_meta_boxes($post) {
        \add_meta_box(
            'wpayme_coupon_options',
            \__('Coupon Options', 'wpayme'),
            array($this, 'meta_box_coupon_options'),
            self::POST_TYPE,
            'normal',
            'high'
        );
    }

    /**
     * Display coupon options meta box.
     *
     * @param WP_Post $post The post object.
     */
    public function meta_box_coupon_options($post) {
        // Nonce field for validation
        \wp_nonce_field('wpayme_pay_save_coupon_options', 'wpayme_pay_nonce');

        // Get meta values
        $active = \get_post_meta($post->ID, '_wpayme_coupon_active', true) !== '' ? \get_post_meta($post->ID, '_wpayme_coupon_active', true) : '1';
        $code = \get_post_meta($post->ID, '_wpayme_coupon_code', true);
        $discount_type = \get_post_meta($post->ID, '_wpayme_coupon_discount_type', true) ?: 'percentage';
        $discount_amount = \get_post_meta($post->ID, '_wpayme_coupon_discount_amount', true);
        $redemption_limit = \get_post_meta($post->ID, '_wpayme_coupon_redemption_limit', true);
        $redemption_count = \get_post_meta($post->ID, '_wpayme_coupon_redemption_count', true) ?: '0';
        $usage_per_user = \get_post_meta($post->ID, '_wpayme_coupon_usage_per_user', true);
        $minimum_amount = \get_post_meta($post->ID, '_wpayme_coupon_minimum_amount', true);
        $start_date = \get_post_meta($post->ID, '_wpayme_coupon_start_date', true);
        $expiry_date = \get_post_meta($post->ID, '_wpayme_coupon_expiry_date', true);
        $availability = \get_post_meta($post->ID, '_wpayme_coupon_availability', true) ?: 'all';
        $specific_forms = \get_post_meta($post->ID, '_wpayme_coupon_specific_forms', true) ?: array();

        // Include the meta box view
        include \dirname(__DIR__) . '/views/meta-box-coupon-options.php';
    }

    /**
     * Save post meta data.
     *
     * @param int $post_id The post ID.
     */
    public function save_post($post_id) {
        // Prevent infinite loop
        if (self::$saving_coupon) {
            return;
        }

        // Check if our nonce is set.
        if (!\array_key_exists('wpayme_pay_nonce', $_POST)) {
            return;
        }

        $nonce = \sanitize_text_field(\wp_unslash($_POST['wpayme_pay_nonce']));

        // Verify that the nonce is valid.
        if (!\wp_verify_nonce($nonce, 'wpayme_pay_save_coupon_options')) {
            return;
        }

        // If this is an autosave, our form has not been submitted, so we don't want to do anything.
        if (\defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
            return;
        }

        // Check the user's permissions.
        if (!\current_user_can('edit_post', $post_id)) {
            return;
        }

        // Save coupon code
        if (isset($_POST['wpayme_coupon_code'])) {
            $code = \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_code']));
            $code = \strtoupper($code); // Convert to uppercase for consistency
            \update_post_meta($post_id, '_wpayme_coupon_code', $code);
            
            // Set the post title to the coupon code
            self::$saving_coupon = true;
            \wp_update_post(array(
                'ID' => $post_id,
                'post_title' => $code,
            ));
            self::$saving_coupon = false;
        }
        
        // Save active status
        $active = isset($_POST['wpayme_coupon_active']) ? '1' : '0';
        \update_post_meta($post_id, '_wpayme_coupon_active', $active);
        
        // Save discount type
        if (isset($_POST['wpayme_coupon_discount_type'])) {
            $discount_type = \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_discount_type']));
            \update_post_meta($post_id, '_wpayme_coupon_discount_type', $discount_type);
        }
        
        // Save discount amount
        if (isset($_POST['wpayme_coupon_discount_amount'])) {
            $discount_amount = (float) \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_discount_amount']));
            \update_post_meta($post_id, '_wpayme_coupon_discount_amount', $discount_amount);
        }
        
        // Save redemption limit
        if (isset($_POST['wpayme_coupon_redemption_limit'])) {
            $redemption_limit = \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_redemption_limit']));
            // Empty string is allowed (meaning unlimited)
            \update_post_meta($post_id, '_wpayme_coupon_redemption_limit', $redemption_limit);
        }
        
        // Save usage per user
        if (isset($_POST['wpayme_coupon_usage_per_user'])) {
            $usage_per_user = \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_usage_per_user']));
            \update_post_meta($post_id, '_wpayme_coupon_usage_per_user', $usage_per_user);
        }
        
        // Save minimum amount
        if (isset($_POST['wpayme_coupon_minimum_amount'])) {
            $minimum_amount = \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_minimum_amount']));
            \update_post_meta($post_id, '_wpayme_coupon_minimum_amount', $minimum_amount);
        }
        
        // Save start date
        if (isset($_POST['wpayme_coupon_start_date'])) {
            $start_date = \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_start_date']));
            \update_post_meta($post_id, '_wpayme_coupon_start_date', $start_date);
        }
        
        // Save expiry date
        if (isset($_POST['wpayme_coupon_expiry_date'])) {
            $expiry_date = \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_expiry_date']));
            \update_post_meta($post_id, '_wpayme_coupon_expiry_date', $expiry_date);
        }
        
        // Save availability
        if (isset($_POST['wpayme_coupon_availability'])) {
            $availability = \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_availability']));
            \update_post_meta($post_id, '_wpayme_coupon_availability', $availability);
        }
        
        // Save specific forms
        if (isset($_POST['wpayme_coupon_specific_forms']) && is_array($_POST['wpayme_coupon_specific_forms'])) {
            $specific_forms = array_map('intval', \wp_unslash($_POST['wpayme_coupon_specific_forms']));
            \update_post_meta($post_id, '_wpayme_coupon_specific_forms', $specific_forms);
        } else {
            // If no forms are selected, save empty array
            \update_post_meta($post_id, '_wpayme_coupon_specific_forms', array());
        }
    }

    /**
     * Add custom columns to the coupon list.
     *
     * @param array $columns The current columns.
     * @return array The modified columns.
     */
    public function add_columns($columns) {
        // Remove date column temporarily
        $date = isset($columns['date']) ? $columns['date'] : '';
        unset($columns['date']);
        
        // Only add our custom columns if they don't already exist
        if (!isset($columns['code'])) {
            $columns['code'] = \__('Coupon Code', 'wpayme');
        }
        
        if (!isset($columns['discount'])) {
            $columns['discount'] = \__('Discount', 'wpayme');
        }
        
        if (!isset($columns['usage'])) {
            $columns['usage'] = \__('Usage', 'wpayme');
        }
        
        if (!isset($columns['restrictions'])) {
            $columns['restrictions'] = \__('Restrictions', 'wpayme');
        }
        
        if (!isset($columns['status'])) {
            $columns['status'] = \__('Status', 'wpayme');
        }
        
        // Re-add date column
        if ($date) {
            $columns['date'] = $date;
        }
        
        return $columns;
    }

    /**
     * Render the data for custom columns.
     *
     * @param string $column The column name.
     * @param int $post_id The post ID.
     */
    public function render_column($column, $post_id) {
        switch ($column) {
            case 'code':
                $code = \get_post_meta($post_id, '_wpayme_coupon_code', true);
                echo \esc_html($code);
                break;
                
            case 'discount':
                $discount_type = \get_post_meta($post_id, '_wpayme_coupon_discount_type', true);
                $discount_amount = (float) \get_post_meta($post_id, '_wpayme_coupon_discount_amount', true);
                
                if ($discount_type === 'percentage') {
                    echo \esc_html($discount_amount) . '%';
                } else {
                    echo '€' . \esc_html(number_format($discount_amount, 2));
                }
                break;
                
            case 'usage':
                $usage_count = (int) \get_post_meta($post_id, '_wpayme_coupon_usage_count', true);
                $redemption_limit = \get_post_meta($post_id, '_wpayme_coupon_redemption_limit', true);
                
                if (!empty($redemption_limit)) {
                    echo \esc_html($usage_count) . ' / ' . \esc_html($redemption_limit);
                } else {
                    echo \esc_html($usage_count) . ' / ' . \esc_html__('Unlimited', 'wpayme');
                }
                break;
                
            case 'restrictions':
                $restrictions = array();
                
                // Check expiry date
                $expiry_date = \get_post_meta($post_id, '_wpayme_coupon_expiry_date', true);
                if (!empty($expiry_date)) {
                    $restrictions[] = \esc_html__('Expires', 'wpayme') . ': ' . \esc_html($expiry_date);
                }
                
                // Check minimum amount
                $minimum_amount = \get_post_meta($post_id, '_wpayme_coupon_minimum_amount', true);
                if (!empty($minimum_amount)) {
                    $restrictions[] = \esc_html__('Min', 'wpayme') . ': €' . \esc_html(number_format($minimum_amount, 2));
                }
                
                // Check form restrictions
                $availability = \get_post_meta($post_id, '_wpayme_coupon_availability', true);
                if ($availability === 'specific') {
                    $specific_forms = \get_post_meta($post_id, '_wpayme_coupon_specific_forms', true);
                    $count = is_array($specific_forms) ? count($specific_forms) : 0;
                    $restrictions[] = $count . ' ' . \esc_html__('form(s)', 'wpayme');
                }
                
                if (empty($restrictions)) {
                    echo '—';
                } else {
                    echo \esc_html(implode(', ', $restrictions));
                }
                break;
                
            case 'status':
                $active = \get_post_meta($post_id, '_wpayme_coupon_active', true);
                $current_date = current_time('Y-m-d');
                $status = '';
                
                // Check start date
                $start_date = \get_post_meta($post_id, '_wpayme_coupon_start_date', true);
                if (!empty($start_date) && $current_date < $start_date) {
                    echo '<span class="coupon-status pending">' . \esc_html__('Pending', 'wpayme') . '</span>';
                    break;
                }
                
                // Check expiry date
                $expiry_date = \get_post_meta($post_id, '_wpayme_coupon_expiry_date', true);
                if (!empty($expiry_date) && $current_date > $expiry_date) {
                    echo '<span class="coupon-status expired">' . \esc_html__('Expired', 'wpayme') . '</span>';
                    break;
                }
                
                // Check usage limit
                $redemption_limit = \get_post_meta($post_id, '_wpayme_coupon_redemption_limit', true);
                if (!empty($redemption_limit)) {
                    $usage_count = (int) \get_post_meta($post_id, '_wpayme_coupon_usage_count', true);
                    if ($usage_count >= (int) $redemption_limit) {
                        echo '<span class="coupon-status used">' . \esc_html__('Used up', 'wpayme') . '</span>';
                        break;
                    }
                }
                
                if ($active === '1') {
                    echo '<span class="coupon-status active">' . \esc_html__('Active', 'wpayme') . '</span>';
                } else {
                    echo '<span class="coupon-status inactive">' . \esc_html__('Inactive', 'wpayme') . '</span>';
                }
                break;
                
            default:
                break;
        }
    }

    /**
     * Make columns sortable.
     *
     * @param array $columns The sortable columns.
     * @return array The modified sortable columns.
     */
    public function sortable_columns($columns) {
        // Only add our custom sortable columns if they don't already exist
        if (!isset($columns['code'])) {
            $columns['code'] = 'code';
        }
        
        if (!isset($columns['discount'])) {
            $columns['discount'] = 'discount';
        }
        
        if (!isset($columns['usage'])) {
            $columns['usage'] = 'usage';
        }
        
        if (!isset($columns['status'])) {
            $columns['status'] = 'status';
        }
        
        return $columns;
    }

    /**
     * Customize row actions.
     *
     * @param array $actions The current row actions.
     * @param WP_Post $post The post object.
     * @return array The modified row actions.
     */
    public function row_actions($actions, $post) {
        if ($post->post_type !== self::POST_TYPE) {
            return $actions;
        }

        // Keep only the edit, trash, and view actions
        $allowed_actions = array('edit', 'trash');
        foreach ($actions as $key => $action) {
            if (!in_array($key, $allowed_actions)) {
                unset($actions[$key]);
            }
        }

        return $actions;
    }

    /**
     * Validate a coupon code.
     *
     * @param string $code Coupon code.
     * @param int|null $form_id Optional form ID to validate against.
     * @param string|null $user_email Optional user email for per-user limits.
     * @param float|null $amount Optional purchase amount for minimum amount validation.
     * @return array|false Coupon data if valid, false otherwise.
     */
    public static function validate_coupon($code, $form_id = null, $user_email = null, $amount = null) {
        if (empty($code)) {
            return false;
        }
        
        $code = strtoupper($code);
        
        // Find coupon by code
        $args = array(
            'post_type' => self::POST_TYPE,
            'post_status' => 'publish',
            'posts_per_page' => 1,
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
            'meta_query' => array(
                array(
                    'key' => '_wpayme_coupon_code',
                    'value' => $code,
                    'compare' => '='
                )
            )
        );
        
        $coupons = get_posts($args);
        
        if (empty($coupons)) {
            return false;
        }
        
        $coupon_id = $coupons[0]->ID;
        
        // Check if coupon is active
        $active = get_post_meta($coupon_id, '_wpayme_coupon_active', true);
        if ($active !== '1') {
            return false;
        }
        
        // Check date restrictions
        $current_date = current_time('Y-m-d');
        
        // Check start date
        $start_date = get_post_meta($coupon_id, '_wpayme_coupon_start_date', true);
        if (!empty($start_date) && $current_date < $start_date) {
            return false; // Coupon not yet active
        }
        
        // Check expiry date
        $expiry_date = get_post_meta($coupon_id, '_wpayme_coupon_expiry_date', true);
        if (!empty($expiry_date) && $current_date > $expiry_date) {
            return false; // Coupon expired
        }
        
        // Check usage limits
        $redemption_limit = get_post_meta($coupon_id, '_wpayme_coupon_redemption_limit', true);
        if (!empty($redemption_limit)) {
            $usage_count = (int) get_post_meta($coupon_id, '_wpayme_coupon_usage_count', true);
            if ($usage_count >= (int) $redemption_limit) {
                return false; // Coupon usage limit reached
            }
        }
        
        // Check per-user limits if email provided
        if (!empty($user_email)) {
            $usage_per_user = get_post_meta($coupon_id, '_wpayme_coupon_usage_per_user', true);
            if (!empty($usage_per_user)) {
                // Get user usage from user meta if WP user, or from coupon meta
                $user = get_user_by('email', $user_email);
                
                if ($user) {
                    // Registered user
                    $user_id = $user->ID;
                    $user_usage = (int) get_user_meta($user_id, '_wpayme_coupon_usage_' . $coupon_id, true);
                } else {
                    // Guest user - track by email in coupon meta
                    $user_usages = get_post_meta($coupon_id, '_wpayme_coupon_user_usages', true);
                    $user_usages = is_array($user_usages) ? $user_usages : array();
                    $user_usage = isset($user_usages[$user_email]) ? (int) $user_usages[$user_email] : 0;
                }
                
                if ($user_usage >= (int) $usage_per_user) {
                    return false; // User has reached their usage limit
                }
            }
        }
        
        // Check minimum purchase amount if provided
        if ($amount !== null) {
            $minimum_amount = (float) get_post_meta($coupon_id, '_wpayme_coupon_minimum_amount', true);
            if (!empty($minimum_amount) && $amount < $minimum_amount) {
                return false; // Purchase amount too low
            }
        }
        
        // Check form restrictions if form_id is provided
        if ($form_id) {
            $availability = get_post_meta($coupon_id, '_wpayme_coupon_availability', true);
            if ($availability === 'specific') {
                $specific_forms = get_post_meta($coupon_id, '_wpayme_coupon_specific_forms', true);
                $specific_forms = is_array($specific_forms) ? $specific_forms : array();
                
                // If no forms are selected but "specific" is chosen, the coupon is not valid for any form
                if (empty($specific_forms)) {
                    return false;
                }
                
                if (!in_array($form_id, $specific_forms)) {
                    return false; // Coupon not valid for this form
                }
            }
        }
        
        // Get discount information
        $discount_type = get_post_meta($coupon_id, '_wpayme_coupon_discount_type', true) ?: 'percentage';
        $discount_amount = (float) get_post_meta($coupon_id, '_wpayme_coupon_discount_amount', true) ?: 10;
        
        // Return coupon data
        return array(
            'id' => $coupon_id,
            'code' => $code,
            'discount_type' => $discount_type,
            'discount_amount' => $discount_amount,
        );
    }

    /**
     * Apply discount to amount.
     *
     * @param array $coupon Coupon data from validate_coupon.
     * @param float $amount Amount to apply discount to.
     * @return float Discounted amount.
     */
    public static function apply_discount($coupon, $amount) {
        if (!is_array($coupon) || !isset($coupon['discount_type']) || !isset($coupon['discount_amount'])) {
            return $amount;
        }
        
        $discount_type = $coupon['discount_type'];
        $discount_amount = (float) $coupon['discount_amount'];
        
        if ($discount_type === 'percentage') {
            // Calculate percentage discount
            $discount = $amount * ($discount_amount / 100);
            $discounted_amount = $amount - $discount;
        } else {
            // Fixed amount discount
            $discounted_amount = $amount - $discount_amount;
        }
        
        // Don't allow negative amounts
        return max(0, $discounted_amount);
    }

    /**
     * Increment the usage count for a coupon.
     *
     * @param int $coupon_id The coupon ID.
     * @param string|null $user_email Optional. The user's email address for per-user tracking.
     */
    public static function increment_usage($coupon_id, $user_email = null) {
        if (empty($coupon_id)) {
            return;
        }
        
        // Increment global usage count
        $usage_count = (int) \get_post_meta($coupon_id, '_wpayme_coupon_usage_count', true);
        $usage_count++;
        \update_post_meta($coupon_id, '_wpayme_coupon_usage_count', $usage_count);
        
        // Track per-user usage if email is provided
        if (!empty($user_email)) {
            $user = \get_user_by('email', $user_email);
            
            if ($user) {
                // Registered user - store in user meta
                $user_id = $user->ID;
                $user_usage = (int) \get_user_meta($user_id, '_wpayme_coupon_usage_' . $coupon_id, true);
                $user_usage++;
                \update_user_meta($user_id, '_wpayme_coupon_usage_' . $coupon_id, $user_usage);
            } else {
                // Guest user - store in coupon meta
                $user_usages = \get_post_meta($coupon_id, '_wpayme_coupon_user_usages', true);
                $user_usages = is_array($user_usages) ? $user_usages : array();
                
                if (!isset($user_usages[$user_email])) {
                    $user_usages[$user_email] = 0;
                }
                
                $user_usages[$user_email]++;
                \update_post_meta($coupon_id, '_wpayme_coupon_user_usages', $user_usages);
            }
        }
    }

    /**
     * Process form submission.
     */
    public static function process_form_submission() {
        if (!isset($_POST['action']) || $_POST['action'] !== 'save_coupon') {
            return;
        }
        
        // Verify nonce
        if (!isset($_POST['wpayme_coupon_nonce']) || !\wp_verify_nonce(\sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_nonce'])), 'save_coupon')) {
            \wp_die(\esc_html__('Security check failed. Please try again.', 'wpayme'));
        }
        
        // Check permissions
        if (!\current_user_can('manage_options')) {
            \wp_die(\esc_html__('You do not have permission to do this.', 'wpayme'));
        }
        
        $coupon_id = isset($_POST['coupon_id']) ? \intval($_POST['coupon_id']) : 0;
        
        // Get coupon code
        $code = isset($_POST['wpayme_coupon_code']) ? \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_code'])) : '';
        $code = \strtoupper($code); // Convert to uppercase for consistency
        
        // Validate required fields
        if (empty($code)) {
            \wp_die(\esc_html__('Coupon code is required.', 'wpayme'));
        }
        
        // Get other field values
        $active = isset($_POST['wpayme_coupon_active']) ? '1' : '0';
        $discount_type = isset($_POST['wpayme_coupon_discount_type']) ? \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_discount_type'])) : 'percentage';
        $discount_amount = isset($_POST['wpayme_coupon_discount_amount']) ? (float) \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_discount_amount'])) : 0;
        $redemption_limit = isset($_POST['wpayme_coupon_redemption_limit']) ? \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_redemption_limit'])) : '';
        $usage_per_user = isset($_POST['wpayme_coupon_usage_per_user']) ? \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_usage_per_user'])) : '';
        $minimum_amount = isset($_POST['wpayme_coupon_minimum_amount']) ? \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_minimum_amount'])) : '';
        $start_date = isset($_POST['wpayme_coupon_start_date']) ? \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_start_date'])) : '';
        $expiry_date = isset($_POST['wpayme_coupon_expiry_date']) ? \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_expiry_date'])) : '';
        $availability = isset($_POST['wpayme_coupon_availability']) ? \sanitize_text_field(\wp_unslash($_POST['wpayme_coupon_availability'])) : 'all';
        
        // Get specific forms if in specific mode
        $specific_forms = array();
        if ($availability === 'specific' && isset($_POST['wpayme_coupon_specific_forms']) && is_array($_POST['wpayme_coupon_specific_forms'])) {
            $specific_forms = array_map('intval', \wp_unslash($_POST['wpayme_coupon_specific_forms']));
        }
        
        // Prevent infinite loop
        self::$saving_coupon = true;
        
        // Create or update post
        if ($coupon_id > 0) {
            // Update existing coupon
            $coupon = array(
                'ID' => $coupon_id,
                'post_title' => $code,
                'post_status' => 'publish',
                'post_type' => self::POST_TYPE,
            );
            $result = \wp_update_post($coupon);
        } else {
            // Create new coupon
            $coupon = array(
                'post_title' => $code,
                'post_status' => 'publish',
                'post_type' => self::POST_TYPE,
            );
            $result = \wp_insert_post($coupon);
            $coupon_id = $result;
        }
        
        self::$saving_coupon = false;
        
        if (\is_wp_error($result)) {
            \wp_die(esc_html($result->get_error_message()));
        }
        
        // Save meta data
        \update_post_meta($coupon_id, '_wpayme_coupon_code', $code);
        \update_post_meta($coupon_id, '_wpayme_coupon_active', $active);
        \update_post_meta($coupon_id, '_wpayme_coupon_discount_type', $discount_type);
        \update_post_meta($coupon_id, '_wpayme_coupon_discount_amount', $discount_amount);
        \update_post_meta($coupon_id, '_wpayme_coupon_redemption_limit', $redemption_limit);
        \update_post_meta($coupon_id, '_wpayme_coupon_usage_per_user', $usage_per_user);
        \update_post_meta($coupon_id, '_wpayme_coupon_minimum_amount', $minimum_amount);
        \update_post_meta($coupon_id, '_wpayme_coupon_start_date', $start_date);
        \update_post_meta($coupon_id, '_wpayme_coupon_expiry_date', $expiry_date);
        \update_post_meta($coupon_id, '_wpayme_coupon_availability', $availability);
        \update_post_meta($coupon_id, '_wpayme_coupon_specific_forms', $specific_forms);
        
        // Redirect back to the coupon list
        \wp_safe_redirect(\admin_url('edit.php?post_type=' . self::POST_TYPE . '&message=success'));
        exit;
    }
    
    /**
     * Process coupon deletion.
     */
    public static function process_deletion() {
        if (!isset($_GET['action']) || $_GET['action'] !== 'delete' || !isset($_GET['coupon_id'])) {
            return;
        }
        
        $coupon_id = \intval($_GET['coupon_id']);
        
        // Verify nonce
        if (!isset($_GET['_wpnonce']) || !\wp_verify_nonce(\sanitize_text_field(\wp_unslash($_GET['_wpnonce'])), 'delete-coupon_' . $coupon_id)) {
            \wp_die(\esc_html__('Security check failed. Please try again.', 'wpayme'));
        }
        
        // Check permissions
        if (!\current_user_can('manage_options')) {
            \wp_die(\esc_html__('You do not have permission to do this.', 'wpayme'));
        }
        
        // Check if coupon exists
        $coupon = \get_post($coupon_id);
        if (!$coupon || $coupon->post_type !== self::POST_TYPE) {
            \wp_die(\esc_html__('Coupon not found.', 'wpayme'));
        }
        
        // Delete the coupon
        $result = \wp_delete_post($coupon_id, true);
        
        if (!$result) {
            \wp_die(\esc_html__('Failed to delete coupon.', 'wpayme'));
        }
        
        // Redirect back to the coupon list
        \wp_safe_redirect(\admin_url('edit.php?post_type=' . self::POST_TYPE . '&message=deleted'));
        exit;
    }

    /**
     * Handle custom sorting for columns.
     *
     * @param \WP_Query $query The query object.
     */
    public function handle_custom_sorting($query) {
        if (!is_admin() || !$query->is_main_query() || $query->get('post_type') !== self::POST_TYPE) {
            return;
        }
        
        $orderby = $query->get('orderby');
        
        switch ($orderby) {
            case 'code':
                $query->set('meta_key', '_wpayme_coupon_code');
                $query->set('orderby', 'meta_value');
                break;
                
            case 'discount':
                $query->set('meta_key', '_wpayme_coupon_discount_amount');
                $query->set('orderby', 'meta_value_num');
                break;
                
            case 'usage':
                $query->set('meta_key', '_wpayme_coupon_usage_count');
                $query->set('orderby', 'meta_value_num');
                break;
                
            case 'status':
                $query->set('meta_key', '_wpayme_coupon_active');
                $query->set('orderby', 'meta_value');
                break;
        }
    }

    /**
     * Enqueue admin scripts and styles.
     */
    public function admin_enqueue_scripts() {
        $screen = \get_current_screen();
        
        // Only load on coupon edit screens
        if ($screen && $screen->post_type === self::POST_TYPE) {
            // Ensure jQuery UI CSS is loaded for datepicker
            // \wp_enqueue_style('jquery-ui', \plugins_url('/assets/libs/jquery-ui/jquery-ui.css', \dirname(__DIR__) . '/wp-wpayme-pay-forms.php'));
            
            // Enqueue datepicker
            \wp_enqueue_script('jquery-ui-datepicker');
            
            // Load Select2 for dropdowns
            \wp_enqueue_style('wpayme-select2', \plugins_url('/assets/libs/select2/select2.min.css', \dirname(__DIR__) . '/wp-wpayme-pay-forms.php'), [], '4.1.0-rc.0');
            \wp_enqueue_script('wpayme-select2', \plugins_url('/assets/libs/select2/select2.min.js', \dirname(__DIR__) . '/wp-wpayme-pay-forms.php'), ['jquery'], '4.1.0-rc.0', true);
            
            // Load admin styles and scripts
            \wp_enqueue_style('wpayme-pay-admin', \plugins_url('/assets/css/admin-style.css', \dirname(__FILE__)), [], '1.0.0');
            \wp_enqueue_script('wpayme-coupon-admin', \plugins_url('/assets/js/coupon-admin.js', \dirname(__FILE__)), ['jquery', 'jquery-ui-datepicker', 'wpayme-select2'], '1.0.0', true);
            
            // Add CSS for coupon status indicators
            $css = '
            .coupon-status {
                display: inline-block;
                padding: 4px 8px;
                border-radius: 12px;
                font-size: 12px;
                font-weight: 500;
                line-height: 1;
                text-align: center;
            }
            
            .coupon-status.active {
                background-color: #dff0d8;
                color: #3c763d;
            }
            
            .coupon-status.inactive {
                background-color: #f2dede;
                color: #a94442;
            }
            
            .coupon-status.pending {
                background-color: #fcf8e3;
                color: #8a6d3b;
            }
            
            .coupon-status.expired {
                background-color: #f2dede;
                color: #a94442;
            }
            
            .coupon-status.used {
                background-color: #d9edf7;
                color: #31708f;
            }';
            \wp_add_inline_style('wpayme-pay-admin', $css);

            // Localize script with admin variables
            \wp_localize_script('wpayme-coupon-admin', 'wpayme_admin_vars', [
                'currency_symbol' => '€',
                'ajax_url' => \admin_url('admin-ajax.php'),
                'nonce' => \wp_create_nonce('wpayme_admin_nonce')
            ]);
        }
    }
} 