<?php
/**
 * Pro Admin Menu for User Directory
 *
 * Handles the Pro version admin menu registration and script enqueuing.
 * Pro version unlocks all features - no restrictions.
 *
 * @package WPUF_Pro
 * @subpackage UserDirectory\Admin
 * @since 4.2.11
 */

namespace WPUF\UserDirectory\Admin;

/**
 * Menu Class
 *
 * @since 4.2.11
 */
class Menu {

    /**
     * Constructor
     *
     * @since 4.2.11
     */
    public function __construct() {
        // Hook to wpuf_admin_menu_top with priority 15 to position after Registration Forms
        add_action( 'wpuf_admin_menu_top', [ $this, 'add_ud_menu' ], 15 );
    }

    /**
     * Add User Directory submenu
     *
     * @since 4.2.11
     *
     * @return void
     */
    public function add_ud_menu() {
        $hook = add_submenu_page(
            'wp-user-frontend',
            __( 'User Directories', 'wpuf-pro' ),
            __( 'User Directories', 'wpuf-pro' ),
            'manage_options',
            'wpuf_userlisting',
            [ $this, 'include_page_template' ]
        );

        add_action( 'load-' . $hook, [ $this, 'enqueue_scripts' ] );
    }

    /**
     * Load content of user directory page
     *
     * @since 4.2.11
     *
     * @return void
     */
    public function include_page_template() {
        include WPUF_UD_ROOT . '/includes/views/admin/user-directory.php';

        if ( function_exists( 'wpuf_load_headway_badge' ) ) {
            wpuf_load_headway_badge();
        }
    }

    /**
     * Enqueue scripts and styles
     *
     * @since 4.2.11
     *
     * @return void
     */
    public function enqueue_scripts() {
        // Use the generated asset file for dependencies and version
        $asset_path = WPUF_UD_ROOT . '/assets/js/wpuf-ud.asset.php';

        if ( file_exists( $asset_path ) ) {
            $asset = include $asset_path;
        } else {
            $asset = [
                'dependencies' => [],
                'version'      => WPUF_PRO_VERSION,
            ];
        }

        wp_enqueue_script(
            'wpuf-user-directory',
            WPUF_UD_ASSET_URI . '/js/wpuf-ud.js',
            $asset['dependencies'],
            $asset['version'],
            true
        );

        wp_enqueue_style(
            'wpuf-user-directory',
            WPUF_UD_ASSET_URI . '/css/wpuf-ud.css',
            [],
            $asset['version']
        );

        // Enqueue Font Awesome for icon picker preview
        wp_enqueue_style( 'wpuf-font-awesome' );

        // Enqueue WordPress media uploader for icon image upload
        wp_enqueue_media();

        wp_localize_script(
            'wpuf-user-directory',
            'wpuf_ud', [
                'site_url'          => site_url(),
                'admin_url'         => admin_url(),
                'asset_url'         => WPUF_UD_ASSET_URI,
                'roles'             => wpuf_ud_get_user_roles(),
                'post_types'        => $this->get_filtered_post_types(),
                'user_meta_fields'  => $this->get_user_meta_keys(),
                'directory_layouts' => [
                    'layout-1' => [
                        'name'  => __( 'Layout 1', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/directory-layout-1.png',
                    ],
                    'layout-2' => [
                        'name'  => __( 'Layout 2', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/directory-layout-2.png',
                    ],
                    'layout-3' => [
                        'name'  => __( 'Layout 3', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/directory-layout-3.png',
                    ],
                    'layout-4' => [
                        'name'  => __( 'Layout 4', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/directory-layout-4.png',
                    ],
                    'layout-5' => [
                        'name'  => __( 'Layout 5', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/directory-layout-5.png',
                    ],
                    'layout-6' => [
                        'name'  => __( 'Layout 6', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/directory-layout-6.png',
                    ],
                    'layout-7' => [
                        'name'  => __( 'Layout 7', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/directory-layout-7.png',
                    ],
                    'layout-8' => [
                        'name'  => __( 'Layout 8', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/directory-layout-8.png',
                    ],
                    'layout-9' => [
                        'name'  => __( 'Layout 9', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/directory-layout-9.png',
                    ],
                    'layout-10' => [
                        'name'  => __( 'Layout 10', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/directory-layout-10.png',
                    ],
                ],
                'profile_layouts'   => [
                    'layout-1' => [
                        'name'  => __( 'Navigator', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/profile-layout-1.png',
                    ],
                    'layout-2' => [
                        'name'  => __( 'Centered', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/profile-layout-2.png',
                    ],
                    'layout-3' => [
                        'name'  => __( 'Spotlight', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/profile-layout-3.png',
                    ],
                    'layout-4' => [
                        'name'  => __( 'Bordered', 'wpuf-pro' ),
                        'image' => WPUF_UD_ASSET_URI . '/images/profile-layout-4.png',
                    ],
                ],
                'profile_size'      => wpuf_get_image_sizes(),
                'avatar_size'       => [
                    '32'  => '32 x 32',
                    '48'  => '48 x 48',
                    '80'  => '80 x 80',
                    '128' => '128 x 128',
                    '160' => '160 x 160',
                    '192' => '192 x 192',
                    '256' => '256 x 256',
                ],
                'profile_base'      => [
                    'username' => __( 'User Name', 'wpuf-pro' ),
                    'user_id'  => __( 'User ID', 'wpuf-pro' ),
                ],
                'profile_tabs'      => $this->get_profile_tabs(),
                'rest_base'         => rest_url( 'wpuf/v1/user_directory' ),
                'rest_nonce'        => wp_create_nonce( 'wp_rest' ),
                'icons'             => $this->get_icon_config(),
            ],
            $this->get_localized_data()
        );
    }

    /**
     * Get localized data for JavaScript
     *
     * @since 4.2.11
     *
     * @return array
     */
    private function get_localized_data() {
        $image_base = WPUF_UD_ASSET_URI . '/images/';

        $data = [
            'site_url'          => site_url(),
            'admin_url'         => admin_url(),
            'asset_url'         => WPUF_UD_ASSET_URI,
            'is_pro_active'     => true,
            'roles'             => $this->get_user_roles(),
            'post_types'        => $this->get_filtered_post_types(),
            'user_meta_fields'  => $this->get_user_meta_keys(),
            'directory_layouts' => $this->get_directory_layouts( $image_base ),
            'profile_layouts'   => $this->get_profile_layouts( $image_base ),
            'avatar_size'       => $this->get_avatar_sizes(),
            'profile_size'      => $this->get_profile_sizes(),
            'profile_base'      => $this->get_profile_base_options(),
            'profile_tabs'      => $this->get_profile_tabs(),
            'rest_base'         => rest_url( 'wpuf/v1/user_directory' ),
            'rest_nonce'        => wp_create_nonce( 'wp_rest' ),
            'i18n'              => $this->get_i18n_strings(),
        ];

        /**
         * Filter the Pro admin localized data
         *
         * @since 4.2.11
         *
         * @param array $data The localized data array.
         */
        return apply_filters( 'wpuf_ud_pro_admin_localized_data', $data );
    }

    /**
     * Get user roles
     *
     * @since 4.2.11
     *
     * @return array
     */
    private function get_user_roles() {
        if ( function_exists( 'wpuf_ud_get_user_roles' ) ) {
            return wpuf_ud_get_user_roles();
        }

        global $wp_roles;

        $roles = [];

        if ( ! empty( $wp_roles->roles ) ) {
            foreach ( $wp_roles->roles as $key => $role ) {
                $roles[ $key ] = $role['name'];
            }
        }

        return $roles;
    }

    /**
     * Get directory layouts - all unlocked for Pro
     *
     * @since 4.2.11
     *
     * @param string $image_base Base URL for layout images.
     *
     * @return array
     */
    private function get_directory_layouts( $image_base ) {
        return [
            'layout-1' => [
                'name'    => __( 'Classic Table', 'wpuf-pro' ),
                'image'   => $image_base . 'directory-layout-1.png',
                'is_free' => false,
            ],
            'layout-2' => [
                'name'    => __( 'Round Sidecard (2x)', 'wpuf-pro' ),
                'image'   => $image_base . 'directory-layout-2.png',
                'is_free' => false,
            ],
            'layout-3' => [
                'name'    => __( 'Round Grid (3x)', 'wpuf-pro' ),
                'image'   => $image_base . 'directory-layout-3.png',
                'is_free' => true,
            ],
            'layout-4' => [
                'name'    => __( 'Square Grid (3x)', 'wpuf-pro' ),
                'image'   => $image_base . 'directory-layout-4.png',
                'is_free' => false,
            ],
            'layout-5' => [
                'name'    => __( 'Round Grid (4x)', 'wpuf-pro' ),
                'image'   => $image_base . 'directory-layout-5.png',
                'is_free' => false,
            ],
            'layout-6' => [
                'name'    => __( 'Square Grid (4x)', 'wpuf-pro' ),
                'image'   => $image_base . 'directory-layout-6.png',
                'is_free' => false,
            ],
            'layout-7' => [
                'name'    => __( 'Square Grid (2x)', 'wpuf-pro' ),
                'image'   => $image_base . 'directory-layout-7.png',
                'is_free' => false,
            ],
            'layout-8' => [
                'name'    => __( 'Round Sidecard (3x)', 'wpuf-pro' ),
                'image'   => $image_base . 'directory-layout-8.png',
                'is_free' => false,
            ],
            'layout-9' => [
                'name'    => __( 'Rounded Sidecard (3x)', 'wpuf-pro' ),
                'image'   => $image_base . 'directory-layout-9.png',
                'is_free' => false,
            ],
            'layout-10' => [
                'name'    => __( 'Wide Sidecard', 'wpuf-pro' ),
                'image'   => $image_base . 'directory-layout-10.png',
                'is_free' => false,
            ],
        ];
    }

    /**
     * Get profile layouts - all unlocked for Pro
     *
     * @since 4.2.11
     *
     * @param string $image_base Base URL for layout images.
     *
     * @return array
     */
    private function get_profile_layouts( $image_base ) {
        return [
            'layout-1' => [
                'name'    => __( 'Navigator', 'wpuf-pro' ),
                'image'   => $image_base . 'profile-layout-1.png',
                'is_free' => false,
            ],
            'layout-2' => [
                'name'    => __( 'Centered', 'wpuf-pro' ),
                'image'   => $image_base . 'profile-layout-2.png',
                'is_free' => true,
            ],
            'layout-3' => [
                'name'    => __( 'Spotlight', 'wpuf-pro' ),
                'image'   => $image_base . 'profile-layout-3.png',
                'is_free' => false,
            ],
        ];
    }

    /**
     * Get avatar sizes - all unlocked for Pro
     *
     * Pro uses simple key => label format (no is_free flag needed).
     *
     * @since 4.2.11
     *
     * @return array
     */
    private function get_avatar_sizes() {
        return [
            '32'  => '32 x 32',
            '48'  => '48 x 48',
            '80'  => '80 x 80',
            '128' => '128 x 128',
            '160' => '160 x 160',
            '192' => '192 x 192',
            '256' => '256 x 256',
        ];
    }

    /**
     * Get profile image sizes - all unlocked for Pro
     *
     * Pro uses simple key => label format (no is_free flag needed).
     *
     * @since 4.2.11
     *
     * @return array
     */
    private function get_profile_sizes() {
        // Use wpuf_get_image_sizes if available
        if ( function_exists( 'wpuf_get_image_sizes' ) ) {
            return wpuf_get_image_sizes();
        }

        // Fallback to WordPress registered sizes
        $registered_sizes = wp_get_registered_image_subsizes();

        $sizes = [];
        foreach ( $registered_sizes as $name => $size ) {
            $sizes[ $name ] = ucfirst( str_replace( '_', ' ', $name ) ) . ' (' . $size['width'] . 'x' . $size['height'] . ')';
        }

        return $sizes;
    }

    /**
     * Get profile base options
     *
     * @since 4.2.11
     *
     * @return array
     */
    private function get_profile_base_options() {
        return [
            'username' => __( 'User Name', 'wpuf-pro' ),
            'user_id'  => __( 'User ID', 'wpuf-pro' ),
        ];
    }

    /**
     * Get profile tabs - all unlocked for Pro
     *
     * @since 4.2.11
     *
     * @return array
     */
    private function get_profile_tabs() {
        $tabs = [
            'about' => [
                'label'     => __( 'About', 'wpuf-pro' ),
                'default'   => 'About',
                'is_active' => true,
                'is_free'   => true,
            ],
            'posts' => [
                'label'     => __( 'Posts', 'wpuf-pro' ),
                'default'   => 'Posts',
                'is_active' => true,
                'is_free'   => false,
            ],
            'file' => [
                'label'     => __( 'Files', 'wpuf-pro' ),
                'default'   => 'File/Image',
                'is_active' => true,
                'is_free'   => false,
            ],
            'comments' => [
                'label'     => __( 'Comments', 'wpuf-pro' ),
                'default'   => 'Comments',
                'is_active' => true,
                'is_free'   => false,
            ],
        ];

        // Add Activity tab if User Activity module is active
        if ( class_exists( 'WPUF_User_Activity' ) ) {
            $tabs['activity'] = [
                'label'     => __( 'Activity', 'wpuf-pro' ),
                'default'   => 'Activity',
                'is_active' => true,
                'is_free'   => false,
            ];
        }

        return $tabs;
    }

    /**
     * Get filtered post types
     *
     * @since 4.2.11
     *
     * @return array
     */
    private function get_filtered_post_types() {
        $post_types = get_post_types();

        $excluded = [
            'attachment',
            'revision',
            'nav_menu_item',
            'wpuf_forms',
            'wpuf_profile',
            'wp_block',
            'wp_template',
            'wp_template_part',
            'wp_navigation',
        ];

        foreach ( $excluded as $exclude ) {
            unset( $post_types[ $exclude ] );
        }

        $filtered = [];
        foreach ( $post_types as $key => $type ) {
            $post_type_obj    = get_post_type_object( $key );
            $filtered[ $key ] = $post_type_obj ? $post_type_obj->labels->singular_name : $type;
        }

        return $filtered;
    }

    /**
     * Get user meta keys from database
     *
     * @since 4.2.11
     *
     * @return array
     */
    private function get_user_meta_keys() {
        $cache_key  = 'wpuf_ud_user_meta_keys';
        $meta_keys  = get_transient( $cache_key );

        if ( false !== $meta_keys ) {
            return $meta_keys;
        }

        global $wpdb;

        $query = $wpdb->get_results(
            "SELECT DISTINCT(meta_key) FROM {$wpdb->usermeta}
            WHERE
            meta_key != 'admin_color'
            AND meta_key != 'wp_user_level'
            AND meta_key != 'wp_capabilities'
            AND meta_key != 'user_role'
            AND meta_key != 'dismissed_wp_pointers'
            AND meta_key != 'users_per_page'
            AND meta_key != 'wp_dashboard_quick_press_last_post_id'
            AND meta_key != 'wp_post_formats_post'
            AND meta_key != 'wp_nav_menu_recently_edited'
            AND meta_key != 'use_ssl'
            AND meta_key NOT LIKE 'closedpostboxes%'
            AND meta_key NOT LIKE 'meta-box-order_%'
            AND meta_key NOT LIKE 'metaboxhidden_%'
            AND meta_key NOT LIKE 'screen_layout_%'
            AND meta_key NOT LIKE 'wp_user-settings%'",
            ARRAY_A
        );

        $meta_keys = [];

        $profile_fields = [
            'user_login',
            'first_name',
            'last_name',
            'display_name',
            'nickname',
            'user_email',
            'user_url',
            'description',
        ];

        foreach ( $query as $val ) {
            $meta_key = $val['meta_key'];
            if ( ! in_array( $meta_key, $profile_fields, true ) ) {
                $meta_keys[ $meta_key ] = $meta_key;
            }
        }

        set_transient( $cache_key, $meta_keys, 12 * HOUR_IN_SECONDS );

        return $meta_keys;
    }

    /**
     * Get icon configuration from JSON file
     *
     * @since 4.2.13
     *
     * @return array
     */
    private function get_icon_config() {
        $config_file = WPUF_ROOT . '/config/icons-config.json';

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

        $config = json_decode( file_get_contents( $config_file ), true );

        if ( json_last_error() !== JSON_ERROR_NONE ) {
            return [];
        }

        return $config['icons'] ?? [];
    }

    /**
     * Get i18n strings
     *
     * @since 4.2.11
     *
     * @return array
     */
    private function get_i18n_strings() {
        return [
            'user_directories'   => __( 'User Directories', 'wpuf-pro' ),
            'new_directory'      => __( 'New Directory', 'wpuf-pro' ),
            'edit_directory'     => __( 'Edit Directory', 'wpuf-pro' ),
            'delete_directory'   => __( 'Delete Directory', 'wpuf-pro' ),
            'search_directories' => __( 'Search Directories', 'wpuf-pro' ),
            'no_directories'     => __( 'No directories found', 'wpuf-pro' ),
            'create_first'       => __( 'Create your first directory', 'wpuf-pro' ),
            'all_features'       => __( 'All Features Unlocked', 'wpuf-pro' ),
            'unlimited'          => __( 'Unlimited', 'wpuf-pro' ),
            'step_basic'         => __( 'Basic', 'wpuf-pro' ),
            'step_layout'        => __( 'Directory Layout', 'wpuf-pro' ),
            'step_profile'       => __( 'Profile Layout', 'wpuf-pro' ),
            'step_tabs'          => __( 'Profile Tabs', 'wpuf-pro' ),
            'step_advanced'      => __( 'Advanced', 'wpuf-pro' ),
            'next'               => __( 'Next', 'wpuf-pro' ),
            'previous'           => __( 'Previous', 'wpuf-pro' ),
            'save'               => __( 'Save', 'wpuf-pro' ),
            'cancel'             => __( 'Cancel', 'wpuf-pro' ),
            'saving'             => __( 'Saving...', 'wpuf-pro' ),
            'saved'              => __( 'Saved!', 'wpuf-pro' ),
            'error_saving'       => __( 'Error saving directory', 'wpuf-pro' ),
            'confirm_delete'     => __( 'Are you sure you want to delete this directory?', 'wpuf-pro' ),
            'directory_name'     => __( 'Directory Name', 'wpuf-pro' ),
            'select_roles'       => __( 'Select Roles', 'wpuf-pro' ),
            'all_roles'          => __( 'All Roles', 'wpuf-pro' ),
            'users_per_page'     => __( 'Users Per Page', 'wpuf-pro' ),
            'users_per_row'      => __( 'Users Per Row', 'wpuf-pro' ),
            'sort_by'            => __( 'Sort By', 'wpuf-pro' ),
            'sort_order'         => __( 'Sort Order', 'wpuf-pro' ),
            'ascending'          => __( 'Ascending', 'wpuf-pro' ),
            'descending'         => __( 'Descending', 'wpuf-pro' ),
            'avatar_size'        => __( 'Avatar Size', 'wpuf-pro' ),
            'profile_image_size' => __( 'Profile Gallery Image Size', 'wpuf-pro' ),
            'enable_search'      => __( 'Enable Search', 'wpuf-pro' ),
            'exclude_users'      => __( 'Exclude Users', 'wpuf-pro' ),
            'exclude_users_desc' => __( 'Enter user IDs separated by commas', 'wpuf-pro' ),
            'shortcode'          => __( 'Shortcode', 'wpuf-pro' ),
            'copy_shortcode'     => __( 'Copy Shortcode', 'wpuf-pro' ),
            'copied'             => __( 'Copied!', 'wpuf-pro' ),
            'activity_tab'       => __( 'Activity', 'wpuf-pro' ),
            'cover_photo'        => __( 'Cover Photo', 'wpuf-pro' ),
            'custom_avatar'      => __( 'Custom Avatar', 'wpuf-pro' ),
        ];
    }
}
