<?php
/*
Plugin Name: Custom Site Enhancements
Description: A plugin to disable Gutenberg, disable comments, enable SVG and AVIF uploads, change the WordPress login URL, disable theme and plugin updates, and enable page/post duplication with on/off toggles.
Version: 1.4.1
Author: Grok
License: GPL2
*/

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

// Initialize default settings on activation
register_activation_hook(__FILE__, 'cse_activate_plugin');
function cse_activate_plugin() {
    $defaults = [
        'disable_gutenberg' => '1',
        'disable_comments' => '1',
        'enable_svg' => '1',
        'enable_avif' => '1',
        'change_login_url' => '1',
        'custom_login_slug' => 'bw-admin',
        'disable_theme_updates' => '1',
        'enable_duplicate_posts' => '1',
        'disable_plugin_updates' => '1'
    ];
    
    if (!get_option('cse_settings')) {
        update_option('cse_settings', $defaults);
    }
}

// Disable Gutenberg Editor
function cse_disable_gutenberg() {
    $settings = get_option('cse_settings', []);
    if (!empty($settings['disable_gutenberg'])) {
        add_filter('use_block_editor_for_post', '__return_false', 10);
        add_filter('use_block_editor_for_post_type', '__return_false', 10);
        add_filter('use_widgets_block_editor', '__return_false');
        add_action('wp_enqueue_scripts', function() {
            wp_dequeue_style('wp-block-library');
            wp_dequeue_style('wp-block-library-theme');
            wp_dequeue_style('global-styles');
            wp_dequeue_style('classic-theme-styles');
        }, 20);
    }
}
add_action('init', 'cse_disable_gutenberg');

// Disable Comments
function cse_disable_comments() {
    $settings = get_option('cse_settings', []);
    if (!empty($settings['disable_comments'])) {
        $post_types = get_post_types(['public' => true], 'names');
        foreach ($post_types as $post_type) {
            add_filter("comments_open_{$post_type}", '__return_false', 20);
            add_filter("pings_open_{$post_type}", '__return_false', 20);
        }
        add_action('admin_menu', function() {
            remove_menu_page('edit-comments.php');
        });
        add_action('admin_init', function() {
            remove_meta_box('commentstatusdiv', 'post', 'normal');
            remove_meta_box('commentstatusdiv', 'page', 'normal');
            remove_meta_box('commentsdiv', 'post', 'normal');
            remove_meta_box('commentsdiv', 'page', 'normal');
        });
        add_filter('block_categories_all', function($categories) {
            return array_filter($categories, function($category) {
                return $category['slug'] !== 'recent-comments';
            });
        });
    }
}
add_action('init', 'cse_disable_comments');

// Enable SVG Upload
function cse_enable_svg_upload($mimes) {
    $settings = get_option('cse_settings', []);
    if (!empty($settings['enable_svg']) && current_user_can('manage_options')) {
        $mimes['svg'] = 'image/svg+xml';
    }
    return $mimes;
}
add_filter('upload_mimes', 'cse_enable_svg_upload');

// Sanitize SVG uploads
function cse_sanitize_svg($file) {
    $settings = get_option('cse_settings', []);
    if (!empty($settings['enable_svg']) && $file['type'] === 'image/svg+xml') {
        $content = file_get_contents($file['tmp_name']);
        if ($content) {
            $content = preg_replace('/<!DOCTYPE[^>]+>/i', '', $content);
            $content = preg_replace('/<\?xml[^>]+>/i', '', $content);
            $content = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $content);
            file_put_contents($file['tmp_name'], $content);
        }
    }
    return $file;
}
add_filter('wp_handle_upload_prefilter', 'cse_sanitize_svg');

// Fix SVG display in admin
function cse_fix_svg_display() {
    $settings = get_option('cse_settings', []);
    if (!empty($settings['enable_svg'])) {
        echo '<style>
            td.media-icon img[src$=".svg"], 
            img[src$=".svg"].attachment-post-thumbnail {
                width: 100% !important;
                height: auto !important;
            }
        </style>';
    }
}
add_action('admin_head', 'cse_fix_svg_display');

// Enable AVIF Upload
function cse_enable_avif_upload($mimes) {
    $settings = get_option('cse_settings', []);
    if (!empty($settings['enable_avif']) && current_user_can('manage_options')) {
        $mimes['avif'] = 'image/avif';
    }
    return $mimes;
}
add_filter('upload_mimes', 'cse_enable_avif_upload');

// Change Login URL
function cse_change_login_url() {
    $settings = get_option('cse_settings', []);
    if (!empty($settings['change_login_url'])) {
        $custom_login_slug = !empty($settings['custom_login_slug']) ? sanitize_title($settings['custom_login_slug']) : 'my-login';
        
        add_action('init', function() use ($custom_login_slug) {
            if (strpos($_SERVER['REQUEST_URI'], 'wp-login.php') !== false && !is_user_logged_in()) {
                wp_redirect(home_url($custom_login_slug));
                exit;
            }
        });
        
        add_filter('login_url', function($login_url, $redirect, $force_reauth) use ($custom_login_slug) {
            return home_url($custom_login_slug);
        }, 10, 3);
        
        add_action('template_redirect', function() use ($custom_login_slug) {
            if (is_user_logged_in() && strpos($_SERVER['REQUEST_URI'], $custom_login_slug) !== false) {
                wp_redirect(admin_url());
                exit;
            }
            
            if (strpos($_SERVER['REQUEST_URI'], $custom_login_slug) !== false) {
                require_once(ABSPATH . 'wp-login.php');
                exit;
            }
        });
    }
}
add_action('init', 'cse_change_login_url');

// Disable Theme Updates
function cse_disable_theme_updates() {
    $settings = get_option('cse_settings', []);
    if (!empty($settings['disable_theme_updates'])) {
        add_filter('site_transient_update_themes', function($value) {
            if (isset($value->response)) {
                $value->response = [];
            }
            return $value;
        });
        add_filter('pre_site_transient_update_themes', '__return_false');
        add_action('admin_init', function() {
            remove_action('admin_notices', 'update_nag', 3);
            remove_action('network_admin_notices', 'update_nag', 3);
        });
    }
}
add_action('init', 'cse_disable_theme_updates');

// Disable Plugin Updates
function cse_disable_plugin_updates() {
    $settings = get_option('cse_settings', []);
    if (!empty($settings['disable_plugin_updates'])) {
        add_filter('site_transient_update_plugins', function($value) {
            if (isset($value->response)) {
                $value->response = [];
            }
            return $value;
        });
        add_filter('pre_site_transient_update_plugins', '__return_false');
        add_action('admin_init', function() {
            remove_action('admin_notices', 'update_nag', 3);
            remove_action('network_admin_notices', 'update_nag', 3);
        });
    }
}
add_action('init', 'cse_disable_plugin_updates');

// Duplicate Page/Post
function cse_duplicate_post() {
    $settings = get_option('cse_settings', []);
    if (!empty($settings['enable_duplicate_posts']) && current_user_can('manage_options')) {
        add_filter('post_row_actions', 'cse_add_duplicate_link', 10, 2);
        add_filter('page_row_actions', 'cse_add_duplicate_link', 10, 2);
        add_action('post_submitbox_misc_actions', 'cse_add_duplicate_button');
        add_action('admin_action_cse_duplicate_post', 'cse_handle_duplicate_post');
    }
}
add_action('admin_init', 'cse_duplicate_post');

// Add duplicate link to post/page list
function cse_add_duplicate_link($actions, $post) {
    if (current_user_can('edit_posts', $post->ID)) {
        $actions['duplicate'] = '<a href="' . wp_nonce_url(admin_url('admin.php?action=cse_duplicate_post&post=' . $post->ID), 'cse_duplicate_' . $post->ID) . '" title="Duplicate this item" rel="permalink">Duplicate</a>';
    }
    return $actions;
}

// Add duplicate button to edit screen
function cse_add_duplicate_button($post) {
    if (current_user_can('edit_posts', $post->ID)) {
        ?>
        <div class="misc-pub-section">
            <a class="button" href="<?php echo wp_nonce_url(admin_url('admin.php?action=cse_duplicate_post&post=' . $post->ID), 'cse_duplicate_' . $post->ID); ?>">Duplicate <?php echo esc_html(get_post_type_object($post->post_type)->labels->singular_name); ?></a>
        </div>
        <?php
    }
}

// Handle post/page duplication
function cse_handle_duplicate_post() {
    if (!isset($_GET['post']) || !isset($_GET['_wpnonce'])) {
        return;
    }
    
    $post_id = intval($_GET['post']);
    if (!wp_verify_nonce($_GET['_wpnonce'], 'cse_duplicate_' . $post_id)) {
        wp_die('Security check failed');
    }
    
    if (!current_user_can('edit_posts', $post_id)) {
        wp_die('Insufficient permissions');
    }
    
    $post = get_post($post_id);
    if (!$post) {
        wp_die('Post not found');
    }
    
    $new_post = [
        'post_title' => $post->post_title . ' (Copy)',
        'post_content' => $post->post_content,
        'post_status' => 'draft',
        'post_type' => $post->post_type,
        'post_author' => get_current_user_id(),
        'post_parent' => $post->post_parent,
        'post_excerpt' => $post->post_excerpt,
        'post_password' => $post->post_password,
        'comment_status' => $post->comment_status,
        'ping_status' => $post->ping_status,
        'menu_order' => $post->menu_order,
    ];
    
    $new_post_id = wp_insert_post($new_post);
    
    if (is_wp_error($new_post_id)) {
        wp_die('Error creating duplicate post');
    }
    
    $meta = get_post_meta($post_id);
    foreach ($meta as $key => $values) {
        foreach ($values as $value) {
            add_post_meta($new_post_id, $key, maybe_unserialize($value));
        }
    }
    
    $taxonomies = get_object_taxonomies($post->post_type);
    foreach ($taxonomies as $taxonomy) {
        $terms = wp_get_object_terms($post_id, $taxonomy, ['fields' => 'slugs']);
        wp_set_object_terms($new_post_id, $terms, $taxonomy);
    }
    
    wp_redirect(admin_url('post.php?action=edit&post=' . $new_post_id));
    exit;
}

// Add settings page
function cse_add_settings_page() {
    add_options_page(
        'Custom Site Enhancements Settings',
        'Site Enhancements',
        'manage_options',
        'cse-settings',
        'cse_render_settings_page'
    );
}
add_action('admin_menu', 'cse_add_settings_page');

// Register settings
function cse_register_settings() {
    register_setting('cse_settings_group', 'cse_settings', [
        'sanitize_callback' => 'cse_sanitize_settings'
    ]);
}
add_action('admin_init', 'cse_register_settings');

// Sanitize settings
function cse_sanitize_settings($input) {
    $sanitized = [];
    $sanitized['disable_gutenberg'] = !empty($input['disable_gutenberg']) ? '1' : '0';
    $sanitized['disable_comments'] = !empty($input['disable_comments']) ? '1' : '0';
    $sanitized['enable_svg'] = !empty($input['enable_svg']) ? '1' : '0';
    $sanitized['enable_avif'] = !empty($input['enable_avif']) ? '1' : '0';
    $sanitized['change_login_url'] = !empty($input['change_login_url']) ? '1' : '0';
    $sanitized['disable_theme_updates'] = !empty($input['disable_theme_updates']) ? '1' : '0';
    $sanitized['enable_duplicate_posts'] = !empty($input['enable_duplicate_posts']) ? '1' : '0';
    $sanitized['disable_plugin_updates'] = !empty($input['disable_plugin_updates']) ? '1' : '0';
    $sanitized['custom_login_slug'] = !empty($input['custom_login_slug']) ? sanitize_title($input['custom_login_slug']) : 'my-login';
    
    // Prevent empty login slug
    if (empty($sanitized['custom_login_slug'])) {
        $sanitized['custom_login_slug'] = 'my-login';
    }
    
    return $sanitized;
}

// Render settings page
function cse_render_settings_page() {
    $settings = get_option('cse_settings', []);
    ?>
    <div class="wrap">
        <h1>Custom Site Enhancements Settings</h1>
        <form method="post" action="options.php">
            <?php
            settings_fields('cse_settings_group');
            do_settings_sections('cse_settings_group');
            ?>
            <table class="form-table">
                <tr>
                    <th scope="row">Disable Gutenberg Editor</th>
                    <td>
                        <input type="checkbox" name="cse_settings[disable_gutenberg]" value="1" <?php checked($settings['disable_gutenberg'], '1'); ?> />
                        <label>Disable Gutenberg and use Classic Editor</label>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Disable Comments</th>
                    <td>
                        <input type="checkbox" name="cse_settings[disable_comments]" value="1" <?php checked($settings['disable_comments'], '1'); ?> />
                        <label>Disable comments on all public post types</label>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Enable SVG Upload</th>
                    <td>
                        <input type="checkbox" name="cse_settings[enable_svg]" value="1" <?php checked($settings['enable_svg'], '1'); ?> />
                        <label>Allow SVG uploads for administrators (with basic sanitization)</label>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Enable AVIF Upload</th>
                    <td>
                        <input type="checkbox" name="cse_settings[enable_avif]" value="1" <?php checked($settings['enable_avif'], '1'); ?> />
                        <label>Allow AVIF uploads for administrators</label>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Change Login URL</th>
                    <td>
                        <input type="checkbox" name="cse_settings[change_login_url]" value="1" <?php checked($settings['change_login_url'], '1'); ?> />
                        <label>Enable custom login URL</label>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Custom Login Slug</th>
                    <td>
                        <input type="text" name="cse_settings[custom_login_slug]" value="<?php echo esc_attr($settings['custom_login_slug']); ?>" />
                        <p class="description">Enter the custom login slug (e.g., "my-login"). Default is "my-login".</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Disable Theme Updates</th>
                    <td>
                        <input type="checkbox" name="cse_settings[disable_theme_updates]" value="1" <?php checked($settings['disable_theme_updates'], '1'); ?> />
                        <label>Disable theme updates and update notifications</label>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Disable Plugin Updates</th>
                    <td>
                        <input type="checkbox" name="cse_settings[disable_plugin_updates]" value="1" <?php checked($settings['disable_plugin_updates'], '1'); ?> />
                        <label>Disable plugin updates and update notifications</label>
                    </td>
                </tr>
                <tr>
                    <th scope="row">Enable Page/Post Duplication</th>
                    <td>
                        <input type="checkbox" name="cse_settings[enable_duplicate_posts]" value="1" <?php checked($settings['enable_duplicate_posts'], '1'); ?> />
                        <label>Enable duplication of pages and posts</label>
                    </td>
                </tr>
            </table>
            <?php submit_button(); ?>
        </form>
    </div>
    <?php
}
?>