<?php
/*
Plugin Name: Suscripción a comentarios
Description: Permite al usuario suscribirse a los comentarios
Version: 1.0
Author: Yo
*/
// Activation hook
register_activation_hook(__FILE__, 'comment_subscription_plugin_activate');
// Deactivation hook
register_deactivation_hook(__FILE__, 'comment_subscription_plugin_deactivate');
// Initialize the plugin
add_action('plugins_loaded', 'comment_subscription_plugin_init');
function comment_subscription_plugin_activate() {
    global $wpdb;
    $table_name = $wpdb->prefix . 'subscriptions';
$wpdb->query("
  CREATE TABLE IF NOT EXISTS $table_name (
    id mediumint(9) NOT NULL AUTO_INCREMENT,
    comment_id mediumint(9) NOT NULL,
    email varchar(255) NOT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY comment_id (comment_id, email)
  ) $wpdb->charset $wpdb->collate;
");
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}
function comment_subscription_plugin_deactivate() {
    // Verifica si el plugin se desactiva manualmente o debido a la desinstalación
    if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) {
        return;
    }
    global $wpdb;
    $table_name = $wpdb->prefix . 'comment_subscriptions';
    $wpdb->query("DROP TABLE IF EXISTS $table_name");
}
function comment_subscription_plugin_init() {
    // Add checkbox to comment form
    add_filter('comment_form_default_fields', 'comment_subscription_plugin_add_checkbox');
    add_action('comment_post', 'comment_subscription_plugin_save_subscription');
    // Process subscription
    add_action('wp_loaded', 'comment_subscription_plugin_process_subscription');
}
function comment_subscription_plugin_save_subscription($comment_id) {
    if (isset($_POST['subscribe_to_comments']) && $_POST['subscribe_to_comments'] == 1) {
        $email = sanitize_email($_POST['email']);
        $post_id = get_comment($comment_id)->comment_post_ID;
        if (!empty($email) && is_email($email)) {
            global $wpdb;
            $table_name = $wpdb->prefix . 'comment_subscriptions';
            // Comprobar si el usuario ya está suscrito con el mismo correo a este post
            $existing_subscription = $wpdb->get_row(
                $wpdb->prepare("SELECT * FROM $table_name WHERE email = %s AND post_id = %d", $email, $post_id)
            );
            if (!$existing_subscription) {
                // Insertar una nueva suscripción si no existe una suscripción con el mismo correo para este post
                    $wpdb->insert(
                $table_name,
                array(
                    'post_id' => $post_id,
                    'email' => $email,
                    'registration_date' => current_time('mysql', 1), // Agrega la fecha de registro
                ),
                array('%d', '%s', '%s')
            );
            }
        }
    }
}
function comment_subscription_plugin_process_subscription() {
    if (isset($_GET['unsubscribe_comment']) && isset($_GET['email'])) {
        $post_id = get_comment($_GET['unsubscribe_comment'])->comment_post_ID;
        $email = sanitize_email($_GET['email']);
        if (!empty($email) && is_email($email)) {
            global $wpdb;
            $table_name = $wpdb->prefix . 'comment_subscriptions';
            $wpdb->delete(
                $table_name,
                array(
                    'post_id' => $post_id,
                    'email' => $email,
                ),
                array('%d', '%s')
            );
            echo 'Has eliminado con éxito su suscripción a los comentarios de este post.';
            exit;
        }
    }
}
// ...
function comment_subscription_plugin_notify_subscribers($comment_id, $comment_approved) {
    if ($comment_approved == 1) {
        $post_id = get_comment($comment_id)->comment_post_ID;
        $comment_permalink = get_comment_link($comment_id);
        $post_title = get_the_title($post_id);
        global $wpdb;
        $table_name = $wpdb->prefix . 'comment_subscriptions';
        $subscribers = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE post_id = %d", $post_id));
        if (!empty($subscribers)) {
        $subject = "Nuevo comentario en $post_title";
        $message = "Se ha publicado un nuevo comentario en el artículo: $post_title:\n\n";
            $message .= "Ver el comentario en el siguiente enlace: {$comment_permalink}\n\n";
            foreach ($subscribers as $subscriber) {
                $unsubscribe_link = add_query_arg(
                    array(
                        'unsubscribe_comment' => $comment_id,
                        'email' => urlencode($subscriber->email),
                    ),
                    home_url()
                );
                $unsubscribe_message = "\n\nPara cancelar la suscripción a este artículo, haga clic en el siguiente enlace: {$unsubscribe_link}";
                wp_mail($subscriber->email, $subject, $message . $unsubscribe_message);
            }
        }
    }
}
add_action('comment_post', 'comment_subscription_plugin_notify_subscribers', 10, 2);
//Agrega casilla de suscripción automáticamente al formulario de comentarios
function comment_subscription_plugin_add_checkbox($fields) {
    $fields['subscribe_to_comments'] = '<p class="comment-form-subscribe"><label for="subscribe_to_comments"><input type="checkbox" id="subscribe_to_comments" name="subscribe_to_comments" value="1" />Suscribirme para recibir respuestas a mi correo</label></p>';
    return $fields;
}
//Agrega casilla de suscripción manualmente al formulario de comentarios
function comment_subscription_plugin_add_checkbox_to_comments($args) {
    ?>
<p class="comment-form-subscribe" style="display: block !important;">
    <label for="subscribe_to_comments">
        <div id="subscribe_to_comments_container">
            <input type="checkbox" id="subscribe_to_comments" name="subscribe_to_comments" value="1" class="subscribe_checkbox" <?php checked(isset($_POST['subscribe_to_comments']) && $_POST['subscribe_to_comments'], 1); ?> />
            Suscribirseo.
        </div>
    </label>
</p>
    <?php
}
//Administración de suscriptores
add_action('admin_menu', 'comment_subscription_plugin_menu');
function comment_subscription_plugin_menu() {
    add_menu_page(
        'Subscription Users',
        'Suscripciones',
        'manage_options',
        'comment-subscription-users',
        'comment_subscription_plugin_users_page'
    );
}
function comment_subscription_plugin_users_page() {
    if (!current_user_can('manage_options')) {
        wp_die('No tienes permisos suficientes para acceder a esta página.');
    }
    global $wpdb;
    $table_name = $wpdb->prefix . 'comment_subscriptions';
    // Procesar la eliminación individual
    if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['email'])) {
        $email = sanitize_email($_GET['email']);
        if (!empty($email) && is_email($email)) {
            $wpdb->delete($table_name, array('email' => $email));
            echo '<div class="updated"><p>Todas las suscripciones de ' . esc_html($email) . ' han sido eliminadas con éxito.</p></div>';
        }
    }
    // Obtener la cadena de búsqueda
    $search_term = isset($_GET['s']) ? sanitize_text_field($_GET['s']) : '';
    // Configuración de paginación
    $per_page = 50;
    $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
    $offset = ($current_page - 1) * $per_page;
    // Obtener la lista de usuarios según la cadena de búsqueda y la paginación
    
// Obtener la lista de usuarios según la cadena de búsqueda y la paginación
if (!empty($search_term)) {
    $users = $wpdb->get_results(
        $wpdb->prepare("SELECT DISTINCT email FROM $table_name WHERE email LIKE %s ORDER BY registration_date DESC LIMIT %d, %d", '%' . like_escape($search_term) . '%', $offset, $per_page)
    );
    $total_users = $wpdb->get_var($wpdb->prepare("SELECT COUNT(DISTINCT email) FROM $table_name WHERE email LIKE %s", '%' . like_escape($search_term) . '%'));
} else {
    $users = $wpdb->get_results("SELECT DISTINCT email FROM $table_name ORDER BY registration_date DESC LIMIT $offset, $per_page");
    $total_users = $wpdb->get_var("SELECT COUNT(DISTINCT email) FROM $table_name");
}
    echo '<div class="wrap">';
    
// Obtener la cantidad de usuarios suscritos
$total_subscribers = $wpdb->get_var("SELECT COUNT(DISTINCT email) FROM $table_name");
// Mostrar el título con la cantidad de usuarios suscritos
echo '<h2>Usuarios suscritos <small>(' . esc_html($total_subscribers) . ')</small></h2>';
    // Formulario de búsqueda
    echo '<form method="get">';
    echo '<input type="hidden" name="page" value="comment-subscription-users" />';
    echo '<input type="text" name="s" placeholder="Buscar por correo electrónico" value="' . esc_attr($search_term) . '" />';
    echo '<input type="submit" class="button" value="Buscar" />';
    echo '</form>';
    echo '<style>';
    echo '.responsive-table { width: 100%; border-collapse: collapse; }';
    echo '.responsive-table th, .responsive-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }';
    echo '</style>';
    // Mostrar la tabla de usuarios paginada
    if (!empty($users)) {
        echo '<table class="responsive-table">';
        echo '<tr><th>Email</th><th>Posts Suscritos</th><th>Acciones</th></tr>';
        foreach ($users as $user) {
            echo '<tr>';
            echo '<td>' . esc_html($user->email) . '</td>';
            echo '<td>';
            // Mostrar los posts suscritos en una lista desordenada (ul)
            echo '<ul>';
            $post_ids = $wpdb->get_col($wpdb->prepare("SELECT post_id FROM $table_name WHERE email = %s", $user->email));
            foreach ($post_ids as $post_id) {
                $post_title = get_the_title($post_id);
                echo '<li>' . esc_html($post_title) . '</li>';
            }
            echo '</ul>';
            echo '</td>';
            echo '<td><a href="?page=comment-subscription-users&action=delete&email=' . urlencode($user->email) . '">Eliminar</a></td>';
            echo '</tr>';
        }
        echo '</table>';
        // Paginación
        echo '<div class="tablenav">';
        echo '<div class="tablenav-pages">';
        echo paginate_links(array(
            'base' => add_query_arg('paged', '%#%'),
            'format' => '',
            'prev_text' => __('« Anterior'),
            'next_text' => __('Siguiente »'),
            'total' => ceil($total_users / $per_page),
            'current' => $current_page,
        ));
        echo '</div>';
        echo '</div>';
    } else {
        echo '<p>No se encontraron usuarios.</p>';
    }
    echo '</div>';
}