<?php

function wpuf_upgrade_4_2_0_user_directory_migration() {
    // Check if legacy options exist
    $legacy_userlisting = get_option( 'wpuf_userlisting', [] );
    $legacy_user_directory = get_option( 'user_directory', [] );

    if ( empty( $legacy_userlisting ) && empty( $legacy_user_directory ) ) {
        return;
    }

    // Get default settings from User_Listing API class
    $defaults = [
        'directory_layout'         => 'layout-1',
        'profile_layout'           => 'layout-1',
        'profile_size'             => 'thumbnail',
        'avatar_size'              => '32',
        'roles'                    => 'all',
        'profile_base'             => 'username',
        'max_item'                 => -1,
        'max_item_per_page'        => 10,
        'enable_search'            => true,
        'search_placeholder'       => 'Search Users',
        'searchable_fields'        => [ 'user_login', 'user_email', 'display_name' ],
        'excluded_users'           => [],
        'columns'                  => [ 'display_name', 'user_email' ],
        'profile_tabs'             => [],
        'about_tabs_content'       => [],
        'social_fields'            => [],
        'single_profile_permalink' => '',
        'show_avatar'              => true,
        'show_email'               => true,
        'show_phone'               => true,
        'show_user_bio'            => true,
        'show_username'            => true,
        'show_website'             => true,
        'enable_tabs'              => true,
        'default_active_tab'       => 'about',
        'posts_per_tab'            => 5,
        'profile_fields'           => [ 'user_login', 'display_name', 'user_email' ],
        'custom_fields'            => [],
        'orderby'                  => 'id',
        'order'                    => 'desc',
        'show_avatar_in_table'     => true,
    ];

    // Start with defaults
    $migrated_data = $defaults;

    // Map legacy user_directory settings
    if ( ! empty( $legacy_user_directory ) ) {
        // Map user_listing_template to directory_layout
        if ( isset( $legacy_user_directory['user_listing_template'] ) ) {
            $template_map = [
                'list'  => 'layout-1',  // Default list template
                'list1' => 'layout-1',
                'list2' => 'layout-2',
                'list3' => 'layout-3',
                'list4' => 'layout-4',
                'list5' => 'layout-5',
                'list6' => 'layout-6',
            ];
            $migrated_data['directory_layout'] = isset( $template_map[ $legacy_user_directory['user_listing_template'] ] )
                ? $template_map[ $legacy_user_directory['user_listing_template'] ]
                : 'layout-1';
        }

        // Map profile_header_template to profile_layout
        if ( isset( $legacy_user_directory['profile_header_template'] ) ) {
            $profile_map = [
                'layout' => 'layout-1',
                'layout1' => 'layout-2',
                'layout2' => 'layout-3',
            ];
            $migrated_data['profile_layout'] = isset( $profile_map[ $legacy_user_directory['profile_header_template'] ] )
                ? $profile_map[ $legacy_user_directory['profile_header_template'] ]
                : 'layout-1';
        }

        // Map avatar_size
        if ( isset( $legacy_user_directory['avatar_size'] ) ) {
            $migrated_data['avatar_size'] = $legacy_user_directory['avatar_size'];
        }

        // Map profile_permalink_base to profile_base
        if ( isset( $legacy_user_directory['profile_permalink_base'] ) ) {
            $migrated_data['profile_base'] = $legacy_user_directory['profile_permalink_base'];
        }

        // Map pro_img_size to profile_size
        if ( isset( $legacy_user_directory['pro_img_size'] ) ) {
            $migrated_data['profile_size'] = $legacy_user_directory['pro_img_size'];
        }
    }

    // Map legacy wpuf_userlisting settings.avatar to show_avatar
    if ( isset( $legacy_userlisting['settings']['avatar'] ) ) {
        $migrated_data['show_avatar'] = (bool) $legacy_userlisting['settings']['avatar'];
    }

    // Map legacy profile_tabs to new structure
    if ( ! empty( $legacy_userlisting['profile_tabs'] ) ) {
        $profile_tabs = [];
        $profile_tabs_labels = [];
        $profile_tabs_order = [];

        foreach ( $legacy_userlisting['profile_tabs'] as $tab_id => $tab_data ) {
            if ( ! empty( $tab_data['show_tab'] ) ) {
                $profile_tabs[] = $tab_id;
                $profile_tabs_order[] = $tab_id;

                // Map custom labels
                if ( ! empty( $tab_data['label'] ) ) {
                    $profile_tabs_labels[ $tab_id ] = $tab_data['label'];
                }
            }
        }

        $migrated_data['profile_tabs'] = $profile_tabs;
        $migrated_data['profile_tabs_order'] = $profile_tabs_order;
        $migrated_data['profile_tabs_labels'] = $profile_tabs_labels;
    }

    // Map legacy fields to about_tabs_content (all fields go in About tab)
    if ( ! empty( $legacy_userlisting['fields'] ) ) {
        $about_tabs_content = [];

        foreach ( $legacy_userlisting['fields'] as $field ) {
            // All field types go in about_tabs_content

            $migrated_field = [
                'id' => uniqid(),
                'profile_user_roles' => [ 'all' ],
                'viewer_roles' => [ 'all' ],
            ];

            switch ( $field['type'] ) {
                case 'meta':
                    $migrated_field['type'] = 'meta_field';
                    $migrated_field['label'] = isset( $field['label'] ) ? $field['label'] : $field['meta'];
                    $migrated_field['meta_key'] = $field['meta'];

                    // Map in_table to show_in_listing
                    if ( isset( $field['in_table'] ) && $field['in_table'] === 'yes' ) {
                        $migrated_field['show_in_listing'] = true;
                    }

                    // Map search_by to search_by_meta
                    if ( isset( $field['search_by'] ) && $field['search_by'] === 'yes' ) {
                        $migrated_field['search_by_meta'] = true;
                    }
                    break;

                case 'section':
                    $migrated_field['type'] = 'section';
                    $migrated_field['label'] = $field['label'];
                    break;

                case 'file':
                    $migrated_field['type'] = 'image_file';
                    $migrated_field['label'] = $field['label'];
                    $migrated_field['meta_key'] = $field['meta'];
                    break;

                case 'post':
                    $migrated_field['type'] = 'post_type';
                    $migrated_field['label'] = $field['label'];
                    $migrated_field['post_type'] = isset( $field['post_type'] ) ? $field['post_type'] : 'post';
                    $migrated_field['count'] = isset( $field['count'] ) ? $field['count'] : 5;
                    break;

                case 'comment':
                    $migrated_field['type'] = 'comment';
                    $migrated_field['label'] = $field['label'];
                    $migrated_field['post_type'] = isset( $field['post_type'] ) ? $field['post_type'] : 'post';
                    $migrated_field['count'] = isset( $field['count'] ) ? $field['count'] : 5;
                    break;
            }

            $about_tabs_content[] = $migrated_field;
        }

        $migrated_data['about_tabs_content'] = $about_tabs_content;

        // Handle post and comment fields to enable tabs and set posts_per_tab
        if ( ! empty( $legacy_userlisting['fields'] ) ) {
            foreach ( $legacy_userlisting['fields'] as $field ) {
                if ( $field['type'] === 'post' ) {
                    // Enable posts tab if not already enabled
                    if ( ! in_array( 'posts', $migrated_data['profile_tabs'] ) ) {
                        $migrated_data['profile_tabs'][] = 'posts';
                    }
                    // Set posts_per_tab from the field's count value
                    if ( isset( $field['count'] ) ) {
                        $migrated_data['posts_per_tab'] = intval( $field['count'] );
                    }
                } elseif ( $field['type'] === 'comment' ) {
                    // Enable comments tab if not already enabled
                    if ( ! in_array( 'comments', $migrated_data['profile_tabs'] ) ) {
                        $migrated_data['profile_tabs'][] = 'comments';
                    }
                }
            }
        }
    }

    // Create the new wpuf_user_listing post
    $postarr = [
        'post_title'   => 'Migrated User Directory',
        'post_type'    => 'wpuf_user_listing',
        'post_status'  => 'publish',
        'post_content' => wp_json_encode( $migrated_data ),
    ];

    $post_id = wp_insert_post( $postarr );

    if ( is_wp_error( $post_id ) || ! $post_id ) {
        error_log( 'WPUF User Directory Migration Failed: ' . ( is_wp_error( $post_id ) ? $post_id->get_error_message() : 'Unknown error' ) );
        return;
    }
}

wpuf_upgrade_4_2_0_user_directory_migration();
