<?php
/**
 * Deactivator functionality for deactivation popup and API logging.
 *
 * @package Preciousuite_Gold_Buyback_Quote_Calculator
 */

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

/**
 * Register Deactivation Hook
 */
register_deactivation_hook(PRECIOUSUITE_PATH . 'preciousuite-gold-buyback-quote-calculator.php', 'preciousuite_deactivation_hook_handler');

function preciousuite_deactivation_hook_handler()
{
    $reason = get_transient('preciousuite_deactivation_reason') ?: '';
    delete_transient('preciousuite_deactivation_reason');

    $plugin_data = preciousuite_deactivation_get_plugin_data();
    $admin_email = $plugin_data['admin_email'];

    $token = preciousuite_deactivation_get_token();
    if (!$token) {
        return;
    }

    $search = preciousuite_deactivation_search_email($token, $admin_email);

    $payload = array(
        'plugin' => 'preciousuite-gold-buyback-quote-calculator',
        'site_url' => $plugin_data['site_url'],
        'email' => $admin_email,
        'store_country' => $plugin_data['country_info'],
        'plugin_version' => $plugin_data['plugin_version'],
        'eStatus' => 'deactivate',
        'reason' => $reason,
        'type' => 'wordpress',
    );

    if ($search && isset($search['success']) && $search['success'] === false) {
        preciousuite_deactivation_store_log($token, $payload);
    } else {
        preciousuite_deactivation_update_log($admin_email, array(
            'eStatus' => 'deactivate',
            'plugin' => 'preciousuite-gold-buyback-quote-calculator',
            'reason' => $reason,
            'type' => 'wordpress',
        ));
    }
}

/**
 * Deactivation Modal — plugins.php footer
 */
add_action('admin_footer', 'preciousuite_deactivation_modal_html');
function preciousuite_deactivation_modal_html()
{
    global $pagenow;
    if ($pagenow !== 'plugins.php') {
        return;
    }
    ?>
    <div id="preciousuite-deactivation-modal"
        title="<?php echo esc_attr__('Why are you deactivating?', 'preciousuite-gold-buyback-quote-calculator'); ?>"
        style="display:none;">
        <p style="margin-bottom:15px;">
            <?php esc_html_e('Before you deactivate, please let us know why. Your feedback helps us improve!', 'preciousuite-gold-buyback-quote-calculator'); ?>
        </p>
        <div style="margin-bottom:10px;">
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_deactivation_reason" value="Need customization for my requirement"
                    style="margin-right:8px;">
                <?php esc_html_e('Need customization for my requirement', 'preciousuite-gold-buyback-quote-calculator'); ?>
            </label>
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_deactivation_reason" value="Need live metal rate updates"
                    style="margin-right:8px;">
                <?php esc_html_e('Need live metal rate updates', 'preciousuite-gold-buyback-quote-calculator'); ?>
            </label>
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_deactivation_reason" value="Plugin is not working"
                    style="margin-right:8px;">
                <?php esc_html_e('Plugin is not working', 'preciousuite-gold-buyback-quote-calculator'); ?>
            </label>
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_deactivation_reason" value="Found a better plugin"
                    style="margin-right:8px;">
                <?php esc_html_e('Found a better plugin', 'preciousuite-gold-buyback-quote-calculator'); ?>
            </label>
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_deactivation_reason" value="No longer needed"
                    style="margin-right:8px;">
                <?php esc_html_e('No longer needed', 'preciousuite-gold-buyback-quote-calculator'); ?>
            </label>
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_deactivation_reason" value="Temporary deactivation - I'll be back"
                    style="margin-right:8px;">
                <?php esc_html_e("Temporary deactivation - I'll be back", 'preciousuite-gold-buyback-quote-calculator'); ?>
            </label>
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_deactivation_reason" value="other" style="margin-right:8px;">
                <?php esc_html_e('Other', 'preciousuite-gold-buyback-quote-calculator'); ?>
            </label>
        </div>
        <div id="preciousuite-deactivation-custom-wrap" style="display:none;margin-top:10px;">
            <label><?php esc_html_e('Please specify:', 'preciousuite-gold-buyback-quote-calculator'); ?></label><br>
            <textarea id="preciousuite-deactivation-custom-reason" rows="3" cols="50"
                placeholder="<?php esc_attr_e('Your reason...', 'preciousuite-gold-buyback-quote-calculator'); ?>"
                style="width:100%;margin-top:5px;"></textarea>
        </div>
    </div>

    <script type="text/javascript">
        jQuery(document).ready(function ($) {
            var preciousuiteDeactivateUrl = '';

            $(document).on('click', 'a[href*="action=deactivate"][href*="preciousuite-gold-buyback-quote-calculator"]', function (e) {
                e.preventDefault();
                preciousuiteDeactivateUrl = $(this).attr('href');

                // Reset modal state
                $('input[name="preciousuite_deactivation_reason"]').prop('checked', false);
                $('#preciousuite-deactivation-custom-wrap').hide();
                $('#preciousuite-deactivation-custom-reason').val('');

                $('#preciousuite-deactivation-modal').dialog({
                    modal: true,
                    width: 500,
                    closeOnEscape: false,
                    draggable: false,
                    resizable: false,
                    buttons: {
                        '<?php echo html_entity_decode(esc_js(__('Submit & Deactivate', 'preciousuite-gold-buyback-quote-calculator')), ENT_QUOTES, 'UTF-8'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>': function () {
                            var selected = $('input[name="preciousuite_deactivation_reason"]:checked').val();
                            var custom = $('#preciousuite-deactivation-custom-reason').val().trim();

                            if (!selected) {
                                alert('<?php echo esc_js(__('Please select a reason.', 'preciousuite-gold-buyback-quote-calculator')); ?>');
                                return;
                            }
                            if (selected === 'other' && !custom) {
                                alert('<?php echo esc_js(__('Please provide a custom reason.', 'preciousuite-gold-buyback-quote-calculator')); ?>');
                                return;
                            }

                            var finalReason = (selected === 'other') ? custom : selected;

                            $.post('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
                                action: 'preciousuite_store_deactivation_reason',
                                reason: finalReason,
                                nonce: '<?php echo esc_js(wp_create_nonce('preciousuite_deactivation_nonce')); ?>'
                            }, function () {
                                window.location.href = preciousuiteDeactivateUrl;
                            });
                        },
                        '<?php echo html_entity_decode(esc_js(__('Cancel', 'preciousuite-gold-buyback-quote-calculator')), ENT_QUOTES, 'UTF-8'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>': function () {
                            $(this).dialog('close');
                        }
                    }
                });

                return false;
            });

            // Toggle custom reason textarea
            $(document).on('change', 'input[name="preciousuite_deactivation_reason"]', function () {
                if ($(this).val() === 'other') {
                    $('#preciousuite-deactivation-custom-wrap').show();
                } else {
                    $('#preciousuite-deactivation-custom-wrap').hide();
                    $('#preciousuite-deactivation-custom-reason').val('');
                }
            });
        });
    </script>
    <?php
}

/**
 * AJAX — Store deactivation reason in transient
 */
add_action('wp_ajax_preciousuite_store_deactivation_reason', 'preciousuite_store_deactivation_reason');
function preciousuite_store_deactivation_reason()
{
    if (
        !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')), // phpcs:ignore WordPress.Security.NonceVerification.Missing
            'preciousuite_deactivation_nonce'
        )
    ) {
        wp_die('Security check failed');
    }

    $reason = sanitize_text_field(wp_unslash($_POST['reason'] ?? '')); // phpcs:ignore WordPress.Security.NonceVerification.Missing
    if (!empty($reason)) {
        // Max 500 chars, 1 hour transient
        set_transient('preciousuite_deactivation_reason', substr($reason, 0, 500), HOUR_IN_SECONDS);
    }

    wp_die();
}

/**
 * Portal API Helper Functions
 */
function preciousuite_deactivation_get_token()
{
    $response = wp_remote_post('https://portal.preciousuite.com/api/auth/token', array(
        'body' => wp_json_encode(array(
            'email' => 'admin@gmail.com',
            'password' => 'admin@123',
        )),
        'headers' => array('Content-Type' => 'application/json'),
        'timeout' => 15,
    ));

    if (is_wp_error($response)) {
        return false;
    }

    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    return ($data && !empty($data['success']) && !empty($data['data']['token']))
        ? $data['data']['token']
        : false;
}

function preciousuite_deactivation_search_email($token, $email)
{
    $url = 'https://portal.preciousuite.com/api/plugin-log/search/email'
        . '?email=' . urlencode($email)
        . '&plugin=' . urlencode('preciousuite-gold-buyback-quote-calculator');

    $response = wp_remote_get($url, array(
        'headers' => array('Authorization' => 'Bearer ' . $token),
        'timeout' => 15,
    ));

    if (is_wp_error($response)) {
        return false;
    }

    $body = wp_remote_retrieve_body($response);
    return json_decode($body, true);
}

function preciousuite_deactivation_store_log($token, $log_data)
{
    $response = wp_remote_post('https://portal.preciousuite.com/api/plugin-log/store', array(
        'body' => wp_json_encode($log_data),
        'headers' => array(
            'Authorization' => 'Bearer ' . $token,
            'Content-Type' => 'application/json',
        ),
        'timeout' => 15,
    ));

    if (is_wp_error($response)) {
        return false;
    }

    $body = wp_remote_retrieve_body($response);
    return json_decode($body, true);
}

function preciousuite_deactivation_update_log($email, $update_data)
{
    $token = preciousuite_deactivation_get_token();
    if (!$token) {
        return false;
    }

    $url = 'https://portal.preciousuite.com/api/plugin-log/update/email?email=' . urlencode($email);

    $response = wp_remote_post($url, array(
        'method' => 'PUT',
        'body' => wp_json_encode($update_data),
        'headers' => array(
            'Authorization' => 'Bearer ' . $token,
            'Content-Type' => 'application/json',
        ),
        'timeout' => 15,
    ));

    if (is_wp_error($response)) {
        return false;
    }

    $body = wp_remote_retrieve_body($response);
    return json_decode($body, true);
}

function preciousuite_deactivation_get_plugin_data()
{
    if (!function_exists('get_plugin_data')) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    $admin_users = get_users(array(
        'role' => 'administrator',
        'number' => 1,
        'orderby' => 'ID',
        'order' => 'ASC',
    ));
    $admin_email = !empty($admin_users) ? $admin_users[0]->user_email : get_option('admin_email');

    $country_info = 'WooCommerce not active';
    if (class_exists('WooCommerce')) {
        $country_raw = get_option('woocommerce_default_country');
        $country_code = explode(':', $country_raw)[0];
        $country_info = $country_code;
        if (class_exists('WC_Countries')) {
            $wc = new WC_Countries();
            $country_info = $wc->countries[$country_code] ?? $country_code;
        }
    }

    $pd = get_plugin_data(PRECIOUSUITE_PATH . 'preciousuite-gold-buyback-quote-calculator.php', false, false);

    return array(
        'admin_email' => $admin_email,
        'site_url' => get_site_url(),
        'country_info' => $country_info,
        'plugin_version' => $pd['Version'] ?? '1.0.0',
    );
}
