<?php
if (!defined('ABSPATH')) {
    exit;
}

register_deactivation_hook(PRECIOUSUITE_MRC_FILE, function () {
    $reason = get_transient('pmrcgold_deactivation_reason') ?: '';
    delete_transient('pmrcgold_deactivation_reason');

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

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

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

    $payload = array(
        'plugin' => 'preciousuite-metal-rate-charts',
        '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) {
        pmrcgold_deactivation_store_log($token, $payload);
    } else {
        pmrcgold_deactivation_update_log($admin_email, array(
            'eStatus' => 'deactivate',
            'plugin' => 'preciousuite-metal-rate-charts',
            'reason' => $reason,
            'type' => 'wordpress',
        ));
    }
});

add_action('admin_enqueue_scripts', 'pmrcgold_deactivation_enqueue_assets');
function pmrcgold_deactivation_enqueue_assets($hook)
{
    if ($hook === 'plugins.php') {
        wp_enqueue_script('jquery-ui-dialog');
        wp_enqueue_script('jquery-ui-button');
        wp_enqueue_script('jquery-ui-draggable');
        wp_enqueue_script('jquery-ui-resizable');
        wp_enqueue_script('jquery-ui-widget');
        wp_enqueue_script('jquery-ui-core');
        wp_enqueue_style('wp-jquery-ui-dialog');
    }
}

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

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

            $(document).on('click', 'a[href*="action=deactivate"][href*="preciousuite-metal-rate-charts"]', function (e) {
                e.preventDefault();
                deactivateUrl = $(this).attr('href');

                $('input[name="pmrcgold_deactivation_reason"]').prop('checked', false);
                $('#pmrcgold-deactivation-custom-wrap').hide();
                $('#pmrcgold-deactivation-custom-reason').val('');

                $('#pmrcgold-deactivation-modal').dialog({
                    modal: true,
                    width: 500,
                    closeOnEscape: false,
                    draggable: false,
                    resizable: false,
                    buttons: {
                        'Submit & Deactivate': function () {
                            var selected = $('input[name="pmrcgold_deactivation_reason"]:checked').val();
                            var custom = $('#pmrcgold-deactivation-custom-reason').val().trim();

                            if (!selected) {
                                alert('Please select a reason.');
                                return;
                            }
                            if (selected === 'other' && !custom) {
                                alert('Please provide a custom reason.');
                                return;
                            }

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

                            $.post('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
                                action: 'pmrcgold_store_deactivation_reason',
                                reason: finalReason,
                                nonce: '<?php echo esc_js(wp_create_nonce('pmrcgold_deactivation_nonce')); ?>'
                            }, function () {
                                window.location.href = deactivateUrl;
                            });
                        },
                        'Cancel': function () {
                            $(this).dialog('close');
                        }
                    }
                });

                return false;
            });

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

add_action('wp_ajax_pmrcgold_store_deactivation_reason', 'pmrcgold_store_deactivation_reason');
function pmrcgold_store_deactivation_reason()
{
    if (
        !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')),
            'pmrcgold_deactivation_nonce'
        )
    ) {
        wp_die('Security check failed');
    }

    $reason = sanitize_text_field(wp_unslash($_POST['reason'] ?? ''));
    if (!empty($reason)) {
        set_transient('pmrcgold_deactivation_reason', substr($reason, 0, 500), HOUR_IN_SECONDS);
    }

    wp_die();
}

function pmrcgold_deactivation_get_token()
{
    $response = wp_remote_post('https://portal.preciousuite.com/api/auth/token', array(
        'body' => 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 pmrcgold_deactivation_search_email($token, $email)
{
    $url = 'https://portal.preciousuite.com/api/plugin-log/search/email'
        . '?email=' . urlencode($email)
        . '&plugin=' . urlencode('preciousuite-metal-rate-charts');

    $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 pmrcgold_deactivation_store_log($token, $log_data)
{
    $response = wp_remote_post('https://portal.preciousuite.com/api/plugin-log/store', array(
        'body' => 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 pmrcgold_deactivation_update_log($email, $update_data)
{
    $token = pmrcgold_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' => 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 pmrcgold_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_MRC_FILE, false, false);

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