<?php
/**
 * Deactivate.php
 *
 * @since      1.0.0
 * @package    WcElectronInvoice
 * @author     alfiopiccione <alfio.piccione@gmail.com>

 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright (C) 2025 POP
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

namespace WcElectronInvoice;

if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

/**
 * Class Deactivate
 *
 * @since  1.0.0
 * @author alfiopiccione <alfio.piccione@gmail.com>
 */
class Deactivate
{
    /**
     * Plugin Deactivate
     *
     * @return void
     * @since  1.0.0
     *
     */
    public static function deactivate()
    {
        // reset secret key
        delete_option('wc_el_inv-license_check');
        delete_option('pop_plugin_wizard_redirect');
        delete_transient('wc_el_inv-license_check');
    }

    /**
     * Fire a non-blocking lifecycle event to POP API on deactivation.
     *
     * Called from the AJAX handler before WordPress processes the deactivation URL,
     * so the full WP environment (options, HTTP API) is still available.
     *
     * @param string $reason  Machine-readable reason slug from the survey.
     * @param string $message Optional free-text comment from the user.
     *
     * @return array|null Normalized response array, or null when the call was skipped.
     * @since  6.9.3
     */
    public static function sendLifecycleEvent(string $reason = '', string $message = ''): ?array
    {
        if (! defined('WC_EL_INV_LIFECYCLE_URL')) {
            return null;
        }

        $licenseKey = (string) (\WcElectronInvoice\Admin\Settings\OptionPage::init()->getOptions('license_key') ?: '');
        if ('' === $licenseKey) {
            return null;
        }

        $payload = [
            'platform' => 'wordpress',
            'reason'   => $reason,
            'message'  => $message,
            'site_url' => get_site_url(),
        ];

        if (defined('WC_EL_INV_ENV') && 'dev' === WC_EL_INV_ENV) {
            $payload['force'] = true;
        }

        $response = wp_remote_post(WC_EL_INV_LIFECYCLE_URL, [
            'body'    => wp_json_encode($payload),
            'headers' => [
                'Content-Type' => 'application/json',
                'X-API-Key'    => $licenseKey,
            ],
            'timeout' => 10,
        ]);

        if (is_wp_error($response)) {
            return [
                'success' => false,
                'code'    => 0,
                'body'    => $response->get_error_message(),
            ];
        }

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

        return [
            'success' => $code >= 200 && $code < 300,
            'code'    => $code,
            'body'    => is_array($data) ? $data : $body,
        ];
    }
}
