<?php
/**
 * DeactivationModal - Renders the deactivation questionnaire modal on plugins.php.
 *
 * Intercepts the plugin deactivation link click with JavaScript, shows
 * a modal asking why the user is deactivating and whether to remove data,
 * then submits the response via AJAX before following through with
 * the actual WordPress deactivation redirect.
 *
 * Displayed on: wp-admin/plugins.php only.
 * Triggered by: click on the "Deactivate" link for this plugin.
 *
 * @package UltraguardPro\modules\onboarding\pages
 */

namespace UltraguardPro\modules\onboarding\pages;

use UltraguardPro\Plugin;
use UltraguardPro\modules\onboarding\OnboardingModule;

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

class DeactivationModal {

    private Plugin $plugin;

    public function __construct( Plugin $plugin ) {
        $this->plugin = $plugin;
    }

    /**
     * Output the modal HTML + CSS + JS.
     * Called via admin_footer on plugins.php.
     */
    public function render(): void {
        $nonce    = wp_create_nonce( OnboardingModule::NONCE_ACTION );
        $basename = defined( 'ULTRAGUARD_PRO_BASENAME' ) ? ULTRAGUARD_PRO_BASENAME : 'ultraguard-security-suite/ultraguard-security-suite.php';
        $this->output_styles();
        $this->output_html();
        $this->output_scripts( $nonce, $basename );
    }

    // -------------------------------------------------------------------------
    // CSS
    // -------------------------------------------------------------------------
    private function output_styles(): void { ?>
<style id="ug-deact-css">
/* Modal overlay */
#ug-deact-overlay{display:none;position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,.55);z-index:100000;align-items:center;justify-content:center;padding:16px}
#ug-deact-overlay.visible{display:flex}
/* Modal card - flex column keeps header/footer always visible */
#ug-deact-modal{background:#fff;border-radius:10px;width:100%;max-width:480px;box-shadow:0 20px 60px rgba(0,0,0,.25);display:flex;flex-direction:column;max-height:calc(100vh - 80px);overflow:hidden}
/* Header - pinned, never scrolls */
.ug-dm-header{padding:14px 18px 12px;border-bottom:1px solid #e2e8f0;display:flex;align-items:center;gap:10px;flex-shrink:0;background:#fff}
.ug-dm-header-icon{width:34px;height:34px;border-radius:7px;background:linear-gradient(135deg,#0ea5e9,#38bdf8);display:flex;align-items:center;justify-content:center;flex-shrink:0}
.ug-dm-header-icon .dashicons{font-size:18px;width:18px;height:18px;color:#fff}
.ug-dm-title{font-size:15px;font-weight:700;color:#0f172a;margin:0}
.ug-dm-subtitle{font-size:11px;color:#64748b;margin:1px 0 0}
/* Body - scrolls when content overflows */
.ug-dm-body{padding:16px 18px;overflow-y:auto;flex:1 1 auto}
.ug-dm-label{font-size:13px;font-weight:600;color:#334155;margin-bottom:10px;display:block}
/* Reason radio list */
.ug-dm-reasons{list-style:none;margin:0 0 12px;padding:0;display:flex;flex-direction:column;gap:4px}
.ug-dm-reason{display:flex;align-items:flex-start;gap:10px;padding:7px 10px;border:1px solid #e2e8f0;border-radius:7px;cursor:pointer;transition:border-color 140ms,background 140ms}
.ug-dm-reason:hover{border-color:#94a3b8;background:#f8fafc}
.ug-dm-reason.selected{border-color:#0ea5e9;background:rgba(14,165,233,.05)}
.ug-dm-reason input[type=radio]{margin:2px 0 0;flex-shrink:0;accent-color:#0ea5e9}
.ug-dm-reason-text{font-size:13px;color:#334155;line-height:1.4}
/* Details textarea */
#ug-deact-details-wrap{display:none;margin-bottom:14px}
#ug-deact-details-wrap label{font-size:12px;font-weight:600;color:#64748b;display:block;margin-bottom:5px}
#ug-deact-details{width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px;resize:vertical;min-height:70px;font-family:inherit;color:#334155}
#ug-deact-details:focus{outline:none;border-color:#0ea5e9;box-shadow:0 0 0 3px rgba(14,165,233,.15)}
/* Data removal section */
.ug-dm-removal{background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:12px;margin-bottom:4px}
.ug-dm-removal-title{font-size:12px;font-weight:700;color:#475569;text-transform:uppercase;letter-spacing:.6px;margin-bottom:10px}
.ug-dm-removal-opts{display:flex;flex-direction:column;gap:7px}
.ug-dm-removal-opt{display:flex;align-items:flex-start;gap:9px;cursor:pointer}
.ug-dm-removal-opt input{margin:2px 0 0;flex-shrink:0;accent-color:#0ea5e9}
.ug-dm-removal-opt-body{}
.ug-dm-removal-opt-name{font-size:13px;font-weight:600;color:#334155}
.ug-dm-removal-opt-desc{font-size:11px;color:#64748b;margin-top:1px;line-height:1.4}
.ug-dm-removal-warn{font-size:11px;color:#b45309;margin-top:8px;padding:7px 9px;background:rgba(245,158,11,.08);border:1px solid rgba(245,158,11,.25);border-radius:5px;display:none}
/* Footer */
.ug-dm-footer{padding:12px 18px;border-top:1px solid #e2e8f0;display:flex;justify-content:space-between;align-items:center;gap:10px;background:#f8fafc;flex-shrink:0}
.ug-dm-skip{font-size:12px;color:#94a3b8;background:none;border:none;cursor:pointer;padding:0;text-decoration:underline}
.ug-dm-skip:hover{color:#64748b}
.ug-dm-deact-btn{padding:8px 18px;background:#0ea5e9;color:#fff;border:none;border-radius:7px;font-size:13px;font-weight:600;cursor:pointer;transition:background 150ms;display:flex;align-items:center;gap:7px}
.ug-dm-deact-btn:hover{background:#0284c7}
.ug-dm-deact-btn:disabled{opacity:.6;cursor:not-allowed}
.ug-dm-cancel-btn{padding:8px 16px;background:#fff;color:#475569;border:1px solid #e2e8f0;border-radius:7px;font-size:13px;font-weight:600;cursor:pointer;transition:border-color 150ms}
.ug-dm-cancel-btn:hover{border-color:#94a3b8}
/* Spinner */
.ug-dm-spin{display:inline-block;width:12px;height:12px;border-radius:50%;border:2px solid rgba(255,255,255,.35);border-top-color:#fff;animation:ugDmSpin .6s linear infinite}
@keyframes ugDmSpin{to{transform:rotate(360deg)}}
</style>
<?php
    }

    // -------------------------------------------------------------------------
    // HTML
    // -------------------------------------------------------------------------
    private function output_html(): void { ?>
<div id="ug-deact-overlay" role="dialog" aria-modal="true" aria-labelledby="ug-dm-title-text">
    <div id="ug-deact-modal">

        <div class="ug-dm-header">
            <div class="ug-dm-header-icon"><span class="dashicons dashicons-shield-alt"></span></div>
            <div>
                <p class="ug-dm-title" id="ug-dm-title-text"><?php esc_html_e( 'Before You Go...', 'ultraguard-security-suite' ); ?></p>
                <p class="ug-dm-subtitle"><?php esc_html_e( 'UltraGuard Pro - Quick Feedback', 'ultraguard-security-suite' ); ?></p>
            </div>
        </div>

        <div class="ug-dm-body">
            <span class="ug-dm-label"><?php esc_html_e( 'Why are you deactivating UltraGuard Pro?', 'ultraguard-security-suite' ); ?></span>

            <ul class="ug-dm-reasons" role="radiogroup">
                <?php
                $reasons = [
                    'temporary'       => __( 'Temporary deactivation - I\'ll be back',     'ultraguard-security-suite' ),
                    'better_plugin'   => __( 'Found a better security plugin',               'ultraguard-security-suite' ),
                    'missing_feature' => __( 'Missing a feature I need',                     'ultraguard-security-suite' ),
                    'too_complex'     => __( 'Too complex / hard to configure',               'ultraguard-security-suite' ),
                    'performance'     => __( 'Slowing down my site',                          'ultraguard-security-suite' ),
                    'bugs'            => __( 'Plugin has bugs or issues',                     'ultraguard-security-suite' ),
                    'no_longer_need'  => __( 'I no longer need a security plugin',            'ultraguard-security-suite' ),
                    'other'           => __( 'Other reason',                                  'ultraguard-security-suite' ),
                ];
                foreach ( $reasons as $value => $label ) :
                ?>
                <li class="ug-dm-reason" data-value="<?php echo esc_attr( $value ); ?>">
                    <input type="radio" name="ug_deact_reason" value="<?php echo esc_attr( $value ); ?>" id="ugdr-<?php echo esc_attr( $value ); ?>">
                    <label class="ug-dm-reason-text" for="ugdr-<?php echo esc_attr( $value ); ?>"><?php echo esc_html( $label ); ?></label>
                </li>
                <?php endforeach; ?>
            </ul>

            <div id="ug-deact-details-wrap">
                <label for="ug-deact-details"><?php esc_html_e( 'Tell us more (optional):', 'ultraguard-security-suite' ); ?></label>
                <textarea id="ug-deact-details" placeholder="<?php esc_attr_e( 'Your feedback helps us improve UltraGuard Pro...', 'ultraguard-security-suite' ); ?>"></textarea>
            </div>

            <div class="ug-dm-removal">
                <div class="ug-dm-removal-title"><?php esc_html_e( 'Data & Settings', 'ultraguard-security-suite' ); ?></div>
                <div class="ug-dm-removal-opts" role="radiogroup">

                    <label class="ug-dm-removal-opt">
                        <input type="radio" name="ug_remove_data" value="none" checked>
                        <div class="ug-dm-removal-opt-body">
                            <div class="ug-dm-removal-opt-name"><?php esc_html_e( 'Keep all data', 'ultraguard-security-suite' ); ?></div>
                            <div class="ug-dm-removal-opt-desc"><?php esc_html_e( 'Settings, logs, and DB tables are preserved. You can reactivate and pick up where you left off.', 'ultraguard-security-suite' ); ?></div>
                        </div>
                    </label>

                    <label class="ug-dm-removal-opt">
                        <input type="radio" name="ug_remove_data" value="soft">
                        <div class="ug-dm-removal-opt-body">
                            <div class="ug-dm-removal-opt-name"><?php esc_html_e( 'Remove settings only', 'ultraguard-security-suite' ); ?></div>
                            <div class="ug-dm-removal-opt-desc"><?php esc_html_e( 'Deletes plugin settings and cached data, but keeps database tables and scan history.', 'ultraguard-security-suite' ); ?></div>
                        </div>
                    </label>

                    <label class="ug-dm-removal-opt">
                        <input type="radio" name="ug_remove_data" value="full" id="ug-remove-full">
                        <div class="ug-dm-removal-opt-body">
                            <div class="ug-dm-removal-opt-name"><?php esc_html_e( 'Remove everything', 'ultraguard-security-suite' ); ?></div>
                            <div class="ug-dm-removal-opt-desc"><?php esc_html_e( 'Deletes all settings, database tables, scan history, and uploaded files. Cannot be undone.', 'ultraguard-security-suite' ); ?></div>
                        </div>
                    </label>

                </div>
                <div class="ug-dm-removal-warn" id="ug-removal-warn">
                    <?php esc_html_e( 'Warning: All plugin data will be permanently deleted. This cannot be undone.', 'ultraguard-security-suite' ); ?>
                </div>
            </div>
        </div>

        <div class="ug-dm-footer">
            <button type="button" class="ug-dm-skip" id="ug-dm-skip"><?php esc_html_e( 'Skip & Deactivate', 'ultraguard-security-suite' ); ?></button>
            <div style="display:flex;gap:8px;">
                <button type="button" class="ug-dm-cancel-btn" id="ug-dm-cancel"><?php esc_html_e( 'Cancel', 'ultraguard-security-suite' ); ?></button>
                <button type="button" class="ug-dm-deact-btn" id="ug-dm-submit">
                    <span class="dashicons dashicons-no-alt" style="font-size:15px;width:15px;height:15px;"></span>
                    <?php esc_html_e( 'Deactivate', 'ultraguard-security-suite' ); ?>
                </button>
            </div>
        </div>

    </div>
</div>
<?php
    }

    // -------------------------------------------------------------------------
    // JS
    // -------------------------------------------------------------------------
    private function output_scripts( string $nonce, string $basename ): void { ?>
<script id="ug-deact-js">
(function(){
'use strict';
var NONCE   = <?php echo wp_json_encode( $nonce ); ?>;
                    var AJAXURL = <?php echo wp_json_encode( self_admin_url( 'admin-ajax.php' ) ); ?>;
var PLUGIN  = <?php echo wp_json_encode( $basename ); ?>;

var overlay  = document.getElementById('ug-deact-overlay');
var submitBtn = document.getElementById('ug-dm-submit');
var cancelBtn = document.getElementById('ug-dm-cancel');
var skipBtn  = document.getElementById('ug-dm-skip');
var detailsWrap = document.getElementById('ug-deact-details-wrap');
var removalWarn = document.getElementById('ug-removal-warn');
var deactLink = null;  // Will be set when intercepted

// ---- Intercept the WP deactivate link for this plugin ----
document.addEventListener('DOMContentLoaded', function(){
    // The deactivation link href contains action=deactivate and the plugin slug.
    var allLinks = document.querySelectorAll('a[href*="action=deactivate"]');
    allLinks.forEach(function(link){
        if(link.href.indexOf(encodeURIComponent(PLUGIN)) >= 0 ||
           link.href.indexOf(PLUGIN.replace(/\//g,'%2F')) >= 0 ||
           link.href.indexOf(PLUGIN) >= 0){
            link.addEventListener('click', function(e){
                e.preventDefault();
                deactLink = link.href; // Save for skip-path fallback
                showModal();
            });
        }
    });

    // ---- Reason radio selection ----
    document.querySelectorAll('.ug-dm-reason').forEach(function(item){
        item.addEventListener('click', function(){
            document.querySelectorAll('.ug-dm-reason').forEach(function(r){r.classList.remove('selected');});
            item.classList.add('selected');
            var radio = item.querySelector('input[type=radio]');
            if(radio) radio.checked = true;
            // Show details textarea for some reasons
            var showDetails = ['bugs','missing_feature','better_plugin','other'];
            detailsWrap.style.display = showDetails.indexOf(radio.value) >= 0 ? '' : 'none';
        });
    });

    // ---- Full removal warning ----
    document.querySelectorAll('input[name=ug_remove_data]').forEach(function(radio){
        radio.addEventListener('change', function(){
            removalWarn.style.display = this.value === 'full' ? '' : 'none';
        });
    });

    // ---- Cancel ----
    cancelBtn.addEventListener('click', hideModal);

    // ---- Click outside to cancel ----
    overlay.addEventListener('click', function(e){
        if(e.target === overlay) hideModal();
    });

    // ---- Escape key ----
    document.addEventListener('keydown', function(e){
        if(e.key === 'Escape' && overlay.classList.contains('visible')) hideModal();
    });

    // ---- Skip (no questionnaire) ----
    skipBtn.addEventListener('click', function(){
        setBusy(true, '<?php echo esc_js( __( 'Deactivating...', 'ultraguard-security-suite' ) ); ?>');
        post('ultraguard_deactivation_skip', {}).then(function(r){
            if(r.success && r.data.redirect) location.href = r.data.redirect;
            else fallbackDeactivate();
        }).catch(fallbackDeactivate);
    });

    // ---- Submit with questionnaire ----
    submitBtn.addEventListener('click', function(){
        var reason     = getCheckedValue('ug_deact_reason') || 'no_reason';
        var details    = document.getElementById('ug-deact-details').value.trim().substring(0, 500);
        var removeData = getCheckedValue('ug_remove_data') || 'none';

        if(removeData === 'full'){
            if(!confirm('<?php echo esc_js( __( 'This will permanently delete all plugin data including your security logs and scan history. Are you sure?', 'ultraguard-security-suite' ) ); ?>')){
                return;
            }
        }

        setBusy(true, '<?php echo esc_js( __( 'Processing...', 'ultraguard-security-suite' ) ); ?>');

        post('ultraguard_deactivation_submit', {
            reason      : reason,
            details     : details,
            remove_data : removeData
        }).then(function(r){
            if(r.success && r.data.redirect) location.href = r.data.redirect;
            else fallbackDeactivate();
        }).catch(fallbackDeactivate);
    });
});

function showModal(){
    overlay.classList.add('visible');
    document.body.style.overflow = 'hidden';
}
function hideModal(){
    overlay.classList.remove('visible');
    document.body.style.overflow = '';
}
function setBusy(busy, label){
    submitBtn.disabled = busy;
    skipBtn.disabled   = busy;
    cancelBtn.disabled = busy;
    if(busy){
        submitBtn.innerHTML = '<span class="ug-dm-spin"></span> ' + escHtml(label);
    } else {
        submitBtn.innerHTML = '<span class="dashicons dashicons-no-alt" style="font-size:15px;width:15px;height:15px;"></span> <?php echo esc_js( __( 'Deactivate', 'ultraguard-security-suite' ) ); ?>';
    }
}
function fallbackDeactivate(){
    // If AJAX fails, just follow the original deactivation link.
    if(deactLink) location.href = deactLink;
}
function getCheckedValue(name){
    var el = document.querySelector('input[name="'+name+'"]:checked');
    return el ? el.value : null;
}
function post(action, data){
    var params = {action: action, nonce: NONCE};
    Object.keys(data).forEach(function(k){ params[k] = data[k]; });
    var body = new URLSearchParams(params);
    return fetch(AJAXURL, {method:'POST', body:body})
        .then(function(r){ return r.json(); })
        .then(function(res){
            if(!res.success && res.data && res.data.message) throw new Error(res.data.message);
            return res;
        });
}
function escHtml(s){
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
}());
</script>
<?php
    }
}
