<?php
/*
Plugin Name: Elementor Page Duplicator
Description: A simple plugin to duplicate Elementor pages and templates.
Version: 1.1
Author: Brandon Harris
*/

// Add a new top-level menu for Elementor Duplicator
function epd_add_admin_menu() {
    add_menu_page(
        'Elementor Duplicator',     // Page title
        'Elementor Duplicator',     // Menu title
        'manage_options',           // Capability
        'epd_mass_duplicate',       // Menu slug
        'epd_mass_duplicate_page',  // Function to display page content
        'dashicons-admin-page',     // Icon
        6                           // Position
    );
}
add_action('admin_menu', 'epd_add_admin_menu');

// Mass Duplicate Page Form
function epd_mass_duplicate_page() {
    ?>
    <div class="wrap">
        <h1>Mass Duplicate Elementor Pages</h1>
        <form method="post" action="">
            <?php wp_nonce_field('epd_mass_duplicate_action', 'epd_mass_duplicate_nonce'); ?>
            
            <label for="epd_page_to_duplicate">Select a page to duplicate:</label>
            <select name="epd_page_to_duplicate" id="epd_page_to_duplicate">
                <?php
                // Get all pages
                $pages = get_pages();
                foreach ($pages as $page) {
                    echo '<option value="' . $page->ID . '">' . esc_html($page->post_title) . '</option>';
                }
                ?>
            </select>
            
            <br><br>
            
            <label for="epd_number_of_copies">How many copies?</label>
            <input type="number" name="epd_number_of_copies" id="epd_number_of_copies" min="1" max="100" value="1">
            
            <br><br>
            
            <input type="submit" name="epd_mass_duplicate_submit" value="Duplicate Pages" class="button button-primary">
        </form>
    </div>
    <?php
}

// Handle Mass Duplication
function epd_handle_mass_duplicate() {
    if (isset($_POST['epd_mass_duplicate_submit'])) {
        // Check the nonce for security
        if (!isset($_POST['epd_mass_duplicate_nonce']) || !wp_verify_nonce($_POST['epd_mass_duplicate_nonce'], 'epd_mass_duplicate_action')) {
            wp_die('Nonce verification failed!');
        }

        // Get the form values
        $page_id = absint($_POST['epd_page_to_duplicate']);
        $number_of_copies = absint($_POST['epd_number_of_copies']);

        if ($page_id && $number_of_copies > 0) {
            // Perform the duplication
            for ($i = 0; $i < $number_of_copies; $i++) {
                epd_duplicate_single_post($page_id);
            }

            // Redirect to the pages list after duplication
            wp_redirect(admin_url('edit.php?post_type=page'));
            exit;
        }
    }
}
add_action('admin_init', 'epd_handle_mass_duplicate');

/**
 * Duplicates a single post by ID
 */
function epd_duplicate_single_post($post_id) {
    global $wpdb;

    $post = get_post($post_id);
    if (isset($post) && $post != null) {
        $current_user = wp_get_current_user();
        $new_post_author = $current_user->ID;

        // Create the new post
        $args = array(
            'comment_status' => $post->comment_status,
            'ping_status'    => $post->ping_status,
            'post_author'    => $new_post_author,
            'post_content'   => $post->post_content,
            'post_excerpt'   => $post->post_excerpt,
            'post_name'      => $post->post_name,
            'post_parent'    => $post->post_parent,
            'post_password'  => $post->post_password,
            'post_status'    => 'draft',
            'post_title'     => $post->post_title . ' (Copy)',
            'post_type'      => $post->post_type,
            'to_ping'        => $post->to_ping,
            'menu_order'     => $post->menu_order
        );

        $new_post_id = wp_insert_post($args);

        // Copy taxonomies
        $taxonomies = get_object_taxonomies($post->post_type);
        foreach ($taxonomies as $taxonomy) {
            $post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs'));
            wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);
        }

        // Copy post meta
        $post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id");
        if (count($post_meta_infos) != 0) {
            $sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) ";
            foreach ($post_meta_infos as $meta_info) {
                $meta_key = $meta_info->meta_key;
                if ($meta_key == '_wp_old_slug') continue;
                $meta_value = addslashes($meta_info->meta_value);
                $sql_query_sel[] = "SELECT $new_post_id, '$meta_key', '$meta_value'";
            }
            $sql_query .= implode(" UNION ALL ", $sql_query_sel);
            $wpdb->query($sql_query);
        }

        return $new_post_id;  // Return the new post ID
    }
}

/**
 * Add the "Duplicate" link to the action list for posts and pages
 */
function epd_duplicate_post_link($actions, $post) {
    if (current_user_can('edit_posts') && in_array($post->post_type, ['post', 'page', 'elementor_library'])) {
        $actions['duplicate'] = '<a href="' . wp_nonce_url('admin.php?action=epd_duplicate_post_as_draft&post=' . $post->ID, basename(__FILE__), 'duplicate_nonce') . '" title="Duplicate this item" rel="permalink">Duplicate</a>';
    }
    return $actions;
}
add_filter('post_row_actions', 'epd_duplicate_post_link', 10, 2);
add_filter('page_row_actions', 'epd_duplicate_post_link', 10, 2);

/**
 * Handle single duplication when clicking the "Duplicate" link
 */
function epd_duplicate_post_as_draft() {
    if (!isset($_GET['post']) || empty($_GET['post'])) {
        wp_die('No post to duplicate has been supplied!');
    }

    $post_id = absint($_GET['post']);
    epd_duplicate_single_post($post_id);

    // Redirect to the pages list after duplication
    wp_redirect(admin_url('edit.php?post_type=' . get_post_type($post_id)));
    exit;
}
add_action('admin_action_epd_duplicate_post_as_draft', 'epd_duplicate_post_as_draft');
