<?php

defined('ABSPATH') || exit;

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

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

        $plugin_slug = 'shopcentral/shopcentral.php';
        ?>
        <style>
            #shopcentral-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;
            }

            .shopcentral-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;
            }

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

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

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

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

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

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

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

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

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

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

            .shopcentral-button-primary {
                background-color: #2271b1;
                color: #fff;
            }

            .shopcentral-button-primary:hover {
                background-color: #135e96;
            }

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

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

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

        <div id="shopcentral-survey-modal">
            <div class="shopcentral-modal-content">
                <div class="shopcentral-modal-header">
                    <h2>We're sorry to see you go!</h2>
                    <p>If you have a moment, please let us know why you are deactivating ShopCentral. This information helps us
                        improve the plugin for everyone.</p>
                </div>

                <div class="shopcentral-survey-reasons">
                    <div class="shopcentral-reason">
                        <input type="radio" name="reason" id="reason-temporary" value="temporary">
                        <label for="reason-temporary">I'm only deactivating the plugin temporarily.</label>
                    </div>
                    <div class="shopcentral-reason">
                        <input type="radio" name="reason" id="reason-found_better" value="found_better">
                        <label for="reason-found_better">I found a better plugin.</label>
                    </div>
                    <div class="shopcentral-reason">
                        <input type="radio" name="reason" id="reason-too_complex" value="too_complex">
                        <label for="reason-too_complex">The plugin is too complex / hard to use.</label>
                    </div>
                    <div class="shopcentral-reason">
                        <input type="radio" name="reason" id="reason-not_needed" value="not_needed">
                        <label for="reason-not_needed">I don't need this plugin anymore.</label>
                    </div>
                    <div class="shopcentral-reason">
                        <input type="radio" name="reason" id="reason-not_working" value="not_working">
                        <label for="reason-not_working">The plugin is not working correctly.</label>
                    </div>
                    <div class="shopcentral-reason">
                        <input type="radio" name="reason" id="reason-other" value="other">
                        <label for="reason-other">Other</label>
                    </div>

                    <div id="feedback-text-container" class="shopcentral-feedback-text">
                        <textarea id="shopcentral-feedback-message"
                            placeholder="Please share more details (optional)"></textarea>
                    </div>
                </div>

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

        <script>
            (function ($) {
                $(function () {
                    var $modal = $('#shopcentral-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 () {
                        $('#feedback-text-container').slideDown(200);
                    });

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

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

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

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

                        $.post(ajaxurl, {
                            action: 'shopcentral_deactivation_feedback',
                            reason: reason,
                            message: message,
                            nonce: '<?php echo wp_create_nonce("shopcentral_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('shopcentral_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('ShopCentral_Event_Tracker')) {
            ShopCentral_Event_Tracker::send_event('deactivation_feedback', [
                'reason' => $reason,
                'feedback_message' => $message
            ]);
        }

        wp_send_json_success();
    }
}
