<?php

/**
 * Get the user list schema.
 *
 * @since 2.0.0
 *
 * @return array
 */
function wpuf_ud_get_user_list_schema() {
    $location = WPUF_UD_ROOT . '/src/settings-schema.json';

    if ( ! file_exists( $location ) ) {
        return [];
    }

    global $wp_filesystem;

    if ( ! $wp_filesystem ) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
        WP_Filesystem();
    }

    $content = $wp_filesystem->get_contents( $location );

    if ( empty( $content ) ) {
        return [];
    }

    return json_decode( $content, true );
}

/**
 * Get available user meta fields for selection
 *
 * @since 4.2.0
 *
 * @return array
 */
function wpuf_get_user_meta_fields() {
    global $wpdb;

    // Get common user meta fields
    $common_fields = [
        'rich_editing'         => __( 'Rich Editing', 'wpuf-pro' ),
        'syntax_highlighting'  => __( 'Syntax Highlighting', 'wpuf-pro' ),
        'comment_shortcuts'    => __( 'Comment Shortcuts', 'wpuf-pro' ),
        'show_admin_bar_front' => __( 'Show Admin Bar Front', 'wpuf-pro' ),
        'locale'               => __( 'Locale', 'wpuf-pro' ),
        'show_welcome_panel'   => __( 'Show Welcome Panel', 'wpuf-pro' ),
        'session_tokens'       => __( 'Session Tokens', 'wpuf-pro' ),
        'community-events-location' => __( 'Community Events Location', 'wpuf-pro' ),
        'wp_persisted_preferences' => __( 'WP Persisted Preferences', 'wpuf-pro' ),
        '_woocommerce_tracks_anon_id' => __( 'WC Last Active', 'wpuf-pro' ),
        'wc_last_active'       => __( 'WC Last Active', 'wpuf-pro' ),
        'last_update'          => __( 'Last Update', 'wpuf-pro' ),
    ];

    // Get dynamic user meta fields from database (limit to avoid performance issues)
    $dynamic_fields = [];

    // Limit query to prevent performance issues on sites with many meta keys
    $meta_keys = $wpdb->get_col(
        $wpdb->prepare(
            "SELECT DISTINCT meta_key FROM {$wpdb->usermeta} LIMIT %d",
            1000
        )
    );

    foreach ( $meta_keys as $meta_key ) {
        if ( ! isset( $common_fields[ $meta_key ] ) ) {
            // Format the key to be more readable
            $label = ucwords( str_replace( [ '_', '-' ], ' ', $meta_key ) );
            $dynamic_fields[ $meta_key ] = $meta_key;
        }
    }

    // Merge common and dynamic fields
    $all_fields = array_merge( $common_fields, $dynamic_fields );

    // Apply filter to allow customization
    return apply_filters( 'wpuf_user_meta_fields', $all_fields );
}

function wpuf_ud_get_localize_object() {
    return [
        'ajaxurl'           => admin_url( 'admin-ajax.php' ),
        'rest_url'          => rest_url(),
        'rest_nonce'        => wp_create_nonce( 'wp_rest' ),
        'roles'             => wpuf_ud_get_user_roles(),
        'users'             => wpuf_get_users_list(),
        'asset_url'         => WPUF_UD_ASSET_URI,
        'directory_layouts' => [
            'layout-1' => __( 'Layout 1', 'wpuf-pro' ),
            'layout-2' => __( 'Layout 2', 'wpuf-pro' ),
            'layout-3' => __( 'Layout 3', 'wpuf-pro' ),
            'layout-4' => __( 'Layout 4', 'wpuf-pro' ),
            'layout-5' => __( 'Layout 5', 'wpuf-pro' ),
            'layout-6' => __( 'Layout 6', 'wpuf-pro' ),
            'layout-7' => __( 'Layout 7', 'wpuf-pro' ),
            'layout-8' => __( 'Layout 8', 'wpuf-pro' ),
            'layout-9' => __( 'Layout 9', 'wpuf-pro' ),
            'layout-10' => __( 'Layout 10', 'wpuf-pro' ),
        ],
        'profile_layouts'   => [
            'layout-1' => __( 'Navigator', 'wpuf-pro' ),
            'layout-2' => __( 'Centered', 'wpuf-pro' ),
            'layout-3' => __( 'Spotlight', 'wpuf-pro' ),
        ],
        'profile_fields'    => [
            'username'     => __( 'Username', 'wpuf-pro' ),
            'display_name' => __( 'Display Name', 'wpuf-pro' ),
            'first_name'   => __( 'First Name', 'wpuf-pro' ),
            'last_name'    => __( 'Last Name', 'wpuf-pro' ),
            'nickname'     => __( 'Nickname', 'wpuf-pro' ),
            'email'        => __( 'E-mail', 'wpuf-pro' ),
            'website'      => __( 'Website', 'wpuf-pro' ),
            'description'  => __( 'Biographical Info', 'wpuf-pro' ),
        ],
        'user_meta_fields'  => wpuf_get_user_meta_fields(),
        'profile_sizes'     => [
            'thumbnail' => __( 'Thumbnail', 'wpuf-pro' ),
            'medium'    => __( 'Medium', 'wpuf-pro' ),
            'large'     => __( 'Large', 'wpuf-pro' ),
        ],
        'avatar_sizes'      => [
            'thumbnail' => __( 'Thumbnail (150x150)', 'wpuf-pro' ),
            'medium'    => __( 'Medium (300x300)', 'wpuf-pro' ),
            'large'     => __( 'Large (600x600)', 'wpuf-pro' ),
        ],
        'profile_bases'     => [
            'user_id'  => __( 'User ID', 'wpuf-pro' ),
            'username' => __( 'Username', 'wpuf-pro' ),
        ],
        'columns'           => [
            'avatar'       => __( 'Avatar', 'wpuf-pro' ),
            'user_login'   => __( 'Username', 'wpuf-pro' ),
            'display_name' => __( 'Display Name', 'wpuf-pro' ),
            'user_email'   => __( 'Email', 'wpuf-pro' ),
            'website'      => __( 'Website', 'wpuf-pro' ),
            'bio'          => __( 'Bio', 'wpuf-pro' ),
        ],
        'profile_tabs'      => [
            'about'    => __( 'About', 'wpuf-pro' ),
            'comments' => __( 'Comments', 'wpuf-pro' ),
            'posts'    => __( 'Posts', 'wpuf-pro' ),
            'files'    => __( 'Files/Images', 'wpuf-pro' ),
        ],
        'searchable_fields' => [
            'user_login'   => __( 'Username', 'wpuf-pro' ),
            'user_email'   => __( 'Email', 'wpuf-pro' ),
            'display_name' => __( 'Display Name', 'wpuf-pro' ),
        ],
        'current_user_id'              => get_current_user_id(),
        'current_user_can_manage_options' => current_user_can( 'manage_options' ),
    ];
}

/**
 * Get user's active subscription pack IDs
 *
 * Checks if a user has an active (non-expired, non-cancelled) subscription pack.
 * Only returns active subscriptions.
 *
 * @since 4.2.6
 *
 * @param int $user_id User ID to check.
 * @return array Array of active subscription pack IDs. Empty array if no active subscription or subscription module not available.
 */
function wpuf_ud_get_user_active_subscription_packs( $user_id ) {
    // Sanitize and validate user ID
    $user_id = absint( $user_id );
    if ( ! $user_id ) {
        return [];
    }

    // Check if subscription module is available
    if ( ! function_exists( 'wpuf' ) ) {
        return [];
    }

    // Try to access subscription - isset() doesn't work with container magic methods
    // So we try to access it directly and check if method exists
    try {
        $subscription = wpuf()->subscription;
        if ( ! $subscription || ! method_exists( $subscription, 'get_user_pack' ) ) {
            return [];
        }
    } catch ( \Exception $e ) {
        return [];
    }

    // Get user's subscription pack data
    $user_pack = wpuf()->subscription->get_user_pack( $user_id );

    // If no subscription data, return empty array
    if ( empty( $user_pack ) || ! is_array( $user_pack ) ) {
        return [];
    }

    // Check if pack_id exists
    if ( ! isset( $user_pack['pack_id'] ) || empty( $user_pack['pack_id'] ) ) {
        return [];
    }

    $pack_id = (int) $user_pack['pack_id'];

    // Check if subscription is cancelled
    $status = isset( $user_pack['status'] ) ? $user_pack['status'] : '';
    if ( 'Cancel' === $status || 'cancel' === strtolower( $status ) ) {
        return [];
    }

    // Only allow 'completed' or 'Free' status for active subscriptions
    if ( ! empty( $status ) && 'completed' !== $status && 'Free' !== $status ) {
        return [];
    }

    // Check expiration
    $expire = isset( $user_pack['expire'] ) ? $user_pack['expire'] : '';

    // Check expiration logic (from User_Subscription::expired())
    $expired = true;
    if ( 'unlimited' === strtolower( $expire ) || empty( $expire ) || -1 === intval( $expire ) ) {
        // Not expired (unlimited, empty, or -1)
        $expired = false;
    } elseif ( ! empty( $expire ) ) {
        // Check if expiration date is in the future
        $expire_timestamp = strtotime( $expire );
        if ( false !== $expire_timestamp && $expire_timestamp >= current_time( 'timestamp' ) ) {
            // Not expired (future date)
            $expired = false;
        }
    }

    // If expired, return empty array
    if ( $expired ) {
        return [];
    }

    // Subscription is active, return pack ID
    return [ $pack_id ];
}
