<?php
/**
 * Duplicator Module
 *
 * Duplicate any post type or taxonomy with all metadata.
 *
 * @package BlaminhorEssentials
 */

// Prevent direct access
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Duplicator module class
 */
class Blaminhor_Essentials_Module_Duplicator extends Blaminhor_Essentials_Module {

    /**
     * Module ID
     *
     * @var string
     */
    protected $id = 'duplicator';

    /**
     * Module name
     *
     * @var string
     */
    protected $name = 'Content Duplicator';

    /**
     * Initialize module
     */
    protected function init() {
        // Note: Strings are translated in the base class get_name() and get_description() methods.
        $this->name        = 'Content Duplicator';
        $this->description = 'Duplicate any post type or taxonomy with all metadata.';

        // Migration: Update old suffix format from " (Copy)" to " - copy"
        $this->maybe_migrate_suffix();
    }

    /**
     * Migrate old suffix format to new format
     */
    private function maybe_migrate_suffix() {
        $current_suffix = $this->get_setting( 'title_suffix', '' );

        // Check for old format (with parentheses in any language) or malformed new format
        // Old formats: " (Copy)", " (Copie)", "(Kopie)", etc.
        // Malformed: "- copy", "- Copie" (missing leading space)
        $needs_migration = false;

        // Check for parentheses format
        if ( preg_match( '/\(.*\)/', $current_suffix ) ) {
            $needs_migration = true;
        }

        // Check for malformed new format (missing leading space before dash)
        if ( preg_match( '/^-\s/', $current_suffix ) ) {
            $needs_migration = true;
        }

        if ( $needs_migration ) {
            $this->settings['title_suffix'] = __( ' - copy', 'blaminhor-essentials' );
            $this->save_settings( $this->settings );
        }
    }

    /**
     * Get default settings
     *
     * @return array
     */
    protected function get_default_settings() {
        // Get all available post types (includes custom post types).
        $all_post_types = blaminhor_essentials_get_post_types();
        $default_post_types = ! empty( $all_post_types ) ? array_keys( $all_post_types ) : array( 'post', 'page' );

        // Get all available taxonomies (includes custom taxonomies).
        $all_taxonomies = blaminhor_essentials_get_taxonomies();
        $default_taxonomies = ! empty( $all_taxonomies ) ? array_keys( $all_taxonomies ) : array( 'category', 'post_tag' );

        return array(
            'post_types'       => $default_post_types,
            'taxonomies'       => $default_taxonomies,
            'copy_title'       => true,
            'title_prefix'     => '',
            'title_suffix'     => __( ' - copy', 'blaminhor-essentials' ),
            'copy_date'        => false,
            'copy_status'      => 'draft',
            'copy_author'      => true,
            'copy_taxonomies'  => true,
            'copy_meta'        => true,
            'copy_children'    => false,
            'copy_comments'    => false,
            'redirect_after'   => 'edit',
        );
    }

    /**
     * Register hooks
     */
    protected function register_hooks() {
        // Admin hooks
        add_action( 'admin_init', array( $this, 'handle_settings_submission' ) );

        // Add duplicate link to post row actions
        add_filter( 'post_row_actions', array( $this, 'add_duplicate_link' ), 10, 2 );
        add_filter( 'page_row_actions', array( $this, 'add_duplicate_link' ), 10, 2 );

        // Add duplicate link to taxonomy row actions
        foreach ( $this->get_setting( 'taxonomies', array() ) as $taxonomy ) {
            add_filter( "{$taxonomy}_row_actions", array( $this, 'add_taxonomy_duplicate_link' ), 10, 2 );
        }

        // Handle duplication
        add_action( 'admin_action_blaminhor_essentials_duplicate_post', array( $this, 'duplicate_post' ) );
        add_action( 'admin_action_blaminhor_essentials_duplicate_term', array( $this, 'duplicate_term' ) );

        // Add bulk action
        $post_types = $this->get_setting( 'post_types', array() );
        foreach ( $post_types as $post_type ) {
            add_filter( "bulk_actions-edit-{$post_type}", array( $this, 'add_bulk_action' ) );
            add_filter( "handle_bulk_actions-edit-{$post_type}", array( $this, 'handle_bulk_action' ), 10, 3 );
        }

        // Admin notices
        add_action( 'admin_notices', array( $this, 'show_notices' ) );

        // Add to admin bar
        add_action( 'admin_bar_menu', array( $this, 'add_admin_bar_link' ), 100 );
    }

    /**
     * Add duplicate link to post row actions
     *
     * @param array   $actions Post actions.
     * @param WP_Post $post    Post object.
     * @return array
     */
    public function add_duplicate_link( $actions, $post ) {
        $post_types = $this->get_setting( 'post_types', array() );

        if ( ! in_array( $post->post_type, $post_types, true ) ) {
            return $actions;
        }

        if ( ! current_user_can( 'edit_post', $post->ID ) ) {
            return $actions;
        }

        $url = wp_nonce_url(
            admin_url( 'admin.php?action=blaminhor_essentials_duplicate_post&post=' . $post->ID ),
            'blaminhor_essentials_duplicate_' . $post->ID
        );

        $actions['blaminhor_essentials_duplicate'] = sprintf(
            '<a href="%s" title="%s">%s</a>',
            esc_url( $url ),
            esc_attr__( 'Duplicate this item', 'blaminhor-essentials' ),
            esc_html__( 'Duplicate', 'blaminhor-essentials' )
        );

        return $actions;
    }

    /**
     * Add duplicate link to taxonomy row actions
     *
     * @param array   $actions Term actions.
     * @param WP_Term $term    Term object.
     * @return array
     */
    public function add_taxonomy_duplicate_link( $actions, $term ) {
        $taxonomies = $this->get_setting( 'taxonomies', array() );

        if ( ! in_array( $term->taxonomy, $taxonomies, true ) ) {
            return $actions;
        }

        if ( ! current_user_can( 'manage_categories' ) ) {
            return $actions;
        }

        $url = wp_nonce_url(
            admin_url( 'admin.php?action=blaminhor_essentials_duplicate_term&term=' . $term->term_id . '&taxonomy=' . $term->taxonomy ),
            'blaminhor_essentials_duplicate_term_' . $term->term_id
        );

        $actions['blaminhor_essentials_duplicate'] = sprintf(
            '<a href="%s" title="%s">%s</a>',
            esc_url( $url ),
            esc_attr__( 'Duplicate this term', 'blaminhor-essentials' ),
            esc_html__( 'Duplicate', 'blaminhor-essentials' )
        );

        return $actions;
    }

    /**
     * Add bulk action
     *
     * @param array $actions Bulk actions.
     * @return array
     */
    public function add_bulk_action( $actions ) {
        $actions['blaminhor_essentials_duplicate'] = __( 'Duplicate', 'blaminhor-essentials' );
        return $actions;
    }

    /**
     * Handle bulk action
     *
     * @param string $redirect_url Redirect URL.
     * @param string $action       Action name.
     * @param array  $post_ids     Post IDs.
     * @return string
     */
    public function handle_bulk_action( $redirect_url, $action, $post_ids ) {
        if ( 'blaminhor_essentials_duplicate' !== $action ) {
            return $redirect_url;
        }

        $duplicated = 0;
        foreach ( $post_ids as $post_id ) {
            if ( $this->create_duplicate_post( $post_id ) ) {
                $duplicated++;
            }
        }

        return add_query_arg( 'blaminhor_essentials_duplicated', $duplicated, $redirect_url );
    }

    /**
     * Duplicate post action handler
     */
    public function duplicate_post() {
        $post_id = isset( $_GET['post'] ) ? absint( $_GET['post'] ) : 0;

        if ( ! $post_id ) {
            wp_die( esc_html__( 'No post to duplicate.', 'blaminhor-essentials' ) );
        }

        // Verify nonce
        if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'blaminhor_essentials_duplicate_' . $post_id ) ) {
            wp_die( esc_html__( 'Security check failed.', 'blaminhor-essentials' ) );
        }

        // Check permissions
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            wp_die( esc_html__( 'You do not have permission to duplicate this post.', 'blaminhor-essentials' ) );
        }

        $new_post_id = $this->create_duplicate_post( $post_id );

        if ( is_wp_error( $new_post_id ) ) {
            wp_die( esc_html( $new_post_id->get_error_message() ) );
        }

        // Redirect
        $redirect = $this->get_setting( 'redirect_after', 'edit' );

        if ( 'edit' === $redirect ) {
            $url = admin_url( 'post.php?action=edit&post=' . $new_post_id );
        } else {
            $post_type = get_post_type( $post_id );
            $url       = admin_url( 'edit.php?post_type=' . $post_type . '&blaminhor_essentials_duplicated=1' );
        }

        wp_safe_redirect( $url );
        exit;
    }

    /**
     * Create duplicate post
     *
     * @param int $post_id Post ID to duplicate.
     * @return int|WP_Error New post ID or error.
     */
    public function create_duplicate_post( $post_id ) {
        $post = get_post( $post_id );

        if ( ! $post ) {
            return new WP_Error( 'post_not_found', __( 'Post not found.', 'blaminhor-essentials' ) );
        }

        // Build new post data
        $new_post = array(
            'post_type'      => $post->post_type,
            'post_content'   => $post->post_content,
            'post_excerpt'   => $post->post_excerpt,
            'post_parent'    => $post->post_parent,
            'post_password'  => $post->post_password,
            'comment_status' => $post->comment_status,
            'ping_status'    => $post->ping_status,
            'menu_order'     => $post->menu_order,
            'post_mime_type' => $post->post_mime_type,
        );

        // Title
        $title_prefix = $this->get_setting( 'title_prefix', '' );
        $title_suffix = $this->get_setting( 'title_suffix', __( ' - copy', 'blaminhor-essentials' ) );
        $new_post['post_title'] = $title_prefix . $post->post_title . $title_suffix;

        // Status
        $new_post['post_status'] = $this->get_setting( 'copy_status', 'draft' );

        // Author
        if ( $this->get_setting( 'copy_author', true ) ) {
            $new_post['post_author'] = $post->post_author;
        } else {
            $new_post['post_author'] = get_current_user_id();
        }

        // Date
        if ( $this->get_setting( 'copy_date', false ) ) {
            $new_post['post_date']     = $post->post_date;
            $new_post['post_date_gmt'] = $post->post_date_gmt;
        }

        // Insert new post
        $new_post_id = wp_insert_post( $new_post, true );

        if ( is_wp_error( $new_post_id ) ) {
            return $new_post_id;
        }

        // Copy taxonomies
        if ( $this->get_setting( 'copy_taxonomies', true ) ) {
            $this->copy_post_taxonomies( $post_id, $new_post_id );
        }

        // Copy meta
        if ( $this->get_setting( 'copy_meta', true ) ) {
            $this->copy_post_meta( $post_id, $new_post_id );
        }

        // Copy comments
        if ( $this->get_setting( 'copy_comments', false ) ) {
            $this->copy_post_comments( $post_id, $new_post_id );
        }

        // Copy children (for hierarchical posts)
        if ( $this->get_setting( 'copy_children', false ) ) {
            $this->copy_post_children( $post_id, $new_post_id );
        }

        /**
         * Action after post duplication
         *
         * @param int     $new_post_id New post ID.
         * @param int     $post_id     Original post ID.
         * @param WP_Post $post        Original post object.
         */
        do_action( 'blaminhor_essentials_after_duplicate_post', $new_post_id, $post_id, $post );

        return $new_post_id;
    }

    /**
     * Copy post taxonomies
     *
     * @param int $source_id Source post ID.
     * @param int $target_id Target post ID.
     */
    private function copy_post_taxonomies( $source_id, $target_id ) {
        $taxonomies = get_object_taxonomies( get_post_type( $source_id ) );

        foreach ( $taxonomies as $taxonomy ) {
            $terms = wp_get_object_terms( $source_id, $taxonomy, array( 'fields' => 'ids' ) );
            if ( ! is_wp_error( $terms ) && ! empty( $terms ) ) {
                wp_set_object_terms( $target_id, $terms, $taxonomy );
            }
        }
    }

    /**
     * Copy post meta
     *
     * Uses direct database query to preserve exact data encoding (important for page builders like Elementor).
     *
     * @param int $source_id Source post ID.
     * @param int $target_id Target post ID.
     */
    private function copy_post_meta( $source_id, $target_id ) {
        global $wpdb;

        // Meta keys to exclude (internal WordPress + generated CSS that contains post IDs)
        $excluded = apply_filters( 'blaminhor_essentials_excluded_meta_keys', array(
            '_edit_lock',
            '_edit_last',
            '_wp_old_slug',
            '_wp_old_date',
            // Page builder generated CSS (contains post ID references, will be regenerated)
            '_elementor_css',
            '_fl_builder_draft_css',
            '_fl_builder_css',
            '_fl_builder_css_position',
            '_brizy_compiled_css',
        ) );

        // Build exclusion placeholders
        $excluded_placeholders = implode( ',', array_fill( 0, count( $excluded ), '%s' ) );

        // Get raw meta data directly from database to preserve exact encoding
        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $source_meta = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT meta_key, meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key NOT IN ($excluded_placeholders)",
                array_merge( array( $source_id ), $excluded )
            )
        );
        // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared

        // Copy each meta entry directly to preserve encoding
        foreach ( $source_meta as $meta ) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
            $wpdb->insert(
                $wpdb->postmeta,
                array(
                    'post_id'    => $target_id,
                    'meta_key'   => $meta->meta_key,
                    'meta_value' => $meta->meta_value,
                ),
                array( '%d', '%s', '%s' )
            );
        }

        // Trigger page builder CSS regeneration
        $this->trigger_page_builder_regeneration( $target_id );
    }

    /**
     * Trigger page builder CSS regeneration for the duplicated post
     *
     * @param int $post_id New post ID.
     */
    private function trigger_page_builder_regeneration( $post_id ) {
        // Elementor: Clear CSS cache to force regeneration
        if ( class_exists( '\Elementor\Plugin' ) ) {
            // Mark CSS as outdated - Elementor will regenerate on next view
            delete_post_meta( $post_id, '_elementor_css' );

            // Use Elementor's CSS class if available
            if ( class_exists( '\Elementor\Core\Files\CSS\Post' ) ) {
                $css_file = new \Elementor\Core\Files\CSS\Post( $post_id );
                $css_file->delete();
            }
        }

        // Beaver Builder: Clear CSS cache
        if ( class_exists( 'FLBuilderModel' ) ) {
            delete_post_meta( $post_id, '_fl_builder_draft_css' );
            delete_post_meta( $post_id, '_fl_builder_css' );
        }

        // Brizy: Clear compiled CSS
        if ( class_exists( 'Brizy_Editor_Post' ) ) {
            delete_post_meta( $post_id, '_brizy_compiled_css' );
        }

        // Divi/Extra: Clear CSS cache
        if ( function_exists( 'et_core_clear_wp_cache' ) ) {
            et_core_clear_wp_cache( $post_id );
        }

        // WPBakery (Visual Composer): No special handling needed, uses inline CSS

        // Oxygen Builder: Clear CSS cache
        if ( function_exists( 'oxygen_vsb_cache_universal_css' ) ) {
            delete_post_meta( $post_id, 'ct_css_cache' );
        }

        // Allow other plugins to hook into post duplication
        do_action( 'blaminhor_essentials_duplicator_regenerate_css', $post_id );
    }

    /**
     * Copy post comments
     *
     * @param int $source_id Source post ID.
     * @param int $target_id Target post ID.
     */
    private function copy_post_comments( $source_id, $target_id ) {
        $comments = get_comments( array(
            'post_id' => $source_id,
            'status'  => 'all',
        ) );

        foreach ( $comments as $comment ) {
            $comment_data = array(
                'comment_post_ID'      => $target_id,
                'comment_author'       => $comment->comment_author,
                'comment_author_email' => $comment->comment_author_email,
                'comment_author_url'   => $comment->comment_author_url,
                'comment_author_IP'    => $comment->comment_author_IP,
                'comment_date'         => $comment->comment_date,
                'comment_date_gmt'     => $comment->comment_date_gmt,
                'comment_content'      => $comment->comment_content,
                'comment_approved'     => $comment->comment_approved,
                'comment_agent'        => $comment->comment_agent,
                'comment_type'         => $comment->comment_type,
                'comment_parent'       => $comment->comment_parent,
                'user_id'              => $comment->user_id,
            );

            wp_insert_comment( $comment_data );
        }
    }

    /**
     * Copy post children
     *
     * @param int $source_id Source post ID.
     * @param int $target_id Target post ID.
     */
    private function copy_post_children( $source_id, $target_id ) {
        $children = get_children( array(
            'post_parent' => $source_id,
            'post_type'   => 'any',
        ) );

        foreach ( $children as $child ) {
            $new_child_id = $this->create_duplicate_post( $child->ID );
            if ( ! is_wp_error( $new_child_id ) ) {
                wp_update_post( array(
                    'ID'          => $new_child_id,
                    'post_parent' => $target_id,
                ) );
            }
        }
    }

    /**
     * Duplicate term action handler
     */
    public function duplicate_term() {
        $term_id  = isset( $_GET['term'] ) ? absint( $_GET['term'] ) : 0;
        $taxonomy = isset( $_GET['taxonomy'] ) ? sanitize_key( $_GET['taxonomy'] ) : '';

        if ( ! $term_id || ! $taxonomy ) {
            wp_die( esc_html__( 'Invalid term or taxonomy.', 'blaminhor-essentials' ) );
        }

        // Verify nonce
        if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'blaminhor_essentials_duplicate_term_' . $term_id ) ) {
            wp_die( esc_html__( 'Security check failed.', 'blaminhor-essentials' ) );
        }

        // Check permissions
        if ( ! current_user_can( 'manage_categories' ) ) {
            wp_die( esc_html__( 'You do not have permission to duplicate this term.', 'blaminhor-essentials' ) );
        }

        $new_term_id = $this->create_duplicate_term( $term_id, $taxonomy );

        if ( is_wp_error( $new_term_id ) ) {
            wp_die( esc_html( $new_term_id->get_error_message() ) );
        }

        // Redirect
        $url = admin_url( 'edit-tags.php?taxonomy=' . $taxonomy . '&blaminhor_essentials_duplicated=1' );
        wp_safe_redirect( $url );
        exit;
    }

    /**
     * Create duplicate term
     *
     * @param int    $term_id  Term ID to duplicate.
     * @param string $taxonomy Taxonomy name.
     * @return int|WP_Error New term ID or error.
     */
    public function create_duplicate_term( $term_id, $taxonomy ) {
        $term = get_term( $term_id, $taxonomy );

        if ( ! $term || is_wp_error( $term ) ) {
            return new WP_Error( 'term_not_found', __( 'Term not found.', 'blaminhor-essentials' ) );
        }

        // Build new term name
        $title_prefix = $this->get_setting( 'title_prefix', '' );
        $title_suffix = $this->get_setting( 'title_suffix', __( ' - copy', 'blaminhor-essentials' ) );
        $new_name     = $title_prefix . $term->name . $title_suffix;

        // Insert new term
        $new_term = wp_insert_term( $new_name, $taxonomy, array(
            'description' => $term->description,
            'parent'      => $term->parent,
        ) );

        if ( is_wp_error( $new_term ) ) {
            return $new_term;
        }

        $new_term_id = $new_term['term_id'];

        // Copy term meta
        $meta = get_term_meta( $term_id );
        foreach ( $meta as $key => $values ) {
            foreach ( $values as $value ) {
                add_term_meta( $new_term_id, $key, maybe_unserialize( $value ) );
            }
        }

        /**
         * Action after term duplication
         *
         * @param int     $new_term_id New term ID.
         * @param int     $term_id     Original term ID.
         * @param WP_Term $term        Original term object.
         */
        do_action( 'blaminhor_essentials_after_duplicate_term', $new_term_id, $term_id, $term );

        return $new_term_id;
    }

    /**
     * Add admin bar link
     *
     * @param WP_Admin_Bar $admin_bar Admin bar object.
     */
    public function add_admin_bar_link( $admin_bar ) {
        if ( ! is_admin() || ! is_singular() ) {
            return;
        }

        global $post;

        if ( ! $post ) {
            return;
        }

        $post_types = $this->get_setting( 'post_types', array() );
        if ( ! in_array( $post->post_type, $post_types, true ) ) {
            return;
        }

        if ( ! current_user_can( 'edit_post', $post->ID ) ) {
            return;
        }

        $url = wp_nonce_url(
            admin_url( 'admin.php?action=blaminhor_essentials_duplicate_post&post=' . $post->ID ),
            'blaminhor_essentials_duplicate_' . $post->ID
        );

        $admin_bar->add_node( array(
            'id'    => 'blaminhor-essentials-duplicate',
            'title' => __( 'Duplicate', 'blaminhor-essentials' ),
            'href'  => $url,
            'meta'  => array(
                'title' => __( 'Duplicate this post', 'blaminhor-essentials' ),
            ),
        ) );
    }

    /**
     * Show admin notices
     */
    public function show_notices() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display notice only, no data modification
        if ( isset( $_GET['blaminhor_essentials_duplicated'] ) ) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $count = absint( $_GET['blaminhor_essentials_duplicated'] );
            if ( $count > 0 ) {
                printf(
                    '<div class="notice notice-success is-dismissible"><p>%s</p></div>',
                    esc_html( sprintf(
                        /* translators: %d: Number of items duplicated */
                        _n(
                            '%d item duplicated successfully.',
                            '%d items duplicated successfully.',
                            $count,
                            'blaminhor-essentials'
                        ),
                        $count
                    ) )
                );
            }
        }
    }

    /**
     * Process settings
     *
     * @param array $data Form data.
     */
    protected function process_settings( $data ) {
        // WordPress slashes $_POST automatically. Unslash once recursively so
        // sanitize_* calls below receive clean input and apostrophes do not
        // accumulate backslashes across successive saves.
        $data = wp_unslash( $data );

        $settings = array();

        // Post types
        $settings['post_types'] = array();
        if ( isset( $data['post_types'] ) && is_array( $data['post_types'] ) ) {
            $settings['post_types'] = array_map( 'sanitize_key', $data['post_types'] );
        }

        // Taxonomies
        $settings['taxonomies'] = array();
        if ( isset( $data['taxonomies'] ) && is_array( $data['taxonomies'] ) ) {
            $settings['taxonomies'] = array_map( 'sanitize_key', $data['taxonomies'] );
        }

        // Title options
        $settings['title_prefix'] = isset( $data['title_prefix'] ) ? sanitize_text_field( $data['title_prefix'] ) : '';
        $settings['title_suffix'] = isset( $data['title_suffix'] ) ? sanitize_text_field( $data['title_suffix'] ) : '';

        // Copy options
        $settings['copy_status']     = isset( $data['copy_status'] ) ? sanitize_key( $data['copy_status'] ) : 'draft';
        $settings['copy_author']     = isset( $data['copy_author'] );
        $settings['copy_date']       = isset( $data['copy_date'] );
        $settings['copy_taxonomies'] = isset( $data['copy_taxonomies'] );
        $settings['copy_meta']       = isset( $data['copy_meta'] );
        $settings['copy_children']   = isset( $data['copy_children'] );
        $settings['copy_comments']   = isset( $data['copy_comments'] );

        // Redirect
        $settings['redirect_after'] = isset( $data['redirect_after'] ) ? sanitize_key( $data['redirect_after'] ) : 'edit';

        $this->save_settings( $settings );

        add_action( 'admin_notices', function() {
            blaminhor_essentials_admin_notice( __( 'Settings saved.', 'blaminhor-essentials' ), 'success' );
        });
    }

    /**
     * Render settings page
     */
    public function render_settings_page() {
        $post_types  = blaminhor_essentials_get_post_types();
        $taxonomies  = blaminhor_essentials_get_taxonomies();
        $enabled_pts = $this->get_setting( 'post_types', array( 'post', 'page' ) );
        $enabled_tax = $this->get_setting( 'taxonomies', array( 'category', 'post_tag' ) );
        ?>
        <div class="wrap blaminhor-essentials-wrap blaminhor-essentials-duplicator-settings">
            <div class="blaminhor-essentials-header">
                <h1><?php esc_html_e( 'Content Duplicator', 'blaminhor-essentials' ); ?></h1>
                <p class="blaminhor-essentials-tagline"><?php esc_html_e( 'Configure duplication settings for posts and taxonomies.', 'blaminhor-essentials' ); ?></p>
            </div>

            <div class="blaminhor-essentials-section blaminhor-essentials-settings">
                <form method="post" action="">
                    <?php $this->render_nonce_field(); ?>

                    <!-- Post Types -->
                    <div class="settings-section">
                        <h3><?php esc_html_e( 'Enabled Post Types', 'blaminhor-essentials' ); ?></h3>
                        <p class="description"><?php esc_html_e( 'Select which post types can be duplicated.', 'blaminhor-essentials' ); ?></p>
                        <div class="duplicator-post-types">
                            <?php foreach ( $post_types as $pt ) : ?>
                            <label>
                                <input type="checkbox"
                                       name="post_types[]"
                                       value="<?php echo esc_attr( $pt->name ); ?>"
                                       <?php checked( in_array( $pt->name, $enabled_pts, true ) ); ?>>
                                <?php echo esc_html( $pt->labels->singular_name ); ?>
                            </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Taxonomies -->
                    <div class="settings-section">
                        <h3><?php esc_html_e( 'Enabled Taxonomies', 'blaminhor-essentials' ); ?></h3>
                        <p class="description"><?php esc_html_e( 'Select which taxonomies can be duplicated.', 'blaminhor-essentials' ); ?></p>
                        <div class="duplicator-post-types">
                            <?php foreach ( $taxonomies as $tax ) : ?>
                            <label>
                                <input type="checkbox"
                                       name="taxonomies[]"
                                       value="<?php echo esc_attr( $tax->name ); ?>"
                                       <?php checked( in_array( $tax->name, $enabled_tax, true ) ); ?>>
                                <?php echo esc_html( $tax->labels->singular_name ); ?>
                            </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Title Options -->
                    <div class="settings-section">
                        <h3><?php esc_html_e( 'Title Options', 'blaminhor-essentials' ); ?></h3>
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="title_prefix"><?php esc_html_e( 'Title Prefix', 'blaminhor-essentials' ); ?></label>
                                </th>
                                <td>
                                    <input type="text"
                                           id="title_prefix"
                                           name="title_prefix"
                                           value="<?php echo esc_attr( $this->get_setting( 'title_prefix', '' ) ); ?>"
                                           class="regular-text">
                                    <p class="description"><?php esc_html_e( 'Text to add before the original title.', 'blaminhor-essentials' ); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="title_suffix"><?php esc_html_e( 'Title Suffix', 'blaminhor-essentials' ); ?></label>
                                </th>
                                <td>
                                    <input type="text"
                                           id="title_suffix"
                                           name="title_suffix"
                                           value="<?php echo esc_attr( $this->get_setting( 'title_suffix', __( ' (Copy)', 'blaminhor-essentials' ) ) ); ?>"
                                           class="regular-text">
                                    <p class="description"><?php esc_html_e( 'Text to add after the original title.', 'blaminhor-essentials' ); ?></p>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <!-- Copy Options -->
                    <div class="settings-section">
                        <h3><?php esc_html_e( 'Copy Options', 'blaminhor-essentials' ); ?></h3>
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="copy_status"><?php esc_html_e( 'Post Status', 'blaminhor-essentials' ); ?></label>
                                </th>
                                <td>
                                    <select id="copy_status" name="copy_status">
                                        <option value="draft" <?php selected( $this->get_setting( 'copy_status' ), 'draft' ); ?>><?php esc_html_e( 'Draft', 'blaminhor-essentials' ); ?></option>
                                        <option value="publish" <?php selected( $this->get_setting( 'copy_status' ), 'publish' ); ?>><?php esc_html_e( 'Published', 'blaminhor-essentials' ); ?></option>
                                        <option value="pending" <?php selected( $this->get_setting( 'copy_status' ), 'pending' ); ?>><?php esc_html_e( 'Pending Review', 'blaminhor-essentials' ); ?></option>
                                        <option value="private" <?php selected( $this->get_setting( 'copy_status' ), 'private' ); ?>><?php esc_html_e( 'Private', 'blaminhor-essentials' ); ?></option>
                                    </select>
                                    <p class="description"><?php esc_html_e( 'Status for the duplicated post.', 'blaminhor-essentials' ); ?></p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row"><?php esc_html_e( 'What to Copy', 'blaminhor-essentials' ); ?></th>
                                <td>
                                    <fieldset>
                                        <label>
                                            <input type="checkbox" name="copy_author" <?php checked( $this->get_setting( 'copy_author', true ) ); ?>>
                                            <?php esc_html_e( 'Original author', 'blaminhor-essentials' ); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="copy_date" <?php checked( $this->get_setting( 'copy_date', false ) ); ?>>
                                            <?php esc_html_e( 'Original date', 'blaminhor-essentials' ); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="copy_taxonomies" <?php checked( $this->get_setting( 'copy_taxonomies', true ) ); ?>>
                                            <?php esc_html_e( 'Taxonomies (categories, tags, etc.)', 'blaminhor-essentials' ); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="copy_meta" <?php checked( $this->get_setting( 'copy_meta', true ) ); ?>>
                                            <?php esc_html_e( 'Custom fields (post meta)', 'blaminhor-essentials' ); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="copy_children" <?php checked( $this->get_setting( 'copy_children', false ) ); ?>>
                                            <?php esc_html_e( 'Child posts (for hierarchical types)', 'blaminhor-essentials' ); ?>
                                        </label><br>
                                        <label>
                                            <input type="checkbox" name="copy_comments" <?php checked( $this->get_setting( 'copy_comments', false ) ); ?>>
                                            <?php esc_html_e( 'Comments', 'blaminhor-essentials' ); ?>
                                        </label>
                                    </fieldset>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <!-- Redirect Option -->
                    <div class="settings-section">
                        <h3><?php esc_html_e( 'After Duplication', 'blaminhor-essentials' ); ?></h3>
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="redirect_after"><?php esc_html_e( 'Redirect To', 'blaminhor-essentials' ); ?></label>
                                </th>
                                <td>
                                    <select id="redirect_after" name="redirect_after">
                                        <option value="edit" <?php selected( $this->get_setting( 'redirect_after' ), 'edit' ); ?>><?php esc_html_e( 'Edit screen of new post', 'blaminhor-essentials' ); ?></option>
                                        <option value="list" <?php selected( $this->get_setting( 'redirect_after' ), 'list' ); ?>><?php esc_html_e( 'Post list', 'blaminhor-essentials' ); ?></option>
                                    </select>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <p class="submit">
                        <button type="submit" class="button button-primary"><?php esc_html_e( 'Save Settings', 'blaminhor-essentials' ); ?></button>
                    </p>
                </form>
            </div>
        </div>
        <?php
    }
}
