<?php
defined('ABSPATH') || exit;

class DSProofwp_Feedback
{
    private $plugin_version = '1.3.12';
    private $plugin_name    = 'Proofwp - Visual Product Reviews for WooCommerce';
    private $plugin_slug    = 'proofwp';
    private $feedback_url   = 'https://crm.dstudio.asia/api/feedback';

    public function __construct()
    {
        add_action('admin_enqueue_scripts', array($this, 'enqueue_feedback_scripts'));
        add_action('admin_head', array($this, 'show_deactivate_feedback_popup'));
        add_action('wp_ajax_' . $this->plugin_slug . '_submit_deactivation_response', array($this, 'submit_deactivation_response'));
    }

    public function enqueue_feedback_scripts()
    {
        $screen = get_current_screen();
        if (isset($screen) && $screen->id == 'plugins') {
            $ajax_nonce = wp_create_nonce('proofwp_deactivate_plugin');
            wp_enqueue_style('proofwp-deactivation-css', plugins_url('assets/css/feedback.css', dirname(__DIR__) . '/proofwp.php'), null, $this->plugin_version);
            wp_enqueue_script('proofwp-deactivation-script', plugins_url('assets/js/feedback.js', dirname(__DIR__) . '/proofwp.php'), array('jquery'), $this->plugin_version, true);
            wp_localize_script('proofwp-deactivation-script', 'proofwp_feedback_ajax', array('nonce' => $ajax_nonce));
        }
    }

    public function show_deactivate_feedback_popup()
    {
        $screen = get_current_screen();
        if (!isset($screen) || $screen->id != 'plugins') {
            return;
        }
?>
        <div class="proofwp-deactivation-popup proofwp-hidden" data-type="wrapper" data-slug="<?php echo esc_attr($this->plugin_slug); ?>">
            <div class="proofwp-overlay">
                <div class="proofwp-close"><i class="dashicons dashicons-no"></i></div>
                <div class="proofwp-body">
                    <div class="proofwp-title-wrap">
                        <div class="proofwp-img-wrap">
                            <img src="<?php echo esc_url(plugins_url('public/proofwp.svg', dirname(__DIR__) . '/proofwp.php')); ?>" alt="ProofWP">
                        </div>
                        <?php echo esc_html(__('Goodbyes are always hard', 'proofwp')); ?>
                    </div>
                    <div class="proofwp-messages-wrap">
                        <p><?php echo esc_html(__('Would you quickly give us your reason for doing so?', 'proofwp')); ?></p>
                    </div>
                    <div class="proofwp-options-wrap">
                        <label class="proofwp-option-label">
                            <input type="radio" name="feedback" value="temp" class="proofwp-radio">
                            <?php echo esc_html(__('Temporary deactivation', 'proofwp')); ?>
                        </label>
                        <label class="proofwp-option-label">
                            <input type="radio" name="feedback" value="setup" class="proofwp-radio">
                            <?php echo esc_html(__('Set up is too difficult', 'proofwp')); ?>
                        </label>
                        <label class="proofwp-option-label">
                            <input type="radio" name="feedback" value="documentation" class="proofwp-radio">
                            <?php echo esc_html(__('Lack of documentation', 'proofwp')); ?>
                        </label>
                        <label class="proofwp-option-label">
                            <input type="radio" name="feedback" value="features" class="proofwp-radio">
                            <?php echo esc_html(__('Not the features I wanted', 'proofwp')); ?>
                        </label>
                        <label class="proofwp-option-label">
                            <input type="radio" name="feedback" value="better-plugin" class="proofwp-radio">
                            <?php echo esc_html(__('Found a better plugin', 'proofwp')); ?>
                        </label>
                        <label class="proofwp-option-label">
                            <input type="radio" name="feedback" value="incompatibility" class="proofwp-radio">
                            <?php echo esc_html(__('Incompatible with theme or plugin', 'proofwp')); ?>
                        </label>
                        <label class="proofwp-option-label">
                            <input type="radio" name="feedback" value="other" class="proofwp-radio">
                            <?php echo esc_html(__('Other', 'proofwp')); ?>
                        </label>
                    </div>
                    <div class="proofwp-messages-wrap proofwp-hidden" data-feedback>
                        <p class="proofwp-hidden" data-feedback="setup"><?php echo esc_html(__('What was the difficult part?', 'proofwp')); ?></p>
                        <p class="proofwp-hidden" data-feedback="documentation"><?php echo esc_html(__('What can we describe more?', 'proofwp')); ?></p>
                        <p class="proofwp-hidden" data-feedback="features"><?php echo esc_html(__('How could we improve?', 'proofwp')); ?></p>
                        <p class="proofwp-hidden" data-feedback="better-plugin"><?php echo esc_html(__('Can you mention it?', 'proofwp')); ?></p>
                        <p class="proofwp-hidden" data-feedback="incompatibility"><?php echo esc_html(__('With what plugin or theme is incompatible?', 'proofwp')); ?></p>
                        <p class="proofwp-hidden" data-feedback="other"><?php echo esc_html(__('Please specify:', 'proofwp')); ?></p>
                    </div>
                    <div class="proofwp-options-wrap proofwp-hidden" data-feedback>
                        <label class="proofwp-textarea-label">
                            <textarea name="suggestions" rows="2" class="proofwp-textarea" placeholder="<?php echo esc_attr(__('Tell us more about your reason...', 'proofwp')); ?>"></textarea>
                        </label>
                    </div>
                    <div class="proofwp-messages-wrap proofwp-hidden" data-feedback>
                        <p><?php echo esc_html(__('Would you like to share your e-mail and elements usage with us so that we can write you back?', 'proofwp')); ?></p>
                    </div>
                    <div class="proofwp-options-wrap proofwp-hidden dennsimc-anonymous" data-feedback>
                        <label class="proofwp-checkbox-label">
                            <input type="checkbox" name="anonymous" value="1" class="proofwp-checkbox">
                            <?php echo esc_html(__('No, I\'d like to stay anonymous', 'proofwp')); ?>
                        </label>
                    </div>

                    <div class="proofwp-buttons-wrap">
                        <button class="proofwp-btn proofwp-skip-btn"><?php echo esc_html(__('Skip & Deactivate', 'proofwp')); ?></button>
                        <button class="proofwp-btn proofwp-submit-btn"><?php echo esc_html(__('Submit & Deactivate', 'proofwp')); ?></button>
                    </div>
                </div>
            </div>
        </div>
<?php
    }

    private function collect_feedback_data($reason, $message, $anonymous = false)
    {
        global $wpdb;

        $plugin_data = array(
            'deactivated_plugin' => array(
                'version' => $this->plugin_version,
                'memory'  => 'Memory: ' . size_format(wp_convert_hr_to_bytes(ini_get('memory_limit'))),
                'time'    => 'Time: ' . ini_get('max_execution_time'),
                'deactivate' => 'Deactivation: ' . gmdate('j F, Y', time()),
                'uninstall_reason' => $reason,
                'uninstall_details' => $message
            ),
        );

        if (!$anonymous) {
            $plugin_data['deactivated_plugin']['domain'] = $this->get_site_domain();
        }

        $wordpress_data = array(
            'wp_version' => get_bloginfo('version'),
            'wp_locale' => get_locale(),
            'wp_debug' => defined('WP_DEBUG') && WP_DEBUG ? 'Enabled' : 'Disabled',
            'wp_memory_limit' => ini_get('memory_limit'),
            'php_version' => phpversion(),
            'mysql_version' => $wpdb->db_version(),
            'server_software' => isset($_SERVER['SERVER_SOFTWARE']) ? sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'])) : 'N/A'
        );

        $environment_data = array(
            'active_theme' => $this->get_active_theme(),
            'active_plugins' => $this->get_active_plugins(),
            'wp_multisite' => is_multisite() ? 'Yes' : 'No'
        );

        $user_data = array();
        if (!$anonymous) {
            $current_user = wp_get_current_user();
            $user_data = array(
                'email' => $current_user->user_email,
                'first_name' => $current_user->first_name,
                'last_name' => $current_user->last_name,
                'domain' => $this->get_site_domain()
            );
        }

        return array(
            'plugin_data' => $plugin_data,
            'wordpress_data' => $wordpress_data,
            'environment_data' => $environment_data,
            'user_data' => $user_data,
            'anonymous' => $anonymous
        );
    }

    private function get_active_theme()
    {
        $theme = wp_get_theme();
        return array(
            'name' => $theme->get('Name'),
            'version' => $theme->get('Version'),
            'author' => $theme->get('Author')
        );
    }

    private function get_active_plugins()
    {
        if (!function_exists('get_plugins')) {
            include_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $active_plugins = get_option('active_plugins', array());
        $plugins_list = array();

        foreach ($active_plugins as $plugin_path) {
            $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin_path);
            $plugins_list[] = array(
                'name' => $plugin_data['Name'],
                'version' => $plugin_data['Version']
            );
        }

        return $plugins_list;
    }

    private function get_site_domain()
    {
        return wp_parse_url(get_site_url(), PHP_URL_HOST);
    }

    public function submit_deactivation_response()
    {
        if (! current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }

        if (! isset($_POST['_wpnonce']) || ! wp_verify_nonce(sanitize_key(wp_unslash($_POST['_wpnonce'])), 'proofwp_deactivate_plugin')) {
            wp_send_json_error('Security check failed');
        }

        $reason = isset($_POST['reason']) ? sanitize_text_field(wp_unslash($_POST['reason'])) : 'other';
        $message = isset($_POST['message']) ? sanitize_textarea_field(wp_unslash($_POST['message'])) : 'N/A';
        $anonymous = isset($_POST['anonymous']) && $_POST['anonymous'] === '1';

        $reason_map = array(
            'temp' => 'temporary_deactivation',
            'setup' => 'setup_difficult',
            'documentation' => 'lack_documentation',
            'features' => 'missing_features',
            'better-plugin' => 'better_plugin',
            'incompatibility' => 'incompatible',
            'other' => 'other'
        );

        $final_reason = isset($reason_map[$reason]) ? $reason_map[$reason] : 'other';

        $feedback_data = $this->collect_feedback_data($final_reason, $message, $anonymous);

        $api_data = array(
            'server_info' => $feedback_data['wordpress_data'],
            'extra_details' => array(
                'wp_theme'       => $feedback_data['environment_data']['active_theme'],
                'active_plugins' => $feedback_data['environment_data']['active_plugins'],
            ),
            'plugin_version' => $this->plugin_version,
            'plugin_name'    => $this->plugin_name,
            'reason'         => $final_reason,
            'review'         => $message,
            'email'          => $anonymous ? null : $feedback_data['user_data']['email'],
            'domain'         => $anonymous ? null : $feedback_data['user_data']['domain'],
            'site_id'        => $anonymous ? 'anonymous_' . wp_generate_password(12, false) : md5(get_site_url() . '-14'),
            'product_uuid' => '1779333489-b944feb2-a685-46a5-84c0-1f8c53ab5e4c',
            'anonymous'      => $anonymous,
            'comprehensive_data' => $feedback_data,
        );

        $args = array(
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json; charset=utf-8',
                'Accept'       => 'application/json',
            ),
            'body'    => wp_json_encode($api_data),
        );

        wp_remote_post($this->feedback_url, $args);

        wp_send_json_success('Feedback submitted successfully');
    }
}

new DSProofwp_Feedback();
