<?php
/**
 * Plugin Name: Easy GPT for WP
 * Plugin URI: https://easygptforwp.com/
 * Description: Integrates GPT models (OpenAI, DeepSeek, Gemini) to generate articles, translate posts automatically, and optimize SEO — all from your WordPress dashboard.
 * Version: 1.38
 * Author: Ignacio Gil Alvarez
 * Author URI: https://morris34.com/
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

// Prevent direct access to this file.
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

define('EASY_GPT_PLUGIN_VERSION', '1.18');

/**
 * Start adding specific functions of the plugin here.
 */

// Load administrative functions if we are in the admin area.
if (is_admin()) {
    require_once plugin_dir_path(__FILE__) . 'admin/admin-functions.php';
}

// Load settings functions
require_once plugin_dir_path(__FILE__) . 'includes/settings-functions.php';

// Load frontend functions
require_once plugin_dir_path(__FILE__) . 'public/public-functions.php';

// Incluir las funciones de las páginas How to Use y Support
require_once plugin_dir_path(__FILE__) . 'includes/how-to-use.php';
require_once plugin_dir_path(__FILE__) . 'includes/support.php';
require_once plugin_dir_path(__FILE__) . 'includes/license.php';
require_once plugin_dir_path(__FILE__) . 'includes/cost.php';
require_once plugin_dir_path(__FILE__) . 'includes/metaboxes.php';
require_once plugin_dir_path(__FILE__) . 'includes/bulk-generation.php';
require_once plugin_dir_path(__FILE__) . 'includes/bulk-list.php';
require_once plugin_dir_path(__FILE__) . 'includes/easy-gpt-bulk-article-generator.php';
require_once plugin_dir_path(__FILE__) . 'includes/bulk-article-processing.php';
require_once plugin_dir_path(__FILE__) . 'includes/comments.php';
require_once plugin_dir_path(__FILE__) . 'includes/status.php';
require_once plugin_dir_path(__FILE__) . 'includes/easy-gpt-refresh-page.php';
require_once plugin_dir_path(__FILE__) . 'includes/easy-gpt-refresh-processing.php';
require_once plugin_dir_path(__FILE__) . 'includes/easy-gpt-translations.php';
require_once plugin_dir_path(__FILE__) . 'includes/easy-gpt-translation-processing.php';
require_once plugin_dir_path(__FILE__) . 'includes/welcome-popup.php';


// Activation and deactivation hooks.
function easy_gpt_for_wordpress_activate() {
    // Code to run upon activation.
    easy_gpt_create_tables();
	easy_gpt_create_moderation_log_table();
    easy_gpt_schedule_cron_jobs();
    
    update_option('easy_gpt_plugin_version', EASY_GPT_PLUGIN_VERSION);
}
register_activation_hook(__FILE__, 'easy_gpt_for_wordpress_activate');

function easy_gpt_for_wordpress_deactivate() {
    // Code to run upon deactivation.
    easy_gpt_unschedule_cron_jobs();
}
register_deactivation_hook(__FILE__, 'easy_gpt_for_wordpress_deactivate');

function easy_gpt_custom_upload_mimes($mimes) {
    // Permitir formatos de imagen adicionales
    $mimes['jpg|jpeg|jpe'] = 'image/jpeg';
    $mimes['png'] = 'image/png';
    $mimes['gif'] = 'image/gif';
    $mimes['bmp'] = 'image/bmp';
    $mimes['tiff|tif'] = 'image/tiff';
    $mimes['ico'] = 'image/x-icon';
    return $mimes;
}
add_filter('upload_mimes', 'easy_gpt_custom_upload_mimes');

function easy_gpt_create_tables() {
    global $wpdb;
    $charset_collate = $wpdb->get_charset_collate();
    $table_name = $wpdb->prefix . 'bulk_generations';

    $sql = "CREATE TABLE $table_name (
      id int(11) NOT NULL AUTO_INCREMENT,
      user_id bigint(20) UNSIGNED NOT NULL,
      prompt text NOT NULL,
      keywords text NOT NULL,
      date_created datetime DEFAULT CURRENT_TIMESTAMP,
      status varchar(50) DEFAULT 'pending',
      num_articles int(11) DEFAULT 1,
      articles_generated int(11) DEFAULT 0,
      total_cost decimal(10,2) DEFAULT 0.00,
      model varchar(255) DEFAULT NULL,
      temperature float DEFAULT 0.7,
      language varchar(10) DEFAULT 'en',
      min_words int(11) DEFAULT 300,
      max_words int(11) DEFAULT 1000,
      num_subheadings int(11) DEFAULT 3,
      subheading_types varchar(255) DEFAULT NULL,
      format_article tinyint(1) DEFAULT 0,
      include_links tinyint(1) DEFAULT 0,
      include_bibliography tinyint(1) DEFAULT 0,
      auto_categories tinyint(1) DEFAULT 0,
      auto_tags tinyint(1) DEFAULT 0,
      enable_seo tinyint(1) DEFAULT 0,
      writing_style varchar(255) DEFAULT NULL,
      writing_tone varchar(255) DEFAULT NULL,
      include_excerpt tinyint(1) DEFAULT 0,
      image_model varchar(255) DEFAULT NULL,
      auto_images tinyint(1) DEFAULT 0,
      num_images int(11) DEFAULT 1,
      image_size varchar(255) DEFAULT NULL,
      image_quality varchar(255) DEFAULT NULL,
      image_style varchar(255) DEFAULT NULL,
      set_featured_image tinyint(1) DEFAULT 0,
      specific_instructions_title text DEFAULT NULL,
      use_specific_title_instructions tinyint(1) DEFAULT 0,
      use_same_specific_title_instructions tinyint(1) DEFAULT 0,
      specific_instructions_outline text DEFAULT NULL,
      use_same_specific_outline_instructions tinyint(1) DEFAULT 0,
      specific_instructions_content text DEFAULT NULL,
      use_same_specific_content_instructions tinyint(1) DEFAULT 0,
      specific_instructions_excerpt text DEFAULT NULL,
      use_same_specific_excerpt_instructions tinyint(1) DEFAULT 0,
      image_prompts text DEFAULT NULL,
      use_same_image_prompts text DEFAULT NULL,
      publish_action varchar(20) DEFAULT 'draft',
      publish_frequency varchar(20) DEFAULT 'once',
      start_date date DEFAULT NULL,
      start_time time DEFAULT NULL,
      articles_per_interval int(11) DEFAULT 1,
      is_product tinyint(1) DEFAULT 0,  -- Nuevo campo
      generate_with_prices tinyint(1) DEFAULT 0, -- Nuevo campo
      price_list text DEFAULT NULL, -- Nuevo campo
      include_videos_bulk tinyint(1) DEFAULT 0, -- Nuevo campo
      video_position_bulk varchar(50) DEFAULT 'end', -- Nuevo campo
      video_paragraph_bulk int(11) DEFAULT 3, -- Nuevo campo
	  include_citations_bulk tinyint(1) DEFAULT 0,
	  final_review_bulk tinyint(1) DEFAULT 0,
	  minutes_between_articles int(11) DEFAULT 0,
	  just_in_time_generation tinyint(1) DEFAULT 0,
      PRIMARY KEY  (id)
    ) $charset_collate;";
    
    $table_name2 = $wpdb->prefix . 'article_generation_tasks';
    $sql2 = "CREATE TABLE $table_name2 (
      id int(11) NOT NULL AUTO_INCREMENT,
      generation_id int(11) NOT NULL,
      article_params TEXT NOT NULL,
      status ENUM('pending', 'processing', 'completed', 'failed', 'cancelled') NOT NULL DEFAULT 'pending',
      cost DECIMAL(10,2) DEFAULT 0.00,
      created_at DATETIME NOT NULL,
      updated_at DATETIME DEFAULT NULL,
	  error_message TEXT DEFAULT NULL,
	  scheduled_for DATETIME DEFAULT NULL,
      PRIMARY KEY (id)
    ) $charset_collate;";

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    dbDelta($sql2);

	$table_name3 = $wpdb->prefix . 'easy_gpt_refresh_log';
	$sql3 = "CREATE TABLE $table_name3 (
	  id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
	  post_id BIGINT(20) UNSIGNED NOT NULL,
	  post_title TEXT,
	  refresh_time DATETIME NOT NULL,
	  updated_images TINYINT(1) DEFAULT 0,
	  new_images_added INT DEFAULT 0,
	  replaced_featured TINYINT(1) DEFAULT 0,
	  updated_youtube TINYINT(1) DEFAULT 0,
	  updated_seo TINYINT(1) DEFAULT 0,
	  updated_post_date TINYINT(1) DEFAULT 0,
	  model_used VARCHAR(100),
	  refresh_cost DECIMAL(10,4) DEFAULT 0.0000,
	  status VARCHAR(20) DEFAULT 'success',
	  error_message TEXT,
	  PRIMARY KEY (id)
	) $charset_collate;";

	dbDelta($sql3);

	$table_name4 = $wpdb->prefix . 'easy_gpt_translations';
	$sql4 = "CREATE TABLE $table_name4 (
		id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
		original_post_id BIGINT UNSIGNED NOT NULL,
		translated_post_id BIGINT UNSIGNED DEFAULT NULL,
		original_language VARCHAR(10) NOT NULL,
		target_language VARCHAR(10) NOT NULL,
		translated_title TEXT DEFAULT NULL,
		cost_usd DECIMAL(10,5) DEFAULT 0.00,
		status VARCHAR(20) DEFAULT 'pending',
		date_translated DATETIME DEFAULT CURRENT_TIMESTAMP
	) $charset_collate;";

	dbDelta($sql4);

    // **Verificar y agregar nuevas columnas si faltan**
    $existing_columns = $wpdb->get_results("SHOW COLUMNS FROM $table_name", ARRAY_A);
    $columns = array_column($existing_columns, 'Field');

    $alter_queries = [];

    if (!in_array('content_type', $columns)) {
        $alter_queries[] = "ADD COLUMN content_type varchar(50) DEFAULT 'article'";
    }
    if (!in_array('enable_product_prices', $columns)) {
        $alter_queries[] = "ADD COLUMN enable_product_prices tinyint(1) DEFAULT 0";
    }
    if (!in_array('product_prices', $columns)) {
        $alter_queries[] = "ADD COLUMN product_prices text DEFAULT NULL";
    }

    if (!in_array('include_videos_bulk', $columns)) {
        $alter_queries[] = "ADD COLUMN include_videos_bulk tinyint(1) DEFAULT 0";
    }
    if (!in_array('video_position_bulk', $columns)) {
        $alter_queries[] = "ADD COLUMN video_position_bulk varchar(50) DEFAULT 'end'";
    }
    if (!in_array('video_paragraph_bulk', $columns)) {
        $alter_queries[] = "ADD COLUMN video_paragraph_bulk int(11) DEFAULT 3";
    }
	
	if (!in_array('include_citations_bulk', $columns)) {
		$alter_queries[] = "ADD COLUMN include_citations_bulk tinyint(1) DEFAULT 0";
	}
	if (!in_array('final_review_bulk', $columns)) {
		$alter_queries[] = "ADD COLUMN final_review_bulk tinyint(1) DEFAULT 0";
	}

	if (!in_array('minutes_between_articles', $columns)) {
		$alter_queries[] = "ADD COLUMN minutes_between_articles int(11) DEFAULT 0";
	}

	if (!in_array('just_in_time_generation', $columns)) {
		$alter_queries[] = "ADD COLUMN just_in_time_generation tinyint(1) DEFAULT 0";
	}

    if (!empty($alter_queries)) {
        $wpdb->query("ALTER TABLE $table_name " . implode(", ", $alter_queries));
    }

    $existing_columns2 = $wpdb->get_results("SHOW COLUMNS FROM $table_name2", ARRAY_A);
    $columns2 = array_column($existing_columns, 'Field');

    if (!in_array('error_message', $columns2)) {
        $wpdb->query("ALTER TABLE $table_name2 ADD COLUMN error_message TEXT DEFAULT NULL");
    }

	if (!in_array('scheduled_for', $columns2)) {
		$wpdb->query("ALTER TABLE $table_name2 ADD COLUMN scheduled_for DATETIME DEFAULT NULL");
	}

	$existing_columns3 = $wpdb->get_results("SHOW COLUMNS FROM $table_name3", ARRAY_A);
	$columns3 = array_column($existing_columns3, 'Field');

	if (!in_array('refresh_cost', $columns3)) {
		$wpdb->query("ALTER TABLE $table_name3 ADD COLUMN refresh_cost DECIMAL(10,4) DEFAULT 0.0000");
	}
}


// Function to schedule cron jobs
function easy_gpt_schedule_cron_jobs() {
    if (!wp_next_scheduled('easy_gpt_process_pending_generations')) {
        wp_schedule_event(time(), 'five_minutes', 'easy_gpt_process_pending_generations');
    }
}

// Function to unschedule cron jobs
function easy_gpt_unschedule_cron_jobs() {
    $timestamp = wp_next_scheduled('easy_gpt_process_pending_generations');
    if ($timestamp) {
        wp_unschedule_event($timestamp, 'easy_gpt_process_pending_generations');
    }
}

function easy_gpt_check_for_updates() {
    $installed_version = get_option('easy_gpt_plugin_version');

    if ($installed_version !== EASY_GPT_PLUGIN_VERSION) {
        // Ejecutar actualizaciones si hay una nueva versión
        easy_gpt_create_tables(); // Asegura que las columnas nuevas se agreguen
        update_option('easy_gpt_plugin_version', EASY_GPT_PLUGIN_VERSION);
    }
}
add_action('admin_init', 'easy_gpt_check_for_updates');

add_action('admin_footer-plugins.php', 'easy_gpt_deactivate_feedback_modal');

function easy_gpt_deactivate_feedback_modal() {
    ?>
    <style>
    #easy-gpt-feedback-modal {
        position: fixed;
        z-index: 9999;
        top: 0; left: 0; right: 0; bottom: 0;
        background: rgba(0,0,0,0.4);
        display: none;
        justify-content: center;
        align-items: center;
    }

    #easy-gpt-feedback-modal.show {
        display: flex !important;
    }

    #easy-gpt-feedback-box {
        background: #fff;
        padding: 24px;
        border-radius: 12px;
        width: 100%;
        max-width: 480px;
        box-shadow: 0 8px 24px rgba(0,0,0,0.2);
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
        position: relative;
        animation: fadeIn 0.2s ease-in-out;
        box-sizing: border-box;
    }

    #easy-gpt-feedback-box h2 {
        margin-top: 0;
        font-size: 18px;
        margin-bottom: 16px;
    }

    .easy-gpt-feedback-btn {
        display: block;
        width: 100%;
        margin: 6px 0;
        padding: 10px 14px;
        border: 1px solid #ccc;
        background: #f9f9f9;
        border-radius: 6px;
        cursor: pointer;
        text-align: left;
        transition: background 0.2s ease;
    }

    .easy-gpt-feedback-btn:hover {
        background: #eef1f5;
    }

    #easy-gpt-modal-close {
        position: absolute;
        top: 10px;
        right: 12px;
        font-size: 18px;
        cursor: pointer;
        color: #666;
    }

    #easy-gpt-modal-close:hover {
        color: #000;
    }

    @keyframes fadeIn {
        from { opacity: 0; transform: scale(0.95); }
        to { opacity: 1; transform: scale(1); }
    }
    </style>

    <div id="easy-gpt-feedback-modal">
        <div id="easy-gpt-feedback-box">
            <div id="easy-gpt-modal-close" title="Close">✖️</div>
			<h2>Why are you deactivating Easy GPT for WP?</h2>
			<p style="background: #ecf9f1; border-left: 4px solid #2ecc71; padding: 10px 14px; font-size: 13px; margin-bottom: 16px;">
				<strong>💡 Looking for a 100% free solution?</strong><br>
				Try <a href="https://nocostaiwriter.com" target="_blank"><strong>No Cost AI Writer</strong></a> – no license, no API required.<br>
				Includes WordPress export, bulk generation, scheduling and translations.
			</p>
			<p style="font-size: 14px; color: #555; margin-top: -10px; margin-bottom: 16px;">
				We value your feedback and may improve based on it.
			</p>
            <button class="easy-gpt-feedback-btn" data-reason="It's just a temporary deactivation">1️⃣ Temporary deactivation</button>
            <button class="easy-gpt-feedback-btn" data-reason="I don't have the API">2️⃣ I don't have the API</button>
            <button class="easy-gpt-feedback-btn" data-reason="I don't like the results">3️⃣ I don't like the results</button>
            <button class="easy-gpt-feedback-btn" data-reason="I don't want to pay">4️⃣ I don't want to pay</button>
            <button class="easy-gpt-feedback-btn" data-reason="It's too expensive">5️⃣ It's too expensive</button>
            <button class="easy-gpt-feedback-btn" data-reason="The plugin is too complicated">6️⃣ Too complicated</button>
            <button class="easy-gpt-feedback-btn" data-reason="I'm switching to another AI tool">7️⃣ Switching to another AI tool</button>
            <button class="easy-gpt-feedback-btn" data-reason="Performance issues (slow, errors, etc.)">8️⃣ Performance issues</button>
            <button class="easy-gpt-feedback-btn" data-reason="Other">9️⃣ Other (please specify)</button>
        </div>
    </div>

    <script>
    jQuery(document).ready(function($) {
        let easyGptDeactivateHref = '';

        // Mostrar el modal al hacer clic en desactivar
        $(document).on('click', '#deactivate-easy-gpt-for-wp', function(e) {
            e.preventDefault();
            easyGptDeactivateHref = $(this).attr('href');
            $('#easy-gpt-feedback-modal').addClass('show');
        });

        // Cerrar el modal al hacer clic en ✖️
        $(document).on('click', '#easy-gpt-modal-close', function() {
            $('#easy-gpt-feedback-modal').removeClass('show');
        });

        // Enviar feedback
        $(document).on('click', '.easy-gpt-feedback-btn', function() {
            let reason = $(this).data('reason');

			// Preguntar detalles para ciertas opciones
			if (reason === 'Other') {
				let details = prompt("Please provide more details:");
				if (details) {
					reason += " - " + details;
				} else {
					return;
				}
			}

			if (reason.includes("Performance issues")) {
				let details = prompt("Could you describe the issue you experienced?");
				if (details) {
					reason += " - Details: " + details;
				}
			}


            $.post(ajaxurl, {
                action: 'easy_gpt_send_uninstall_email',
                reason: reason
            }, function() {
                $('#easy-gpt-feedback-modal').removeClass('show');
                setTimeout(function() {
                    window.location.href = easyGptDeactivateHref;
                }, 50);
            });
        });
    });
    </script>
    <?php
}



add_action('wp_ajax_easy_gpt_send_uninstall_email', 'easy_gpt_send_uninstall_email');

function easy_gpt_send_uninstall_email() {
    if (!isset($_POST['reason'])) {
        wp_die();
    }

    $reason = sanitize_text_field($_POST['reason']);

    // Obtener datos del usuario actual
    $current_user = wp_get_current_user();
    $user_email   = $current_user->user_email;
    $user_name    = $current_user->display_name ?: $current_user->user_login;

    // Información del sitio
    $site_url = get_site_url();

    // Datos del correo
    $to       = 'contact@easygptforwp.com';
    $subject  = "📌 Easy GPT – User feedback on plugin deactivation";
    $headers  = array('Reply-To: ' . $user_name . ' <' . $user_email . '>');

    $message  = "A user is deactivating the Easy GPT for WP plugin.\n\n";
    $message .= "🔹 Reason: {$reason}\n";
    $message .= "👤 User: {$user_name} ({$user_email})\n";
    $message .= "🌐 Site: {$site_url}\n";
    $message .= "\n📩 This message was automatically generated.";

    wp_mail($to, $subject, $message, $headers);

    wp_die();
}


register_activation_hook(__FILE__, function() {
    add_option('easy_gpt_show_welcome_popup', true);
});

add_action( 'admin_init', function(){
    $opts = get_option( 'easy_gpt_options', [] );
    $fields = [
        'easy_gpt_format_article',      // Formatear artículo
        'easy_gpt_auto_images',         // Automatically Generate Images
        'easy_gpt_set_featured_image',  // Set First Generated Image as Featured
        'easy_gpt_auto_tags',           // Set tags automáticamente
        'easy_gpt_include_links',       // Incluir links
        'easy_gpt_include_bibliography',// Incluir bibliografía
        'easy_gpt_include_excerpt',     // Incluir extracto
        'easy_gpt_include_citations',   // Incluir citas
        'easy_gpt_final_review',        // Revisión final
    ];

    foreach ( $fields as $field ) {
        $value = isset( $opts[ $field ] ) ? $opts[ $field ] : null;
        error_log( "[DEBUG] {$field} = " . var_export( $value, true ) );
    }
} );


?>