<?php

namespace SoftminalB2B;

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

/**
 * Deactivation feedback survey.
 *
 * Shows a modal when the admin clicks "Deactivate" on the plugin's row of the
 * Plugins screen. The user can pick a reason and submit it, or skip — either way
 * the deactivation proceeds. Feedback is only sent on an explicit submit; the
 * network call is handled server-side by FeedbackController.
 *
 * Self-contained: renders its own markup in the admin footer with inlined CSS +
 * vanilla JS (no Vue/Vite), so it works on plugins.php, which is outside the SPA.
 * Styles/behaviour are inlined rather than shipped as asset files because the
 * build only ships assets/config/includes/lib/vendor/languages, not resources/.
 */
class DeactivationSurvey
{
    public static function init(): void
    {
        add_action('current_screen', [self::class, 'maybeHook']);
    }

    /**
     * Engage only on the Plugins screen, and only for users who can deactivate.
     */
    public static function maybeHook($screen): void
    {
        if (!($screen instanceof \WP_Screen) || $screen->id !== 'plugins') {
            return;
        }

        if (!current_user_can('activate_plugins')) {
            return;
        }

        add_action('admin_footer', [self::class, 'render']);
    }

    /**
     * The survey reasons. A `placeholder` marks an optional free-text follow-up.
     *
     * @return array<int,array<string,string>>
     */
    private static function reasons(): array
    {
        return [
            [
                'id'    => 'no_longer',
                'label' => __('I no longer need the plugin', 'softminal-b2b-wholesale-for-woocommerce'),
            ],
            [
                'id'          => 'better_found',
                'label'       => __('I found a better plugin', 'softminal-b2b-wholesale-for-woocommerce'),
                'placeholder' => __('Which plugin? (optional)', 'softminal-b2b-wholesale-for-woocommerce'),
            ],
            [
                'id'          => 'not_working',
                'label'       => __("I couldn't get the plugin to work", 'softminal-b2b-wholesale-for-woocommerce'),
                'placeholder' => __("What went wrong? We'd love to help. (optional)", 'softminal-b2b-wholesale-for-woocommerce'),
            ],
            [
                'id'    => 'temporary',
                'label' => __("It's a temporary deactivation", 'softminal-b2b-wholesale-for-woocommerce'),
            ],
            [
                'id'          => 'too_complex',
                'label'       => __("I don't know how to use it", 'softminal-b2b-wholesale-for-woocommerce'),
                'placeholder' => __('What were you trying to do? (optional)', 'softminal-b2b-wholesale-for-woocommerce'),
            ],
            [
                'id'          => 'other',
                'label'       => __('Other', 'softminal-b2b-wholesale-for-woocommerce'),
                'placeholder' => __('Please tell us more (optional)', 'softminal-b2b-wholesale-for-woocommerce'),
            ],
        ];
    }

    /**
     * Output the modal markup, styles and behaviour.
     */
    public static function render(): void
    {
        $basename = plugin_basename(SMB2B_DIR . 'softminal-b2b-wholesale-for-woocommerce.php');

        self::enqueueStyles();
        self::enqueueScript($basename);
        ?>
        <div id="smb2b-deactivate-modal" class="smb2b-deactivate-modal" aria-hidden="true">
            <div class="smb2b-deactivate-overlay" data-smb2b-close></div>
            <div class="smb2b-deactivate-box" role="dialog" aria-modal="true" aria-labelledby="smb2b-deactivate-title">
                <button type="button" class="smb2b-deactivate-x" data-smb2b-close aria-label="<?php echo esc_attr__('Close', 'softminal-b2b-wholesale-for-woocommerce'); ?>">&times;</button>

                <h2 id="smb2b-deactivate-title" class="smb2b-deactivate-title">
                    <?php echo esc_html__('Quick question before you go', 'softminal-b2b-wholesale-for-woocommerce'); ?>
                </h2>
                <p class="smb2b-deactivate-subtitle">
                    <?php echo esc_html__('If you have a moment, please let us know why you are deactivating B2B Suite. It helps us improve.', 'softminal-b2b-wholesale-for-woocommerce'); ?>
                </p>

                <div class="smb2b-deactivate-reasons">
                    <?php foreach (self::reasons() as $reason) : ?>
                        <label class="smb2b-deactivate-reason">
                            <input type="radio" name="smb2b_reason" value="<?php echo esc_attr($reason['id']); ?>">
                            <span><?php echo esc_html($reason['label']); ?></span>
                        </label>
                        <?php if (!empty($reason['placeholder'])) : ?>
                            <div class="smb2b-deactivate-detail" data-for="<?php echo esc_attr($reason['id']); ?>" style="display:none;">
                                <textarea rows="2" placeholder="<?php echo esc_attr($reason['placeholder']); ?>"></textarea>
                            </div>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </div>

                <div class="smb2b-deactivate-actions">
                    <button type="button" class="button smb2b-deactivate-skip" data-smb2b-skip>
                        <?php echo esc_html__('Skip & Deactivate', 'softminal-b2b-wholesale-for-woocommerce'); ?>
                    </button>
                    <button type="button" class="button button-primary smb2b-deactivate-submit" data-smb2b-submit>
                        <?php echo esc_html__('Submit & Deactivate', 'softminal-b2b-wholesale-for-woocommerce'); ?>
                    </button>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Inline the modal CSS on a registered (source-less) handle.
     */
    private static function enqueueStyles(): void
    {
        wp_register_style('smb2b-deactivate-survey', false, [], SMB2B_VERSION);
        wp_enqueue_style('smb2b-deactivate-survey');

        $css = <<<'CSS'
.smb2b-deactivate-modal { display: none; position: fixed; inset: 0; z-index: 100000; }
.smb2b-deactivate-modal.is-open { display: block; }
body.smb2b-deactivate-open { overflow: hidden; }
.smb2b-deactivate-overlay { position: absolute; inset: 0; background: rgba(0,0,0,.55); }
.smb2b-deactivate-box {
    position: relative; z-index: 1; width: 100%; max-width: 480px; margin: 8vh auto 0;
    background: #fff; border-radius: 8px; box-shadow: 0 10px 40px rgba(0,0,0,.25);
    padding: 28px 28px 22px; box-sizing: border-box; animation: smb2b-deactivate-in .18s ease-out;
}
@keyframes smb2b-deactivate-in { from { opacity: 0; transform: translateY(-12px); } to { opacity: 1; transform: translateY(0); } }
.smb2b-deactivate-x {
    position: absolute; top: 10px; right: 12px; border: 0; background: none; cursor: pointer;
    font-size: 22px; line-height: 1; color: #787c82;
}
.smb2b-deactivate-x:hover { color: #1d2327; }
.smb2b-deactivate-title { margin: 0 0 6px; font-size: 18px; font-weight: 600; }
.smb2b-deactivate-subtitle { margin: 0 0 18px; color: #646970; font-size: 13px; line-height: 1.5; }
.smb2b-deactivate-reasons { display: flex; flex-direction: column; gap: 4px; margin-bottom: 20px; }
.smb2b-deactivate-reason { display: flex; align-items: center; gap: 9px; padding: 7px 4px; cursor: pointer; font-size: 13px; }
.smb2b-deactivate-reason input { margin: 0; }
.smb2b-deactivate-detail { padding: 0 4px 6px 26px; }
.smb2b-deactivate-detail textarea {
    width: 100%; box-sizing: border-box; resize: vertical; font-size: 13px;
    border: 1px solid #dcdcde; border-radius: 4px; padding: 7px 9px;
}
.smb2b-deactivate-detail textarea:focus { border-color: #6D5EF5; box-shadow: 0 0 0 1px #6D5EF5; outline: none; }
.smb2b-deactivate-actions { display: flex; justify-content: flex-end; gap: 10px; }
.smb2b-deactivate-submit.button-primary { background: #6D5EF5; border-color: #6D5EF5; }
.smb2b-deactivate-submit.button-primary:hover { background: #5b4de0; border-color: #5b4de0; }
CSS;

        wp_add_inline_style('smb2b-deactivate-survey', $css);
    }

    /**
     * Register a source-less script handle, localise config, attach the handler.
     */
    private static function enqueueScript(string $basename): void
    {
        wp_register_script('smb2b-deactivate-survey', false, [], SMB2B_VERSION, true);
        wp_enqueue_script('smb2b-deactivate-survey');

        wp_localize_script('smb2b-deactivate-survey', 'smb2bDeactivation', [
            'plugin'  => $basename,
            'restUrl' => rest_url(SMB2B_API_NAMESPACE . '/feedback/deactivation'),
            'nonce'   => wp_create_nonce('wp_rest'),
        ]);

        $js = <<<'JS'
(function () {
    var cfg = window.smb2bDeactivation || {};
    var modal = document.getElementById('smb2b-deactivate-modal');
    if (!modal || !cfg.plugin) { return; }

    var link = document.querySelector('tr[data-plugin="' + cfg.plugin + '"] span.deactivate a');
    if (!link) { return; }

    var deactivateUrl = link.getAttribute('href');

    function open() {
        modal.classList.add('is-open');
        modal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('smb2b-deactivate-open');
    }
    function close() {
        modal.classList.remove('is-open');
        modal.setAttribute('aria-hidden', 'true');
        document.body.classList.remove('smb2b-deactivate-open');
    }
    function go() { window.location.href = deactivateUrl; }

    link.addEventListener('click', function (e) { e.preventDefault(); open(); });

    modal.querySelectorAll('input[name="smb2b_reason"]').forEach(function (radio) {
        radio.addEventListener('change', function () {
            modal.querySelectorAll('.smb2b-deactivate-detail').forEach(function (d) { d.style.display = 'none'; });
            var detail = modal.querySelector('.smb2b-deactivate-detail[data-for="' + radio.value + '"]');
            if (detail) {
                detail.style.display = 'block';
                var field = detail.querySelector('textarea, input');
                if (field) { field.focus(); }
            }
        });
    });

    modal.querySelectorAll('[data-smb2b-close]').forEach(function (el) {
        el.addEventListener('click', function (e) { e.preventDefault(); close(); });
    });
    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && modal.classList.contains('is-open')) { close(); }
    });

    var skip = modal.querySelector('[data-smb2b-skip]');
    if (skip) { skip.addEventListener('click', function (e) { e.preventDefault(); go(); }); }

    var submit = modal.querySelector('[data-smb2b-submit]');
    if (submit) {
        submit.addEventListener('click', function (e) {
            e.preventDefault();
            var checked = modal.querySelector('input[name="smb2b_reason"]:checked');
            if (!checked) { go(); return; }

            var reason = checked.value;
            var detail = modal.querySelector('.smb2b-deactivate-detail[data-for="' + reason + '"] textarea, .smb2b-deactivate-detail[data-for="' + reason + '"] input');
            var message = detail ? detail.value : '';

            submit.disabled = true;

            // Never trap the user: deactivate even if the request hangs or fails.
            var done = false;
            function finish() { if (done) { return; } done = true; go(); }
            setTimeout(finish, 2500);

            try {
                fetch(cfg.restUrl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': cfg.nonce },
                    body: JSON.stringify({ reason: reason, message: message })
                }).then(finish).catch(finish);
            } catch (err) { finish(); }
        });
    }
})();
JS;

        wp_add_inline_script('smb2b-deactivate-survey', $js);
    }
}
