<?php
/**
 * Plugin Name: Clone & Duplicate Posts
 * Description: Duplicate WordPress posts, pages and custom post types with a single click
 * Version: 1.0.0
 * Author: Alexei Haberli
 * Author URI: https://fullstackdev.es/
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: clone-duplicate-posts
*/


if (!defined('ABSPATH')) exit;

// Function to clone post data
function clone_duplicate_post_action(){
    // Verify and sanitize input
    $post_id = isset($_GET['post']) ? absint($_GET['post']) : 0;
    $nonce = isset($_GET['clone_duplicate_nonce']) ? sanitize_text_field(wp_unslash($_GET['clone_duplicate_nonce'])) : '';

    // Verify nonce
    if (!wp_verify_nonce($nonce, 'clone_duplicate_post_' . $post_id)) {
        wp_die('Unauthorized action');
    }

    // Check permissions
    if (!current_user_can('edit_posts')) {
        wp_die('You do not have permissions');
    }

    // Verify post exists
    if (!$post_id) {
        wp_die('Post not found');
    }

    $post = get_post ($post_id);

    if (!$post) {
        wp_die('Post not found');
    }

    $nuevo_post = array(
        'post_title'   => $post->post_title . ' (Copy)',
        'post_content' => $post->post_content,
        'post_status'  => 'draft',
        'post_type'    => $post->post_type,
    );

    $nuevo_id = wp_insert_post($nuevo_post);


    // Copy taxonomies (categories, tags, etc.)
    $taxonomias = get_object_taxonomies($post->post_type);
    foreach ($taxonomias as $taxonomia) {
        $terminos = wp_get_object_terms($post_id, $taxonomia, array('fields' => 'ids'));
        wp_set_object_terms($nuevo_id, $terminos, $taxonomia);
    }

    // Copy featured image
    $thumbnail_id = get_post_thumbnail_id($post_id);
    if ($thumbnail_id) {
        set_post_thumbnail($nuevo_id, $thumbnail_id);
    }

    // Copy custom fields
    $post_meta = get_post_meta($post_id);
    foreach ($post_meta as $key => $values) {
        foreach ($values as $value) {
            add_post_meta($nuevo_id, $key, maybe_unserialize($value));
        }
    }


     wp_safe_redirect(
        add_query_arg(
            array(
                'post' => $nuevo_id,
                'action' => 'edit'
            ),
            admin_url('post.php')
        )
    );
    exit;

}

add_action('admin_action_clone_duplicate_post', 'clone_duplicate_post_action');



// Admin buttons


// Add clone link in posts list
function clone_duplicate_post_link($actions, $post) {
    $nonce = wp_create_nonce('clone_duplicate_post_' . $post->ID);
    $url = admin_url('admin.php?action=clone_duplicate_post&post=' . $post->ID . '&clone_duplicate_nonce=' . $nonce);
    $actions['clone_duplicate'] = '<a href="' . $url . '">Clone</a>';
    return $actions;
}

add_filter('post_row_actions', 'clone_duplicate_post_link', 10, 2);
add_filter('page_row_actions', 'clone_duplicate_post_link', 10, 2);



// Metabox button in editor
function clone_duplicate_post_metabox() {
    // Get all public post types
    $post_types = get_post_types(array('public' => true), 'names');
    
    foreach ($post_types as $post_type) {
        add_meta_box(
            'clone_duplicate_post_box',
            'Clone',
            'clone_duplicate_post_metabox_html',
            $post_type,
            'side',
            'high'
        );
    }
}
add_action('add_meta_boxes', 'clone_duplicate_post_metabox');

function clone_duplicate_post_metabox_html($post) {
    $nonce = wp_create_nonce('clone_duplicate_post_' . $post->ID);
    $post_type_object = get_post_type_object($post->post_type);
    $label = $post_type_object ? $post_type_object->labels->singular_name : 'Post';
    ?>
    <a href="<?php echo esc_url(admin_url('admin.php?action=clone_duplicate_post&post=' . $post->ID . '&clone_duplicate_nonce=' . $nonce)); ?>"
       class="button button-primary button-large"
       style="width: 100%; text-align: center;">
        Clone this <?php echo esc_html($label); ?>
    </a>
    <?php
}