<?php
/**
 * File: deactivation-feedback.php
 * Description: Deactivation feedback modal popup with modern, compact, responsive, and centered design (procedural style).
 */

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

/**
 * Modify the Deactivate link on the plugins page.
 */
function ai_content_wizard_modify_deactivate_link($actions, $plugin_file, $plugin_data, $context) {
    if (isset($actions['deactivate'])) {
        $actions['deactivate'] = '<a href="#" class="ai-content-wizard-deactivate-link" data-plugin="' . esc_attr($plugin_file) . '">' . __('Deactivate', 'ai-content-wizard') . '</a>';
    }
    return $actions;
}
add_filter('plugin_action_links_' . plugin_basename(AI_CONTENT_WIZARD_PLUGIN_FILE), 'ai_content_wizard_modify_deactivate_link', 10, 4);

/**
 * Print modal HTML (with inline CSS and JS) in footer of plugins page.
 */
function ai_content_wizard_print_modal_html() {
    ?>
    <!-- Modal Overlay and Modal Markup -->
    <div id="ai-content-wizard-modal-overlay" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.7); z-index: 10000; backdrop-filter: blur(5px);">
        <div id="ai-content-wizard-modal" style="background: #ffffff; width: 90%; max-width: 600px; margin: auto; padding: 25px; border-radius: 12px; box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2); position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%) scale(0.9); opacity: 0; animation: modalFadeIn 0.5s ease forwards;">
            <h2 style="font-size: 22px; color: #4A148C; margin-bottom: 15px; font-weight: bold; display: flex; align-items: center;">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#4A148C" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 8px;">
                    <path d="M12 2L2 22h20L12 2zm0 16v-2m0-4V8"/>
                </svg>
                <?php esc_html_e('Deactivation Feedback', 'ai-content-wizard'); ?>
            </h2>
            <p style="font-size: 14px; color: #616161; margin-bottom: 20px; line-height: 1.4;">
                <?php esc_html_e('Please let us know why you are deactivating AI Content Wizard Lite. Your feedback helps us improve our trial experience!', 'ai-content-wizard'); ?>
            </p>
            <form id="ai-content-wizard-feedback-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" style="transition: all 0.3s;">
                <?php wp_nonce_field('ai_content_wizard_deactivation_feedback_nonce', 'ai_content_wizard_deactivation_feedback_nonce_field'); ?>
                <input type="hidden" name="action" value="ai_content_wizard_deactivation_feedback">
                <input type="hidden" name="plugin" id="ai_content_wizard_plugin_field" value="">
                <input type="hidden" name="skip_feedback" id="ai_content_wizard_skip_feedback" value="0">
                
                <div class="form-columns" style="display: flex; gap: 20px; flex-wrap: wrap;">
                    <div class="column-left" style="flex: 1; min-width: 280px;">
                        <div class="feedback-options" style="background: #f5f7fa; padding: 15px; border-radius: 8px; margin-bottom: 15px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);">
                            <h3 style="font-size: 16px; color: #333; margin-bottom: 12px;"><?php esc_html_e('Why are you deactivating?', 'ai-content-wizard'); ?></h3>
                            <div style="display: flex; flex-direction: column; gap: 10px;">
                                <label class="radio-option" style="display: flex; align-items: center; padding: 8px 12px; background: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0; transition: all 0.3s; cursor: pointer;">
                                    <input type="radio" name="preset_feedback" value="not_useful" style="margin-right: 8px;">
                                    <span><?php esc_html_e('I did not find the trial useful', 'ai-content-wizard'); ?></span>
                                </label>
                                <label class="radio-option" style="display: flex; align-items: center; padding: 8px 12px; background: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0; transition: all 0.3s; cursor: pointer;">
                                    <input type="radio" name="preset_feedback" value="technical_issues" style="margin-right: 8px;">
                                    <span><?php esc_html_e('I encountered technical issues', 'ai-content-wizard'); ?></span>
                                </label>
                                <label class="radio-option" style="display: flex; align-items: center; padding: 8px 12px; background: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0; transition: all 0.3s; cursor: pointer;">
                                    <input type="radio" name="preset_feedback" value="prefer_alternative" style="margin-right: 8px;">
                                    <span><?php esc_html_e('I prefer another solution', 'ai-content-wizard'); ?></span>
                                </label>
                                <label class="radio-option" style="display: flex; align-items: center; padding: 8px 12px; background: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0; transition: all 0.3s; cursor: pointer;">
                                    <input type="radio" name="preset_feedback" value="other" style="margin-right: 8px;">
                                    <span><?php esc_html_e('Other', 'ai-content-wizard'); ?></span>
                                </label>
                            </div>
                        </div>

                        <div id="custom_feedback_container" class="custom-feedback" style="display: none; background: #f5f7fa; padding: 15px; border-radius: 8px; margin-bottom: 15px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05); transition: all 0.3s;">
                            <h3 style="font-size: 16px; color: #333; margin-bottom: 12px;"><?php esc_html_e('Your Feedback', 'ai-content-wizard'); ?></h3>
                            <textarea name="feedback_reason" id="feedback_reason" rows="3" style="width: 100%; padding: 10px; border: 1px solid #e0e0e0; border-radius: 6px; font-size: 14px; color: #333; box-shadow: inset 0 2px 4px rgba(0,0,0,0.05); transition: border-color 0.3s; resize: vertical;" placeholder="<?php esc_attr_e('Please describe your reason for deactivation...', 'ai-content-wizard'); ?>"></textarea>
                        </div>
                    </div>

                    <div class="column-right" style="flex: 1; min-width: 280px;">
                        <div class="data-options" style="background: #f5f7fa; padding: 15px; border-radius: 8px; margin-bottom: 15px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);">
                            <h3 style="font-size: 16px; color: #333; margin-bottom: 12px;"><?php esc_html_e('Data Options', 'ai-content-wizard'); ?></h3>
                            <label class="checkbox-option" style="display: flex; align-items: center; margin-bottom: 10px; padding: 8px 12px; background: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0; transition: all 0.3s; cursor: pointer;">
                                <input type="checkbox" id="delete_tables_main" name="delete_tables_main" value="1" style="margin-right: 8px;">
                                <span><?php esc_html_e('Delete data tables', 'ai-content-wizard'); ?></span>
                            </label>
                            <div id="delete_tables_options" style="margin-left: 25px; display: none; transition: all 0.3s;">
                                <label class="checkbox-option" style="display: flex; align-items: center; margin-bottom: 8px; padding: 6px 10px; background: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0; transition: all 0.3s; cursor: pointer;">
                                    <input type="checkbox" name="delete_tables[]" value="settings" checked style="margin-right: 6px;">
                                    <span><?php esc_html_e('Settings table', 'ai-content-wizard'); ?></span>
                                </label>
                                <label class="checkbox-option" style="display: flex; align-items: center; margin-bottom: 8px; padding: 6px 10px; background: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0; transition: all 0.3s; cursor: pointer;">
                                    <input type="checkbox" name="delete_tables[]" value="posts_logs" checked style="margin-right: 6px;">
                                    <span><?php esc_html_e('Posts logs table', 'ai-content-wizard'); ?></span>
                                </label>
                                <label class="checkbox-option" style="display: flex; align-items: center; padding: 6px 10px; background: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0; transition: all 0.3s; cursor: pointer;">
                                    <input type="checkbox" name="delete_tables[]" value="content_plan_logs" checked style="margin-right: 6px;">
                                    <span><?php esc_html_e('Content plan logs table', 'ai-content-wizard'); ?></span>
                                </label>
                                <label class="checkbox-option" style="display: flex; align-items: center; margin-bottom: 8px; padding: 6px 10px; background: #ffffff; border-radius: 6px; border: 1px solid #e0e0e0; transition: all 0.3s; cursor: pointer;">
                                    <input type="checkbox" name="delete_tables[]" value="content_plan" style="margin-right: 6px;">
                                    <span><?php esc_html_e('Content Plan Table', 'ai-content-wizard'); ?></span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal-actions" style="display: flex; gap: 10px; justify-content: flex-end; flex-wrap: wrap; margin-top: 15px;">
                    <?php submit_button(__('Submit & Deactivate', 'ai-content-wizard'), 'primary', 'submit_feedback', false, ['style' => 'background: #4CAF50; border-color: #4CAF50; padding: 10px 20px; border-radius: 6px; font-size: 14px; transition: all 0.3s;']); ?>
                    <button type="button" id="skip_deactivate" class="button" style="background: #E91E63; color: #ffffff; border: none; padding: 10px 20px; border-radius: 6px; font-size: 14px; transition: all 0.3s; box-shadow: 0 4px 12px rgba(0,233,30,0.3);"><?php esc_html_e('Skip & Deactivate', 'ai-content-wizard'); ?></button>
                    <button type="button" id="ai-content-wizard-modal-close" class="button-secondary" style="background: #B0BEC5; color: #333; border: none; padding: 10px 20px; border-radius: 6px; font-size: 14px; transition: all 0.3s; box-shadow: 0 4px 12px rgba(176,190,197,0.3);"><?php esc_html_e('Cancel', 'ai-content-wizard'); ?></button>
                </div>
            </form>
        </div>
    </div>

    <!-- Inline Styles -->
    <style>
        @keyframes modalFadeIn {
            0% { transform: translate(-50%, -50%) scale(0.9); opacity: 0; }
            100% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
        }

        .ai-content-wizard-deactivate-link {
            cursor: pointer;
            color: #E91E63;
            transition: color 0.3s;
        }

        .ai-content-wizard-deactivate-link:hover {
            color: #C2185B;
        }

        .form-columns {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }

        .radio-option input[type="radio"]:checked + span,
        .checkbox-option input[type="checkbox"]:checked + span {
            color: #4CAF50;
            font-weight: bold;
        }

        .radio-option input[type="radio"]:checked,
        .checkbox-option input[type="checkbox"]:checked {
            accent-color: #4CAF50;
        }

        textarea:focus,
        input:focus {
            border-color: #4CAF50;
            outline: none;
            box-shadow: 0 0 5px rgba(76, 175, 80, 0.5);
        }

        textarea:hover,
        input:hover {
            border-color: #E91E63;
        }

        button:hover,
        .button-primary:hover,
        #skip_deactivate:hover,
        #ai-content-wizard-modal-close:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }

        .button-primary:hover {
            background: #2E7D32;
            border-color: #2E7D32;
        }

        #skip_deactivate:hover {
            background: #C2185B;
        }

        #ai-content-wizard-modal-close:hover {
            background: #90A4AE;
            color: #ffffff;
        }

        #custom_feedback_container.visible,
        #delete_tables_options.visible {
            display: block;
        }

        @media (max-width: 600px) {
            #ai-content-wizard-modal {
                max-width: 90%;
                padding: 15px;
            }

            .form-columns {
                flex-direction: column;
                gap: 10px;
            }

            .column-left, .column-right {
                min-width: auto;
            }

            h2 { font-size: 18px; }
            p { font-size: 12px; }
            .feedback-options, .custom-feedback, .data-options, .license-option { padding: 10px; }
            h3 { font-size: 14px; }
            label { padding: 6px 10px; font-size: 12px; }
            .modal-actions { flex-direction: column; gap: 8px; }
            button, .button-primary, #skip_deactivate, #ai-content-wizard-modal-close { padding: 8px 16px; font-size: 12px; }
        }
    </style>

    <!-- Inline JavaScript -->
    <script type="text/javascript">
        (function($) {
            $(document).ready(function() {
                $('.ai-content-wizard-deactivate-link').on('click', function(e) {
                    e.preventDefault();
                    var plugin = $(this).data('plugin');
                    $('#ai_content_wizard_plugin_field').val(plugin);
                    $('#ai-content-wizard-modal-overlay').fadeIn();
                });

                $('input[name="preset_feedback"]').on('change', function() {
                    if ($(this).val() === 'other') {
                        $('#custom_feedback_container').slideDown().addClass('visible');
                    } else {
                        $('#custom_feedback_container').slideUp().removeClass('visible');
                    }
                });

                $('#delete_tables_main').on('change', function() {
                    if ($(this).is(':checked')) {
                        $('#delete_tables_options').slideDown().addClass('visible');
                        $('#delete_tables_options input[type="checkbox"]').prop('checked', true);
                    } else {
                        $('#delete_tables_options').slideUp().removeClass('visible');
                        $('#delete_tables_options input[type="checkbox"]').prop('checked', false);
                    }
                });

                $('#skip_deactivate').on('click', function() {
                    $('#ai_content_wizard_skip_feedback').val('1');
                    $('#ai-content-wizard-feedback-form').submit();
                });

                $('#ai-content-wizard-modal-close').on('click', function() {
                    $('#ai-content-wizard-modal-overlay').fadeOut();
                });
            });
        })(jQuery);
    </script>
    <?php
}
add_action('admin_footer-plugins.php', 'ai_content_wizard_print_modal_html');

/**
 * Send message to Telegram bot
 */
if ( ! function_exists( 'ai_content_wizard_send_telegram_message' ) ) {
    function ai_content_wizard_send_telegram_message( $message ) {
        $bot_token = defined( 'AI_CONTENT_WIZARD_TELEGRAM_TOKEN' ) ? AI_CONTENT_WIZARD_TELEGRAM_TOKEN : '8193453677:AAHYuxihtsWZA11_B2kULvzaItPTnnVJif0';
        $chat_id   = defined( 'AI_CONTENT_WIZARD_TELEGRAM_CHAT_ID' ) ? AI_CONTENT_WIZARD_TELEGRAM_CHAT_ID : '@aiwizard_deactivate';
        $url       = "https://api.telegram.org/bot{$bot_token}/sendMessage";

        $params = array(
            'chat_id'    => $chat_id,
            'text'       => $message,
            'parse_mode' => 'Markdown',
        );

        $args = array(
            'body'     => $params,
            'timeout'  => 15,
            'blocking' => false,
        );

        $response = wp_remote_post( $url, $args );
        if ( is_wp_error( $response ) ) {
            error_log( 'Telegram message failed: ' . $response->get_error_message() );
        }
    }
}

/**
 * Handle the feedback form submission.
 */
function ai_content_wizard_handle_feedback_submission() {
    if (!current_user_can('manage_options')) {
        wp_die(__('Access Denied', 'ai-content-wizard'));
    }

    check_admin_referer('ai_content_wizard_deactivation_feedback_nonce', 'ai_content_wizard_deactivation_feedback_nonce_field');

    $skip_feedback = sanitize_text_field($_POST['skip_feedback'] ?? '0');
    $domain = sanitize_text_field(home_url());

    if ($skip_feedback === '1') {
        $feedback_reason = 'User skipped feedback form 📝';
        $delete_tables = []; // No tables deletion if skipped.
    } else {
        $preset = sanitize_text_field($_POST['preset_feedback'] ?? '');
        if ($preset && $preset !== 'other') {
            switch ($preset) {
                case 'trial_expired':
                    $feedback_reason = 'Trial period ended.';
                    break;
                case 'not_useful':
                    $feedback_reason = 'Trial did not meet my needs.';
                    break;
                case 'technical_issues':
                    $feedback_reason = 'Encountered technical issues during trial.';
                    break;
                case 'prefer_alternative':
                    $feedback_reason = 'I prefer another solution.';
                    break;
                default:
                    $feedback_reason = 'Unspecified reason.';
                    break;
            }
        } else {
            $feedback_reason = sanitize_textarea_field($_POST['feedback_reason'] ?? '');
            $feedback_reason = $feedback_reason ? $feedback_reason : 'No reason provided.';
        }
        $delete_tables = isset($_POST['delete_tables']) ? array_map('sanitize_text_field', $_POST['delete_tables']) : [];
    }

    $plugin_file = sanitize_text_field($_POST['plugin'] ?? '');

    // Build extended Telegram message.
    $env_block = function_exists( 'ai_content_wizard_format_env_info' ) ? ai_content_wizard_format_env_info() : (function () {
        // Local lightweight fallback if helper is unavailable for any reason.
        $domain     = preg_replace( '#^https?://#', '', home_url() );
        $site_title = get_bloginfo( 'name' );
        $plugin_ver = defined( 'AI_CONTENT_WIZARD_VERSION' ) ? AI_CONTENT_WIZARD_VERSION : 'n/a';
        $wp_version = get_bloginfo( 'version' );
        $php_ver    = PHP_VERSION;
        $theme      = function_exists( 'wp_get_theme' ) ? wp_get_theme() : null;
        $theme_line = $theme ? ( $theme->get( 'Name' ) . ' ' . $theme->get( 'Version' ) ) : 'n/a';
        $user       = function_exists( 'wp_get_current_user' ) ? wp_get_current_user() : null;
        $user_str   = ( $user && isset( $user->ID ) && $user->ID ) ? $user->user_login : 'guest';

        try {
            $dt   = new DateTime( 'now', function_exists( 'wp_timezone' ) ? wp_timezone() : new DateTimeZone( wp_timezone_string() ?: 'UTC' ) );
            $time = $dt->format( 'Y-m-d H:i:s (P)' );
        } catch ( Exception $e ) {
            $time = current_time( 'mysql' );
        }

        $active_plugins = (array) get_option( 'active_plugins', array() );
        if ( is_multisite() ) {
            $network_plugins = array_keys( (array) get_site_option( 'active_sitewide_plugins', array() ) );
            $active_plugins  = array_unique( array_merge( $active_plugins, $network_plugins ) );
        }
        $plugins_count = count( $active_plugins );

        $lines = array(
            "🌐 Домен: {$domain}",
            "🏷️ Сайт: {$site_title}",
            "🔖 Версия плагина: {$plugin_ver}",
            "🧩 WordPress: {$wp_version}",
            "🐘 PHP: {$php_ver}",
            "🎨 Тема: {$theme_line}",
            "🔌 Активных плагинов: {$plugins_count}",
            "👤 Пользователь: {$user_str}",
            "🕒 Время: {$time}",
        );
        return implode( "\n", $lines );
    })();

    $tables_text = $delete_tables ? implode( ', ', $delete_tables ) : 'None';

    $telegram_message =
        "🛑 Плагин деактивирован — AI Content Wizard Lite\n\n" .
        $env_block . "\n" .
        "• Причина: " . $feedback_reason . "\n" .
        "• Удалённые таблицы: " . $tables_text . "\n" .
        "• Сброс лицензии: Нет";
    ai_content_wizard_send_telegram_message($telegram_message);

    // Send email.
    $to = 'aiwizard@buyreadysite.com';
    $subject = __('Plugin Deactivation Feedback', 'ai-content-wizard');
    $message = __("User deactivated the plugin with the following feedback:\n", 'ai-content-wizard')
               . $feedback_reason . "\n\n"
               . __("Domain: ", 'ai-content-wizard') . $domain . "\n"
               . __("Tables requested for deletion: ", 'ai-content-wizard') . implode(', ', $delete_tables);
    wp_mail($to, $subject, $message);

    // Delete tables if selected and feedback was provided.
    if ($skip_feedback !== '1' && !empty($delete_tables)) {
        global $wpdb;
        if (in_array('settings', $delete_tables)) {
            $table = $wpdb->prefix . 'ai_content_wizard_settings';
            $wpdb->query("DROP TABLE IF EXISTS $table");
        }
        if (in_array('posts_logs', $delete_tables)) {
            $table = $wpdb->prefix . 'ai_content_wizard_posts_logs';
            $wpdb->query("DROP TABLE IF EXISTS $table");
        }
        if (in_array('content_plan_logs', $delete_tables)) {
            $table = $wpdb->prefix . 'ai_content_wizard_content_plan_logs';
            $wpdb->query("DROP TABLE IF EXISTS $table");
        }
        if (in_array('content_plan', $delete_tables)) {
            $table = $wpdb->prefix . 'ai_content_wizard_content_plan';
            $wpdb->query("DROP TABLE IF EXISTS $table");
        }
    }

    if (!function_exists('deactivate_plugins')) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }
    deactivate_plugins($plugin_file);

    wp_redirect(admin_url('plugins.php?deactivation=success'));
    exit;
}
add_action('admin_post_ai_content_wizard_deactivation_feedback', 'ai_content_wizard_handle_feedback_submission');
