<?php

defined('ABSPATH') || exit;

class InsightPress_Deactivation_Survey
{
    public static function init()
    {
        add_action('admin_footer', [__CLASS__, 'render_survey_modal']);
        add_action('wp_ajax_insightpress_deactivation_feedback', [__CLASS__, 'handle_feedback']);
    }

    public static function render_survey_modal()
    {
        $screen = get_current_screen();
        if ($screen->id !== 'plugins') {
            return;
        }

        $plugin_slug = 'insightpress-advanced-analytics-for-woocommerce/insightpress-advanced-analytics-for-woocommerce.php';
        ?>
        <style>
            #insightpress-survey-modal {
                display: none;
                position: fixed;
                z-index: 999999;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
            }

            .insightpress-modal-content {
                background-color: #fff;
                margin: 10% auto;
                padding: 30px;
                border-radius: 8px;
                width: 500px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
                position: relative;
            }

            .insightpress-modal-header h2 {
                margin: 0 0 10px;
                font-size: 20px;
                color: #1d2327;
            }

            .insightpress-modal-header p {
                margin: 0 0 20px;
                color: #646970;
                font-size: 14px;
                line-height: 1.5;
            }

            .insightpress-survey-reasons {
                margin-bottom: 20px;
            }

            .insightpress-reason {
                margin-bottom: 12px;
                display: flex;
                align-items: center;
                cursor: pointer;
            }

            .insightpress-reason input {
                margin: 0 10px 0 0;
            }

            .insightpress-reason label {
                font-size: 14px;
                color: #1d2327;
                cursor: pointer;
            }

            .insightpress-feedback-text {
                display: none;
                margin-top: 10px;
            }

            .insightpress-feedback-text textarea {
                width: 100%;
                padding: 10px;
                border: 1px solid #dcdcde;
                border-radius: 4px;
                font-size: 13px;
                min-height: 80px;
            }

            .insightpress-modal-footer {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-top: 25px;
            }

            .insightpress-button {
                padding: 10px 20px;
                border-radius: 4px;
                font-size: 14px;
                font-weight: 500;
                cursor: pointer;
                transition: background-color 0.2s;
                border: none;
            }

            .insightpress-button-primary {
                background-color: #7c3aed;
                color: #fff;
            }

            .insightpress-button-primary:hover {
                background-color: #6d28d9;
            }

            .insightpress-button-secondary {
                background-color: transparent;
                color: #646970;
                text-decoration: underline;
                padding-left: 0;
            }

            .insightpress-button-secondary:hover {
                color: #1d2327;
            }

            .insightpress-button:disabled {
                opacity: 0.6;
                cursor: not-allowed;
            }
        </style>

        <div id="insightpress-survey-modal">
            <div class="insightpress-modal-content">
                <div class="insightpress-modal-header">
                    <h2>Wait! Before you go...</h2>
                    <p>Could you please tell us why you are deactivating InsightPress? Your feedback helps us make the plugin better.</p>
                </div>

                <div class="insightpress-survey-reasons">
                    <div class="insightpress-reason">
                        <input type="radio" name="reason" id="ip-reason-temporary" value="temporary">
                        <label for="ip-reason-temporary">I'm only deactivating it temporarily.</label>
                    </div>
                    <div class="insightpress-reason">
                        <input type="radio" name="reason" id="ip-reason-found_better" value="found_better">
                        <label for="ip-reason-found_better">I found a better analytics plugin.</label>
                    </div>
                    <div class="insightpress-reason">
                        <input type="radio" name="reason" id="ip-reason-too_complex" value="too_complex">
                        <label for="ip-reason-too_complex">It's too complicated to set up.</label>
                    </div>
                    <div class="insightpress-reason">
                        <input type="radio" name="reason" id="ip-reason-not_working" value="not_working">
                        <label for="ip-reason-not_working">The data doesn't seem accurate or it's not working.</label>
                    </div>
                    <div class="insightpress-reason">
                        <input type="radio" name="reason" id="ip-reason-other" value="other">
                        <label for="ip-reason-other">Other</label>
                    </div>

                    <div id="ip-feedback-text-container" class="insightpress-feedback-text">
                        <textarea id="insightpress-feedback-message"
                            placeholder="Please share your thoughts..."></textarea>
                    </div>
                </div>

                <div class="insightpress-modal-footer">
                    <button type="button" id="insightpress-submit-deactivate"
                        class="insightpress-button insightpress-button-primary">Submit & Deactivate</button>
                    <button type="button" id="insightpress-skip-deactivate"
                        class="insightpress-button insightpress-button-secondary">Skip & Deactivate</button>
                </div>
            </div>
        </div>

        <script>
            (function ($) {
                $(function () {
                    var $modal = $('#insightpress-survey-modal');
                    var $deactivateLink = $('.wp-list-table tr[data-plugin="<?php echo $plugin_slug; ?>"] .deactivate a');
                    var deactivateUrl = $deactivateLink.attr('href');

                    if (!$deactivateLink.length) return;

                    $deactivateLink.on('click', function (e) {
                        e.preventDefault();
                        $modal.fadeIn(200);
                    });

                    $('input[name="reason"]').on('change', function () {
                        $('#ip-feedback-text-container').slideDown(200);
                    });

                    $('#insightpress-skip-deactivate').on('click', function () {
                        window.location.href = deactivateUrl;
                    });

                    $('#insightpress-submit-deactivate').on('click', function () {
                        var $btn = $(this);
                        var reason = $('input[name="reason"]:checked').val();
                        var message = $('#insightpress-feedback-message').val();

                        if (!reason) {
                            alert('Please select a reason or skip.');
                            return;
                        }

                        $btn.prop('disabled', true).text('Processing...');

                        $.post(ajaxurl, {
                            action: 'insightpress_deactivation_feedback',
                            reason: reason,
                            message: message,
                            nonce: '<?php echo wp_create_nonce("insightpress_feedback_nonce"); ?>'
                        }).always(function () {
                            window.location.href = deactivateUrl;
                        });
                    });

                    // Close modal when clicking outside
                    $(window).on('click', function (e) {
                        if ($(e.target).is($modal)) {
                            $modal.fadeOut(200);
                        }
                    });
                });
            })(jQuery);
        </script>
        <?php
    }

    public static function handle_feedback()
    {
        check_ajax_referer('insightpress_feedback_nonce', 'nonce');

        $reason = isset($_POST['reason']) ? sanitize_text_field($_POST['reason']) : 'unknown';
        $message = isset($_POST['message']) ? sanitize_textarea_field($_POST['message']) : '';

        if (class_exists('InsightPress_Event_Tracker')) {
            InsightPress_Event_Tracker::send_event('deactivation_feedback', [
                'reason' => $reason,
                'feedback_message' => $message
            ]);
        }

        wp_send_json_success();
    }
}
