<?php

namespace WPUF\UserDirectory\Admin;

class Menu {

    public function __construct() {
        // Hook to wpuf_admin_menu_top with priority 15 to position after Registration Forms but before Transactions
        add_action( 'wpuf_admin_menu_top', [ $this, 'add_ud_menu' ], 15 );
    }

    public function add_ud_menu() {
        // Add User Directory as submenu under the main User Frontend menu, positioned after Subscriptions
        $wpufud = 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-' . $wpufud, [ $this, 'enqueue_scripts' ] );
    }

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

        wpuf_load_headway_badge();
    }

    /**
     * Enqueue scripts and styles
     *
     * @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']
        );

        wp_localize_script(
            'wpuf-user-directory',
            'wpuf_ud', [
                'site_url'          => site_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',
                    ],
                ],
                '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',
                    ],
                ],
                '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_nonce'        => wp_create_nonce( 'wp_rest' ),
            ]
        );
    }

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

        // Remove unwanted post types
        unset( $post_types['attachment'] );
        unset( $post_types['revision'] );
        unset( $post_types['nav_menu_item'] );
        unset( $post_types['wpuf_forms'] );
        unset( $post_types['wpuf_profile'] );
        unset( $post_types['wp_block'] );
        unset( $post_types['wp_template'] );
        unset( $post_types['wp_template_part'] );
        unset( $post_types['wp_navigation'] );

        $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
     *
     * @return array
     */
    private function get_user_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 = [];

        // Default profile fields to exclude (they're already in Profile Fields optgroup)
        $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'];
            // Skip if it's a default profile field
            if ( ! in_array( $meta_key, $profile_fields ) ) {
                $meta_keys[ $meta_key ] = $meta_key;
            }
        }

        return $meta_keys;
    }

    /**
     * Get profile tabs with User Activity module check
     *
     * @since 4.2.0
     * @return array
     */
    private function get_profile_tabs() {
        $tabs = [
            'about'    => [
                'label'     => __( 'About', 'wpuf-pro' ),
                'default'   => 'About',
                'is_active' => true,
            ],
            'posts'    => [
                'label'     => __( 'Posts', 'wpuf-pro' ),
                'default'   => 'Posts',
                'is_active' => true,
            ],
            'file'     => [
                'label'     => __( 'File', 'wpuf-pro' ),
                'default'   => 'File/Image',
                'is_active' => true,
            ],
            'comments' => [
                'label'     => __( 'Comments', 'wpuf-pro' ),
                'default'   => 'Comments',
                'is_active' => true,
            ],
        ];

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

        return $tabs;
    }
}
