<?php
/**
 * Deactivation Feedback Handler
 * 
 * Shows feedback modal on deactivation and sends data to API
 * @since 2.1.2
 * @since 2.2.2 Added data retention choice functionality, data retention on deactivation handling
 * @package VMPFence
 */

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

class VMPFence_Deactivation_Feedback {
    
    /**
     * Flag to skip API submission for private/local IPs
     * Set to false to send feedback from local development environments
     * 
     * @var bool
     */
    private $skip_api_for_private_ip = true;
    
    public function __construct() {
        add_action('admin_footer', array($this, 'render_feedback_modal'));
        add_action('wp_ajax_vmpfence_send_deactivation_feedback', array($this, 'send_feedback'));
    }
    
    public function render_feedback_modal() {
        $screen = get_current_screen();
        
        if (!$screen || $screen->id !== 'plugins') {
            return;
        }
        
        ?>
        <div id="vmpfence-deactivation-modal" style="display:none;">
            <div class="vmpfence-modal-overlay"></div>
            <div class="vmpfence-modal-content">
                <span class="vmpfence-modal-close">&times;</span>
                
                <!-- Step 1: Data Retention Choice (shown if enabled) -->
                <div id="vmpfence-data-retention-step" style="display:none;">
                    <h2>Data Retention</h2>
                    <p>What would you like to do with your VMP Security data?</p>
                    
                    <div class="vmpfence-data-choice">
                        <label class="vmpfence-data-option">
                            <input type="radio" name="data_action" value="keep" checked>
                            <div class="vmpfence-data-option-content">
                                <span class="vmpfence-data-option-title">Keep all tables and data</span>
                                <span class="vmpfence-data-option-desc">Your settings, scan results, and logs will be preserved for future use</span>
                            </div>
                        </label>
                        
                        <label class="vmpfence-data-option">
                            <input type="radio" name="data_action" value="delete">
                            <div class="vmpfence-data-option-content">
                                <span class="vmpfence-data-option-title">Delete all tables and data</span>
                                <span class="vmpfence-data-option-desc">Permanently remove all VMP Security data from your database</span>
                            </div>
                        </label>
                    </div>
                    
                    <p style="margin-top: 15px; font-size: 13px; color: #646970;">
                        <strong>Note:</strong> This does not include Login Security settings and tables.
                    </p>
                    
                    <div class="modal-buttons">
                        <button type="button" class="button button-primary" id="vmpfence-data-retention-next">
                            Continue
                        </button>
                    </div>
                </div>
                
                <!-- Step 2: Feedback Form (always shown or second step) -->
                <div id="vmpfence-feedback-step">
                    <h2>Quick Feedback</h2>
                    <p>We're sorry to see you go! Please help us improve:</p>
                    
                    <form id="vmpfence-feedback-form">
                        <label class="vmpfence-feedback-option">
                            <input type="checkbox" name="reason_bugs" value="1">
                            <span class="vmpfence-reason-title">Bugs</span>
                            <span class="vmpfence-reason-desc">Plugin has technical issues</span>
                        </label>
                        
                        <label class="vmpfence-feedback-option">
                            <input type="checkbox" name="reason_not_interested" value="1">
                            <span class="vmpfence-reason-title">Not Interested</span>
                            <span class="vmpfence-reason-desc">Don't need this functionality</span>
                        </label>
                        
                        <label class="vmpfence-feedback-option">
                            <input type="checkbox" name="reason_found_better" value="1">
                            <span class="vmpfence-reason-title">Found something better</span>
                            <span class="vmpfence-reason-desc">Using alternative solution</span>
                        </label>
                        
                        <label class="vmpfence-feedback-option">
                            <input type="checkbox" name="reason_others" value="1" id="reason-others-checkbox">
                            <span class="vmpfence-reason-title">Others</span>
                            <span class="vmpfence-reason-desc">Tell us more...</span>
                        </label>
                        
                        <textarea 
                            name="others_reason" 
                            id="others-reason-text"
                            placeholder="Please tell us more..."
                            rows="4"
                            style="display:none;"
                        ></textarea>
                        
                        <p class="error-message" style="color:#d63638; display:none; margin-top:10px; font-weight:600;">
                            ⚠ Please select at least one reason
                        </p>
                        
                        <div class="modal-buttons">
                            <button type="button" class="button" id="vmpfence-feedback-back" style="display:none;">
                                Back
                            </button>
                            <button type="submit" class="button button-primary" id="vmpfence-submit-feedback" disabled>
                                Submit & Deactivate
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        
        <style>
            .vmpfence-modal-overlay {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.7);
                z-index: 99999;
                backdrop-filter: blur(2px);
            }
            .vmpfence-modal-content {
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: white;
                padding: 30px;
                border-radius: 12px;
                max-width: 550px;
                width: 90%;
                z-index: 100000;
                box-shadow: 0 10px 40px rgba(0,0,0,0.3);
                max-height: 90vh;
                overflow-y: auto;
            }
            .vmpfence-modal-content h2 {
                margin: 0 0 10px 0;
                font-size: 24px;
                color: #1d2327;
            }
            .vmpfence-modal-content > div > p {
                margin: 0 0 20px 0;
                color: #50575e;
                font-size: 14px;
            }
            .vmpfence-modal-close {
                position: absolute;
                top: 15px;
                right: 20px;
                font-size: 28px;
                font-weight: normal;
                color: #999;
                cursor: pointer;
                line-height: 1;
                transition: color 0.2s;
            }
            .vmpfence-modal-close:hover {
                color: #333;
            }
            
            /* Data Retention Styles */
            .vmpfence-data-choice {
                margin: 20px 0;
            }
            .vmpfence-data-option {
                display: block;
                padding: 15px 20px;
                margin: 12px 0;
                background: #f6f7f7;
                border: 2px solid #dcdcde;
                border-radius: 8px;
                cursor: pointer;
                transition: all 0.2s;
                position: relative;
                display: flex;
                align-items: flex-start;
            }
            .vmpfence-data-option:hover {
                background: #e8f0fe;
                border-color: #2271b1;
            }
            .vmpfence-data-option input[type="radio"] {
                margin-top: 3px;
                margin-right: 15px;
                width: 18px;
                height: 18px;
                cursor: pointer;
                flex-shrink: 0;
            }
            .vmpfence-data-option input[type="radio"]:checked ~ .vmpfence-data-option-content {
                color: #2271b1;
            }
            .vmpfence-data-option-content {
                flex: 1;
            }
            .vmpfence-data-option-title {
                display: block;
                font-weight: 600;
                color: #1d2327;
                margin-bottom: 4px;
                font-size: 15px;
            }
            .vmpfence-data-option-desc {
                display: block;
                font-size: 13px;
                color: #646970;
                line-height: 1.5;
            }
            
            /* Feedback Styles */
            .vmpfence-feedback-option {
                display: block;
                padding: 12px 15px;
                margin: 10px 0;
                background: #f6f7f7;
                border: 2px solid transparent;
                border-radius: 8px;
                cursor: pointer;
                transition: all 0.2s;
                position: relative;
                padding-left: 45px;
            }
            .vmpfence-feedback-option:hover {
                background: #e8f0fe;
                border-color: #2271b1;
            }
            .vmpfence-feedback-option input[type="checkbox"] {
                position: absolute;
                left: 15px;
                top: 50%;
                transform: translateY(-50%);
                margin: 0;
                width: 18px;
                height: 18px;
                cursor: pointer;
            }
            .vmpfence-reason-title {
                display: block;
                font-weight: 600;
                color: #1d2327;
                margin-bottom: 2px;
                font-size: 14px;
            }
            .vmpfence-reason-desc {
                display: block;
                font-size: 13px;
                color: #646970;
            }
            #others-reason-text {
                width: 100%;
                margin-top: 10px;
                padding: 12px;
                border: 1px solid #8c8f94;
                border-radius: 6px;
                font-size: 14px;
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
                resize: vertical;
            }
            #others-reason-text:focus {
                border-color: #2271b1;
                outline: none;
                box-shadow: 0 0 0 1px #2271b1;
            }
            .modal-buttons {
                margin-top: 25px;
                text-align: right;
                padding-top: 20px;
                border-top: 1px solid #dcdcde;
            }
            .modal-buttons button {
                margin-left: 10px;
                padding: 8px 16px;
                font-size: 14px;
            }
            .modal-buttons button:disabled {
                opacity: 0.5;
                cursor: not-allowed;
            }
        </style>
        
        <script>
        jQuery(document).ready(function($) {
            
            // Get plugin slug dynamically from plugin basename
            var pluginBasename = '<?php echo VMPFENCE_PLUGIN_BASENAME; ?>';
            var pluginSlug = pluginBasename.split('/')[0];
            
            var deactivateLink = '';
            var dataAction = 'keep'; // Default to keep data
            var showDataRetentionStep = <?php echo get_option('vmpfence_enable_deactivation_choice', 0) ? 'true' : 'false'; ?>;
            
            // Build selector dynamically using the plugin slug and basename
            var deactivateSelector = 'tr[data-slug="' + pluginSlug + '"] .deactivate a, tr[data-plugin="' + pluginBasename + '"] .deactivate a';
            
            $('#the-list').on('click', deactivateSelector, function(e) {
                e.preventDefault();
                deactivateLink = $(this).attr('href');
                
                // Show appropriate step based on settings
                if (showDataRetentionStep) {
                    $('#vmpfence-data-retention-step').show();
                    $('#vmpfence-feedback-step').hide();
                    $('#vmpfence-feedback-back').hide();
                } else {
                    $('#vmpfence-data-retention-step').hide();
                    $('#vmpfence-feedback-step').show();
                    $('#vmpfence-feedback-back').hide();
                }
                
                $('#vmpfence-deactivation-modal').fadeIn(200);
            });
            
            $('.vmpfence-modal-close, .vmpfence-modal-overlay').on('click', function() {
                $('#vmpfence-deactivation-modal').fadeOut(200);
                // Reset to first step
                if (showDataRetentionStep) {
                    $('#vmpfence-data-retention-step').show();
                    $('#vmpfence-feedback-step').hide();
                }
            });
            
            // Data retention step - Continue button
            $('#vmpfence-data-retention-next').on('click', function() {
                dataAction = $('input[name="data_action"]:checked').val();
                // console.log('User selected data action:', dataAction);
                
                // Move to feedback step
                $('#vmpfence-data-retention-step').hide();
                $('#vmpfence-feedback-step').show();
                $('#vmpfence-feedback-back').show();
            });
            
            // Feedback step - Back button
            $('#vmpfence-feedback-back').on('click', function() {
                $('#vmpfence-feedback-step').hide();
                $('#vmpfence-data-retention-step').show();
            });
            
            // Function to check if any reason is selected and enable/disable submit button
            function updateSubmitButton() {
                var hasReason = false;
                $('input[name^="reason_"]').each(function() {
                    if ($(this).is(':checked')) {
                        hasReason = true;
                        return false; // break loop
                    }
                });
                
                $('#vmpfence-submit-feedback').prop('disabled', !hasReason);
            }
            
            // Listen to all reason checkboxes
            $('input[name^="reason_"]').on('change', function() {
                updateSubmitButton();
            });
            
            $('#reason-others-checkbox').on('change', function() {
                if ($(this).is(':checked')) {
                    $('#others-reason-text').slideDown(200);
                } else {
                    $('#others-reason-text').slideUp(200).val('');
                }
            });
            
            $('#vmpfence-feedback-form').on('submit', function(e) {
                e.preventDefault();
                
                var formData = $(this).serializeArray();
                
                // Add data action to feedback
                formData.push({
                    name: 'data_action',
                    value: dataAction
                });
                
                var $submitBtn = $('#vmpfence-submit-feedback');
                $submitBtn.prop('disabled', true).text('Submitting...');
                
                
                $.post(ajaxurl, {
                    action: 'vmpfence_send_deactivation_feedback',
                    feedback: formData,
                    nonce: '<?php echo wp_create_nonce('vmpfence_feedback'); ?>'
                }).done(function(response) {
                    // console.log('VMPFence: Feedback submitted successfully:', response);
                }).fail(function(xhr, status, error) {
                    console.error('VMPFence: Feedback submission failed:', error);
                    console.error('VMPFence: XHR:', xhr.responseText);
                }).always(function() {
                    window.location.href = deactivateLink;
                });
            });
        });
        </script>
        <?php
    }
    
    public function send_feedback() {
        check_ajax_referer('vmpfence_feedback', 'nonce');
        
        
        if (!isset($_POST['feedback']) || !is_array($_POST['feedback'])) {
            wp_send_json_error();
        }
        
        $data = array(
            'site_url' => get_site_url(),
            'reason_bugs' => false,
            'reason_not_interested' => false,
            'reason_found_better' => false,
            'reason_others' => false,
            'others_reason' => '',
            'plugin_version' => VMPFENCE_VERSION,
            'wordpress_version' => get_bloginfo('version'),
            'php_version' => phpversion(),
        );
        
        // Store data retention choice for deactivation hook
        $data_action = 'keep'; // Default to keep
        
        foreach ($_POST['feedback'] as $field) {
            if (!isset($field['name']) || !isset($field['value'])) continue;
            
            $name = sanitize_key($field['name']);
            $value = $field['value'];
            
            if ($name === 'data_action') {
                $data_action = sanitize_text_field($value);
            } elseif ($name === 'others_reason') {
                $data['others_reason'] = sanitize_textarea_field($value);
            } elseif (strpos($name, 'reason_') === 0 && $value === '1') {
                $data[$name] = true;
            }
        }
        
        // Store the data action choice as a transient (expires in 5 minutes)
        // This will be read by vmpfence_deactivate() function
        set_transient('vmpfence_deactivation_data_action', $data_action, 300);
        
        // CRITICAL: Also save as permanent option for uninstall.php
        // Transient expires in 5 minutes, but user might not click Delete button immediately
        // uninstall.php needs this to be persistent to honor user's choice
        if ($data_action === 'keep') {
            update_option('vmpfence_preserve_data_on_uninstall', true);
        } else {
            update_option('vmpfence_preserve_data_on_uninstall', false);
        }
        
        // Check if we should skip API for private IPs
        if ($this->skip_api_for_private_ip && $this->is_private_ip()) {
            // Fake successful submission for local/private environments
            wp_send_json_success(array(
                'message' => 'Feedback received (local environment)',
                'skipped' => true
            ));
            return;
        }
        
        $response = wp_remote_post('https://newton-wordpress-security.vpnmasterpro.com/api/v1/feedback/plugin-deletion', array(
            'timeout' => 15,
            'headers' => array('Content-Type' => 'application/json'),
            'body' => json_encode($data),
        ));
        
        // if (is_wp_error($response)) {
        //     error_log('VMPFence: Feedback API error: ' . $response->get_error_message());
        // } else {
        //     $status_code = wp_remote_retrieve_response_code($response);
        //     $response_body = wp_remote_retrieve_body($response);
        //     error_log('VMPFence: Feedback API response (status ' . $status_code . '): ' . $response_body);
        // }
        
        wp_send_json_success();
    }
    
    /**
     * Check if the current server IP is private/local
     * 
     * @return bool True if private IP, false otherwise
     */
    private function is_private_ip() {
        // Get server IP
        $server_ip = $_SERVER['SERVER_ADDR'] ?? $_SERVER['LOCAL_ADDR'] ?? '';
        
        // If we can't determine IP, assume it's not private
        if (empty($server_ip)) {
            return false;
        }
        
        // Check if IP is private/local
        // IPv4 private ranges:
        // 10.0.0.0 - 10.255.255.255
        // 172.16.0.0 - 172.31.255.255
        // 192.168.0.0 - 192.168.255.255
        // 127.0.0.0 - 127.255.255.255 (localhost)
        // ::1 (IPv6 localhost)
        
        // Check for localhost/127.0.0.0
        if ($server_ip === '127.0.0.1' || $server_ip === 'localhost' || $server_ip === '::1') {
            return true;
        }
        
        // Check for private IPv4 ranges
        $private_ranges = array(
            '10.0.0.0|10.255.255.255',     // Class A
            '172.16.0.0|172.31.255.255',   // Class B
            '192.168.0.0|192.168.255.255', // Class C
        );
        
        $long_ip = ip2long($server_ip);
        if ($long_ip === false) {
            return false; // Invalid IP or IPv6
        }
        
        foreach ($private_ranges as $range) {
            list($start, $end) = explode('|', $range);
            if ($long_ip >= ip2long($start) && $long_ip <= ip2long($end)) {
                return true;
            }
        }
        
        return false;
    }
}

new VMPFence_Deactivation_Feedback();
