<?php
/*-----------------------------------------------*/
/*  EXTHEM.ES
/*  PREMIUM WORDRESS THEMES
/*
/*  STOP DON'T TRY EDIT
/*  IF YOU DON'T KNOW PHP 
/*
/*  As Errors In Your Themes
/*  Are Not The Responsibility
/*  Of The DEVELOPERS
/*  @EXTHEM.ES
/*  
/*  Follow Social Media Exthem.es
/*  Youtube : https://www.youtube.com/channel/UCpcZNXk6ySLtwRSBN6fVyLA
/*  Facebook : https://www.facebook.com/groups/exthem.es
/*  Twitter : https://x.com/bangreyblog
/*  Instagram : https://www.instagram.com/exthem.es/
/*  Telegram : https://t.me/exthemes_helps
/*  TikTok : https://www.tiktok.com/@exthemes
/*	More Premium Themes Visit Now On https://exthem.es/
/*-----------------------------------------------*/
if ( ! defined( 'ABSPATH' ) ) exit; 
// Silence is golden.
add_action('wp_dashboard_setup', function () {
    if (!current_user_can('manage_options')) return;

    wp_add_dashboard_widget(
        'delete_duplicate_posts_widget',
        'Delete Duplicate Posts & Pages',
        'dashboard_widget_delete_duplicates'
    );

    // Fully responsive inline CSS
    add_action('admin_head', function () {
        if (get_current_screen()->id !== 'dashboard') return;
        echo '<style>
            .dup-widget { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; line-height: 1.6; }
            .dup-count { font-size: 28px; color: #d63638; font-weight: bold; }
            .dup-buttons { margin: 20px 0; display: flex; flex-wrap: wrap; gap: 12px; align-items: center; }
            .dup-btn { padding: 12px 20px; border: none; border-radius: 6px; font-size: 15px; font-weight: bold; cursor: pointer; text-decoration: none; display: inline-block; }
            .dup-preview-btn { background: #2271b1; color: white; }
            .dup-delete-btn { background: #d63638; color: white; }
            .dup-modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.75); z-index: 99999; overflow-y: auto; padding: 20px 0; box-sizing: border-box; }
            .dup-modal-content { background: white; margin: 0 auto; max-width: 96%; width: 1100px; border-radius: 12px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); position: relative; }
            .dup-close { position: absolute; top: 10px; right: 20px; font-size: 36px; font-weight: bold; color: #aaa; cursor: pointer; z-index: 10; }
            .dup-close:hover { color: #000; }
            .dup-modal-header { padding: 30px 30px 10px; border-bottom: 1px solid #eee; }
            .dup-modal-body { padding: 20px 30px 40px; }
            table.dup-table { width: 100%; border-collapse: collapse; font-size: 14px; margin: 20px 0; }
            table.dup-table th { background: #2271b1; color: white; padding: 14px 10px; text-align: left; font-weight: 600; }
            table.dup-table td { padding: 12px 10px; border-bottom: 1px solid #eee; word-wrap: break-word; }
            .dup-keep { background: #f0fff0 !important; }
            .dup-delete { background: #fff0f0 !important; }
            .dup-action { font-weight: bold; white-space: nowrap; }
            .dup-legend { margin: 15px 0; font-size: 15px; }
            .dup-legend span { display: inline-block; padding: 6px 12px; border-radius: 4px; margin-right: 15px; font-weight: bold; }
            .dup-keep-legend { background: #d4edda; color: #155724; }
            .dup-delete-legend { background: #f8d7da; color: #721c24; }

            /* Responsive table */
            @media (max-width: 782px) {
                .dup-count { font-size: 22px; }
                .dup-buttons { flex-direction: column; gap: 10px; }
                .dup-btn { width: 100%; text-align: center; padding: 16px; font-size: 16px; }
                table.dup-table, table.dup-table thead, table.dup-table tbody, table.dup-table th, table.dup-table td, table.dup-table tr { display: block; }
                table.dup-table thead tr { position: absolute; top: -9999px; left: -9999px; }
                table.dup-table tr { border: 1px solid #ddd; margin-bottom: 15px; border-radius: 8px; overflow: hidden; }
                table.dup-table td { border: none; position: relative; padding-left: 50% !important; text-align: right; }
                table.dup-table td:before { content: attr(data-label); position: absolute; left: 12px; width: 45%; font-weight: bold; text-align: left; color: #555; }
                .dup-modal-content { margin: 20px auto; padding: 20px; }
                .dup-close { top: 8px; right: 15px; font-size: 32px; }
            }
        </style>';
    });

    // Modal open/close
    add_action('admin_footer', function () {
        if (get_current_screen()->id !== 'dashboard') return;
        echo '<script>
            jQuery(function($){
                $("#show-dup-preview").on("click", function(){ $(".dup-modal").fadeIn(300); });
                $(document).on("click", ".dup-close, .dup-modal", function(e){
                    if (e.target === this || $(e.target).hasClass("dup-close")) $(".dup-modal").fadeOut(300);
                });
            });
        </script>';
    });
});

function dashboard_widget_delete_duplicates() {
    global $wpdb;
    $notice = '';

    // Your original safe deletion
    if (isset($_POST['delete_duplicates']) && wp_verify_nonce($_POST['dup_nonce'], 'delete_duplicates_action') && $_POST['confirm_delete'] === '1') {
        $deleted = $wpdb->query("
            DELETE p1 FROM {$wpdb->posts} p1
            INNER JOIN {$wpdb->posts} p2 ON p1.ID > p2.ID
            WHERE p1.post_title = p2.post_title
              AND p1.post_content = p2.post_content
              AND p1.post_status = p2.post_status
              AND p1.post_type = p2.post_type
              AND p1.post_type IN ('post', 'page')
        ");
        $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id NOT IN (SELECT ID FROM {$wpdb->posts})");
        $wpdb->query("DELETE FROM {$wpdb->term_relationships} WHERE object_id NOT IN (SELECT ID FROM {$wpdb->posts})");
        $wpdb->query("DELETE FROM {$wpdb->comments} WHERE comment_post_ID NOT IN (SELECT ID FROM {$wpdb->posts})");
        foreach (['category','post_tag'] as $tax) {
            $terms = get_terms(['taxonomy'=>$tax,'fields'=>'ids','hide_empty'=>false]);
            if ($terms && !is_wp_error($terms)) wp_update_term_count_now($terms, $tax);
        }
        wp_cache_flush();
        $notice = '<div class="notice notice-success is-dismissible"><p><strong>' . intval($deleted) . ' duplicates permanently deleted!</strong></p></div>';
    }

    // Count duplicates
    $count = (int) $wpdb->get_var("
        SELECT COUNT(*) FROM (
            SELECT 1 FROM {$wpdb->posts} p1
            INNER JOIN {$wpdb->posts} p2 ON p1.ID > p2.ID
            WHERE p1.post_title = p2.post_title
              AND p1.post_content = p2.post_content
              AND p1.post_status = p2.post_status
              AND p1.post_type = p2.post_type
              AND p1.post_type IN ('post', 'page')
        ) AS t
    ");

    echo '<div class="dup-widget">';
    echo $notice;
    echo '<p><strong>Duplicates found:</strong> <span class="dup-count">' . number_format($count) . '</span></p>';
    echo '<p><em>Keeps oldest copy • Compares title + content + status + type</em></p>';

    if ($count > 0) {
        echo '<div class="dup-buttons">
                <button type="button" id="show-dup-preview" class="dup-btn dup-preview-btn">Preview Duplicates</button>
              </div>';

        echo '<form method="post" onsubmit="return confirm(\'PERMANENTLY DELETE ALL ' . $count . ' DUPLICATES?\n\nDid you backup your database?\n\nThis cannot be undone!\');">
                ' . wp_nonce_field('delete_duplicates_action', 'dup_nonce', true, false) . '
                <p><label><input type="checkbox" name="confirm_delete" value="1" required> I have backed up my database and understand this is permanent</label></p>
                <p><input type="submit" name="delete_duplicates" class="dup-btn dup-delete-btn" value="Permanently Delete All ' . number_format($count) . ' Duplicates"></p>
              </form>';
    } else {
        echo '<p style="color:green;font-weight:bold;font-size:20px;">No duplicates found — your site is clean!</p>';
    }

    // RESPONSIVE PREVIEW MODAL
    echo '<div class="dup-modal">
            <div class="dup-modal-content">
                <span class="dup-close">×</span>
                <div class="dup-modal-header">
                    <h2>Duplicate Preview</h2>
                    <div class="dup-legend">
                        <span class="dup-keep-legend">Kept (oldest copy)</span>
                        <span class="dup-delete-legend">Will be deleted</span>
                    </div>
                </div>
                <div class="dup-modal-body">';

    $rows = $wpdb->get_results("
        SELECT p1.ID as del_id, p1.post_title, p1.post_type, p1.post_status, p1.post_date,
               p2.ID as keep_id, p2.post_date as keep_date
        FROM {$wpdb->posts} p1
        INNER JOIN {$wpdb->posts} p2 ON p1.ID > p2.ID
        WHERE p1.post_title = p2.post_title
          AND p1.post_content = p2.post_content
          AND p1.post_status = p2.post_status
          AND p1.post_type = p2.post_type
          AND p1.post_type IN ('post', 'page')
        ORDER BY p1.post_title
        LIMIT 600
    ");

    if ($rows) {
        echo '<table class="dup-table">
            <thead><tr>
                <th>Title</th><th>Type</th><th>Status</th><th>Date</th><th>ID</th><th class="dup-action">Action</th>
            </tr></thead><tbody>';

        foreach ($rows as $r) {
            $title = $r->post_title ? esc_html($r->post_title) : '(No title)';
            echo "<tr class='dup-delete'>
                <td data-label='Title'><a href='" . get_edit_post_link($r->del_id) . "' target='_blank'>$title</a></td>
                <td data-label='Type'>{$r->post_type}</td>
                <td data-label='Status'>{$r->post_status}</td>
                <td data-label='Date'>{$r->post_date}</td>
                <td data-label='ID'>{$r->del_id}</td>
                <td data-label='Action' class='dup-action'>Will be deleted</td>
            </tr>
            <tr class='dup-keep'>
                <td data-label='Title'><a href='" . get_edit_post_link($r->keep_id) . "' target='_blank'>$title</a></td>
                <td data-label='Type'>{$r->post_type}</td>
                <td data-label='Status'>{$r->post_status}</td>
                <td data-label='Date'>{$r->keep_date}</td>
                <td data-label='ID'>{$r->keep_id}</td>
                <td data-label='Action' class='dup-action'>Kept (oldest)</td>
            </tr>";
        }
        echo '</tbody></table>';
        echo '<p><em>Showing first 300 duplicate pairs • Total: ' . number_format($count) . '</em></p>';
    } else {
        echo '<p>No duplicates found.</p>';
    }

    echo '      </div>
            </div>
          </div>';

    echo '<hr><small><strong>Safety:</strong> Always backup first • Keeps oldest copy • One-click permanent delete</small></div>';
}