<?php

/**
 * Subscriptions Core Initialization
 *
 * @package ArraySubs\Features\Subscriptions\Services
 */

namespace ArraySubs\Features\Subscriptions\Services;

defined('ABSPATH') || exit;

/**
 * Initialize subscription Custom Post Type and core infrastructure
 */
class SubscriptionCPT
{
    /**
     * Enable auto-loading
     *
     * @var bool
     */
    public static $loadable = true;

    /**
     * Constructor
     */
    public function __construct()
    {
        add_action('init', [$this, 'registerSubscriptionCPT'], 10);
        add_action('init', [$this, 'registerSubscriptionStatuses'], 10);
        add_action('init', [$this, 'registerMetaFields'], 10);

        // Add admin list filters for REST API
        add_filter('rest_arraysubs_data_query', [$this, 'handleCustomerSearchQuery'], 10, 2);
        add_filter('rest_arraysubs_data_query', [$this, 'handleGatewayQuery'], 10, 2);
        add_filter('rest_arraysubs_data_collection_params', [$this, 'addAdminListCollectionParams']);
    }

    /**
     * Register the Subscription Custom Post Type
     */
    public function registerSubscriptionCPT(): void
    {
        $labels = [
            'name'                  => __('Subscriptions', 'arraysubs'),
            'singular_name'         => __('Subscription', 'arraysubs'),
            'menu_name'             => __('Subscriptions', 'arraysubs'),
            'name_admin_bar'        => __('Subscription', 'arraysubs'),
            'add_new'               => __('Add New', 'arraysubs'),
            'add_new_item'          => __('Add New Subscription', 'arraysubs'),
            'new_item'              => __('New Subscription', 'arraysubs'),
            'edit_item'             => __('Edit Subscription', 'arraysubs'),
            'view_item'             => __('View Subscription', 'arraysubs'),
            'all_items'             => __('All Subscriptions', 'arraysubs'),
            'search_items'          => __('Search Subscriptions', 'arraysubs'),
            'parent_item_colon'     => __('Parent Subscriptions:', 'arraysubs'),
            'not_found'             => __('No subscriptions found.', 'arraysubs'),
            'not_found_in_trash'    => __('No subscriptions found in Trash.', 'arraysubs'),
            'filter_items_list'     => __('Filter subscriptions list', 'arraysubs'),
            'items_list_navigation' => __('Subscriptions list navigation', 'arraysubs'),
            'items_list'            => __('Subscriptions list', 'arraysubs'),
        ];

        $args = [
            'labels'              => $labels,
            'description'         => __('Customer subscription orders', 'arraysubs'),
            'public'              => false,
            'publicly_queryable'  => false,
            'show_ui'             => false,
            'show_in_menu'        => false, // We'll use custom admin UI
            'query_var'           => true,
            'rewrite'             => ['slug' => 'subscription'],
            'capability_type'     => 'post',
            'capabilities'        => [
                'create_posts' => 'manage_options', // Only admins can create
            ],
            'map_meta_cap'        => true,
            'has_archive'         => false,
            'hierarchical'        => false,
            'menu_position'       => 56, // After WooCommerce
            'show_in_rest'        => true, // Enable REST API
            'rest_base'           => 'arraysubs_data',
            'rest_controller_class' => 'WP_REST_Posts_Controller',
            'supports'            => ['title', 'custom-fields'],
        ];

        register_post_type('arraysubs_data', $args);
    }

    /**
     * Register custom subscription statuses
     */
    public function registerSubscriptionStatuses(): void
    {
        $statuses = [
            'arraysubs-pending' => [
                'label'                     => _x('Pending', 'Subscription status', 'arraysubs'),
                'public'                    => false,
                'exclude_from_search'       => false,
                'show_in_admin_all_list'    => true,
                'show_in_admin_status_list' => true,
                /* translators: %s: count of subscriptions */
                'label_count'               => _n_noop('Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>', 'arraysubs'),
            ],
            'arraysubs-active' => [
                'label'                     => _x('Active', 'Subscription status', 'arraysubs'),
                'public'                    => false,
                'exclude_from_search'       => false,
                'show_in_admin_all_list'    => true,
                'show_in_admin_status_list' => true,
                /* translators: %s: count of subscriptions */
                'label_count'               => _n_noop('Active <span class="count">(%s)</span>', 'Active <span class="count">(%s)</span>', 'arraysubs'),
            ],
            'arraysubs-on-hold' => [
                'label'                     => _x('On Hold', 'Subscription status', 'arraysubs'),
                'public'                    => false,
                'exclude_from_search'       => false,
                'show_in_admin_all_list'    => true,
                'show_in_admin_status_list' => true,
                /* translators: %s: count of subscriptions */
                'label_count'               => _n_noop('On Hold <span class="count">(%s)</span>', 'On Hold <span class="count">(%s)</span>', 'arraysubs'),
            ],
            'arraysubs-cancelled' => [
                'label'                     => _x('Cancelled', 'Subscription status', 'arraysubs'),
                'public'                    => false,
                'exclude_from_search'       => false,
                'show_in_admin_all_list'    => true,
                'show_in_admin_status_list' => true,
                /* translators: %s: count of subscriptions */
                'label_count'               => _n_noop('Cancelled <span class="count">(%s)</span>', 'Cancelled <span class="count">(%s)</span>', 'arraysubs'),
            ],
            'arraysubs-expired' => [
                'label'                     => _x('Expired', 'Subscription status', 'arraysubs'),
                'public'                    => false,
                'exclude_from_search'       => false,
                'show_in_admin_all_list'    => true,
                'show_in_admin_status_list' => true,
                /* translators: %s: count of subscriptions */
                'label_count'               => _n_noop('Expired <span class="count">(%s)</span>', 'Expired <span class="count">(%s)</span>', 'arraysubs'),
            ],
            'arraysubs-trial' => [
                'label'                     => _x('Trial', 'Subscription status', 'arraysubs'),
                'public'                    => false,
                'exclude_from_search'       => false,
                'show_in_admin_all_list'    => true,
                'show_in_admin_status_list' => true,
                /* translators: %s: count of subscriptions */
                'label_count'               => _n_noop('Trial <span class="count">(%s)</span>', 'Trial <span class="count">(%s)</span>', 'arraysubs'),
            ],
        ];

        foreach ($statuses as $status => $args) {
            register_post_status($status, $args);
        }
    }

    /**
     * Register subscription meta fields
     */
    public function registerMetaFields(): void
    {
        $post_type = 'arraysubs_data';

        // Core billing fields
        register_post_meta($post_type, '_billing_period', [
            'type'              => 'string',
            'description'       => 'Billing period (day, week, month, year)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 'month',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_billing_interval', [
            'type'              => 'integer',
            'description'       => 'Billing interval (every X periods)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 1,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_subscription_length', [
            'type'              => 'integer',
            'description'       => 'Subscription length (0 = unlimited)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // Trial fields
        register_post_meta($post_type, '_trial_length', [
            'type'              => 'integer',
            'description'       => 'Trial length (0 = no trial)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_trial_period', [
            'type'              => 'string',
            'description'       => 'Trial period (day, week, month, year)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 'day',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // Date fields
        register_post_meta($post_type, '_start_date', [
            'type'              => 'string',
            'description'       => 'Subscription start date (Y-m-d H:i:s)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_next_payment_date', [
            'type'              => 'string',
            'description'       => 'Next payment date (Y-m-d H:i:s)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_end_date', [
            'type'              => 'string',
            'description'       => 'Subscription end date (Y-m-d H:i:s)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_last_payment_date', [
            'type'              => 'string',
            'description'       => 'Last payment date (Y-m-d H:i:s)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // Customer & Payment
        register_post_meta($post_type, '_customer_id', [
            'type'              => 'integer',
            'description'       => 'WordPress user ID',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_customer_email', [
            'type'              => 'string',
            'description'       => 'Customer email address',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_email',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_payment_method', [
            'type'              => 'string',
            'description'       => 'Payment gateway ID',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_payment_method_title', [
            'type'              => 'string',
            'description'       => 'Payment method display name',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_payment_method_token', [
            'type'              => 'string',
            'description'       => 'Payment method token (encrypted)',
            'single'            => true,
            'show_in_rest'      => false, // Never expose token via REST
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('manage_options'),
        ]);

        // Pricing
        register_post_meta($post_type, '_subscription_price', [
            'type'              => 'number',
            'description'       => 'Recurring amount',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => floatval($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_recurring_amount', [
            'type'              => 'number',
            'description'       => 'Renewal price',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => floatval($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_signup_fee', [
            'type'              => 'number',
            'description'       => 'One-time signup fee',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => floatval($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_currency', [
            'type'              => 'string',
            'description'       => 'Currency code (USD, EUR, etc.)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 'USD',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // Trial fields
        register_post_meta($post_type, '_trial_length', [
            'type'              => 'integer',
            'description'       => 'Trial length (days)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_trial_period', [
            'type'              => 'string',
            'description'       => 'Trial period (day, week, month)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 'day',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_trial_end_date', [
            'type'              => 'string',
            'description'       => 'Trial end date (Y-m-d H:i:s)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // Product info
        register_post_meta($post_type, '_product_id', [
            'type'              => 'integer',
            'description'       => 'WooCommerce product ID',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_variation_id', [
            'type'              => 'integer',
            'description'       => 'Variation ID if applicable',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_quantity', [
            'type'              => 'integer',
            'description'       => 'Subscription quantity',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 1,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // Related orders
        register_post_meta($post_type, '_parent_order_id', [
            'type'              => 'integer',
            'description'       => 'Initial order ID',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_order_ids', [
            'type'              => 'string',
            'description'       => 'JSON array of all related order IDs',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '[]',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // Flags
        register_post_meta($post_type, '_requires_manual_renewal', [
            'type'              => 'boolean',
            'description'       => 'Requires manual renewal',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => false,
            'sanitize_callback' => fn($value) => (bool) $value,
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // Addresses (stored as JSON)
        register_post_meta($post_type, '_billing_address', [
            'type'              => 'string',
            'description'       => 'Billing address (JSON)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '{}',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_shipping_address', [
            'type'              => 'string',
            'description'       => 'Shipping address (JSON)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '{}',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // Invoice email (can differ from customer email)
        register_post_meta($post_type, '_invoice_email', [
            'type'              => 'string',
            'description'       => 'Invoice email address',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_email',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // Admin remarks/notes
        register_post_meta($post_type, '_admin_remarks', [
            'type'              => 'string',
            'description'       => 'Admin internal notes',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'wp_kses_post',
            'auth_callback'     => fn() => current_user_can('manage_options'), // Admin only
        ]);

        // Different renewal price fields
        register_post_meta($post_type, '_different_renewal_price', [
            'type'              => 'number',
            'description'       => 'Different renewal price after threshold',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => floatval($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_different_renewal_price_after', [
            'type'              => 'integer',
            'description'       => 'Apply different renewal price after N periods',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 1,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_completed_payments', [
            'type'              => 'integer',
            'description'       => 'Number of completed billing cycles',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // Shipping meta fields (for physical products only)
        register_post_meta($post_type, '_arraysubs_needs_shipping', [
            'type'              => 'string',
            'description'       => 'Whether subscription needs shipping (yes/no)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_arraysubs_shipping_type', [
            'type'              => 'string',
            'description'       => 'Shipping type: one-time or recurring',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 'recurring',
            'sanitize_callback' => fn($value) => in_array($value, ['one-time', 'recurring'], true) ? $value : 'recurring',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_arraysubs_shipping_method_id', [
            'type'              => 'string',
            'description'       => 'Shipping method ID from WooCommerce',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_arraysubs_shipping_method_title', [
            'type'              => 'string',
            'description'       => 'Shipping method display title',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_arraysubs_shipping_total', [
            'type'              => 'number',
            'description'       => 'Initial order shipping total',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => floatval($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_arraysubs_renewal_shipping_total', [
            'type'              => 'number',
            'description'       => 'Renewal order shipping total',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => floatval($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_arraysubs_initial_shipping_paid', [
            'type'              => 'string',
            'description'       => 'Whether initial shipping has been paid (yes/no)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // =====================================================================
        // Skip Renewal Meta Fields
        // =====================================================================

        register_post_meta($post_type, '_skip_cycles_count', [
            'type'              => 'integer',
            'description'       => 'Total number of cycles being skipped (0 = not skipping)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_skip_cycles_remaining', [
            'type'              => 'integer',
            'description'       => 'Remaining cycles to skip',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_original_next_payment_date', [
            'type'              => 'string',
            'description'       => 'Stored original next payment date before skip (Y-m-d H:i:s)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_skip_requested_at', [
            'type'              => 'string',
            'description'       => 'Timestamp when skip was requested (Y-m-d H:i:s)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_skip_requested_by', [
            'type'              => 'integer',
            'description'       => 'User ID who requested the skip (0 = system)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_skip_reason', [
            'type'              => 'string',
            'description'       => 'Optional reason recorded when skip renewal was requested',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_textarea_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_skip_history', [
            'type'              => 'string',
            'description'       => 'JSON array of past skip actions',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '[]',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        // =====================================================================
        // Pause Subscription Meta Fields
        // =====================================================================

        register_post_meta($post_type, '_pause_start_date', [
            'type'              => 'string',
            'description'       => 'When pause started (Y-m-d H:i:s)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_pause_end_date', [
            'type'              => 'string',
            'description'       => 'Scheduled pause end date (Y-m-d H:i:s)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_pause_duration_days', [
            'type'              => 'integer',
            'description'       => 'Pause duration in days',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_pause_reason', [
            'type'              => 'string',
            'description'       => 'Optional reason for pausing',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_pause_requested_by', [
            'type'              => 'integer',
            'description'       => 'User ID who requested the pause (0 = system)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_pre_pause_status', [
            'type'              => 'string',
            'description'       => 'Subscription status before pause (for restoration)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_pause_count', [
            'type'              => 'integer',
            'description'       => 'Total number of times this subscription has been paused',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => 0,
            'sanitize_callback' => fn($value) => absint($value),
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_last_pause_date', [
            'type'              => 'string',
            'description'       => 'Last time subscription was paused (Y-m-d H:i:s)',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);

        register_post_meta($post_type, '_pause_history', [
            'type'              => 'string',
            'description'       => 'JSON array of past pause actions',
            'single'            => true,
            'show_in_rest'      => true,
            'default'           => '[]',
            'sanitize_callback' => 'sanitize_text_field',
            'auth_callback'     => fn() => current_user_can('edit_posts'),
        ]);
    }

    /**
     * Add customer_search parameter to REST API collection params
     *
     * @param array $params Existing collection parameters
     * @return array Modified parameters
     */
    public function addAdminListCollectionParams(array $params): array
    {
        $params['customer_search'] = [
            'description' => __('Search by customer name or email', 'arraysubs'),
            'type'        => 'string',
            'sanitize_callback' => 'sanitize_text_field',
        ];

        $params['gateway'] = [
            'description'       => __('Filter subscriptions by stored payment gateway slug', 'arraysubs'),
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_key',
        ];

        return $params;
    }

    /**
     * Handle customer search in REST API queries
     *
     * @param array            $args    Query arguments
     * @param \WP_REST_Request $request REST request object
     * @return array Modified query arguments
     */
    public function handleCustomerSearchQuery(array $args, \WP_REST_Request $request): array
    {
        $customer_search = $request->get_param('customer_search');

        if (empty($customer_search)) {
            return $args;
        }

        // Search for users matching the search term
        $users = get_users([
            'search'         => '*' . $customer_search . '*',
            'search_columns' => ['user_login', 'user_email', 'display_name', 'user_nicename'],
            'fields'         => 'ID',
            'number'         => 100, // Limit to prevent performance issues
        ]);

        // Also search in user meta for first/last name
        $meta_users = get_users([
            'meta_query' => [
                'relation' => 'OR',
                [
                    'key'     => 'first_name',
                    'value'   => $customer_search,
                    'compare' => 'LIKE',
                ],
                [
                    'key'     => 'last_name',
                    'value'   => $customer_search,
                    'compare' => 'LIKE',
                ],
                [
                    'key'     => 'billing_first_name',
                    'value'   => $customer_search,
                    'compare' => 'LIKE',
                ],
                [
                    'key'     => 'billing_last_name',
                    'value'   => $customer_search,
                    'compare' => 'LIKE',
                ],
                [
                    'key'     => 'billing_email',
                    'value'   => $customer_search,
                    'compare' => 'LIKE',
                ],
            ],
            'fields' => 'ID',
            'number' => 100,
        ]);

        // Merge unique user IDs
        $user_ids = array_unique(array_merge($users, $meta_users));

        if (empty($user_ids)) {
            // No users found - return impossible query to get empty results
            $args['post__in'] = [0];
            return $args;
        }

        // Add meta query to filter by customer ID
        if (!isset($args['meta_query'])) {
            $args['meta_query'] = [];
        }

        $args['meta_query'][] = [
            'key'     => '_customer_id',
            'value'   => $user_ids,
            'compare' => 'IN',
        ];

        return $args;
    }

    /**
     * Handle payment gateway filtering in REST API queries.
     *
     * @param array            $args    Query arguments
     * @param \WP_REST_Request $request REST request object
     * @return array Modified query arguments
     */
    public function handleGatewayQuery(array $args, \WP_REST_Request $request): array
    {
        $gateway = sanitize_key((string) $request->get_param('gateway'));

        if ($gateway === '' || $gateway === 'all') {
            return $args;
        }

        if (strpos($gateway, 'arraysubs_') === 0) {
            $gateway = substr($gateway, strlen('arraysubs_'));
        }

        if (!isset($args['meta_query'])) {
            $args['meta_query'] = [];
        }

        $args['meta_query'][] = [
            'key'     => '_payment_gateway',
            'value'   => $gateway,
            'compare' => '=',
        ];

        return $args;
    }
}
