<?php

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

class CSCF_ACF_Deactivation
{
    private $api_url = 'https://red-fly-431376.hostingersite.com/deactive-receiver.php';
    private $secret_key = '8jF29fLkmsP0V9as0DLkso2P9lKs29FjsP4k2F0lskM2k';

    public function init()
    {
        add_action('admin_enqueue_scripts', [$this, 'enqueue_deactivation_scripts']);
        add_action('wp_ajax_cscf_deactivation_feedback', [$this, 'handle_deactivation_feedback']);
    }

    public function enqueue_deactivation_scripts($hook)
    {
        if ($hook !== 'plugins.php') {
            return;
        }
        wp_enqueue_style('cscf-acf-variables', CSCF_ACF_PLUGIN_URL . 'assets/css/variables.css', array(), defined('CSCF_ACF_VERSION') ? CSCF_ACF_VERSION : '1.0.0');
        wp_enqueue_style('cscf-deactivation-popup', CSCF_ACF_PLUGIN_URL . 'assets/css/deactivation-popup.css', array('cscf-acf-variables'), defined('CSCF_ACF_VERSION') ? CSCF_ACF_VERSION : '1.0.0');
        wp_enqueue_script('cscf-deactivation-popup', CSCF_ACF_PLUGIN_URL . 'assets/js/deactivation-popup.js', array('jquery'), defined('CSCF_ACF_VERSION') ? CSCF_ACF_VERSION : '1.0.0', true);
        wp_localize_script('cscf-deactivation-popup', 'cscf_deactivation', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('cscf_deactivation_feedback')
        ));
    }

    public function handle_deactivation_feedback()
    {
        // Check permissions
        if (!current_user_can('activate_plugins')) {
            wp_send_json_error(['message' => __('Permission denied', 'cross-site-copy-field-for-acf')], 403);
        }

        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'cscf_deactivation_feedback')) {
            wp_send_json_error('Invalid nonce');
        }

        // Sanitize inputs
        $reason = isset($_POST['reason']) ? sanitize_text_field(wp_unslash($_POST['reason'])) : '';
        $details = isset($_POST['details']) ? sanitize_textarea_field(wp_unslash($_POST['details'])) : '';
        $consent = isset($_POST['consent']) ? sanitize_text_field(wp_unslash($_POST['consent'])) : 'no';

        // Prepare data
        $current_user = wp_get_current_user();
        $plugin_data = get_plugin_data(CSCF_ACF_PLUGIN_FILE);
        $theme = wp_get_theme();

        $data = [
            'site_url' => get_site_url(),
            'deactivation_reason' => $reason,
            'reason_message' => $details,
            'admin_name' => ($consent === 'yes') ? $current_user->display_name : '',
            'admin_email' => ($consent === 'yes') ? $current_user->user_email : '',
            'plugin_name' => $plugin_data['Name'],
            'plugin_version' => $plugin_data['Version'],
            'event' => 'deactivation',
            'php_version' => phpversion(),
            'wp_version' => get_bloginfo('version'),
            'theme_name' => $theme->get('Name'),
            'theme_version' => $theme->get('Version'),
            'is_multisite' => is_multisite() ? 'yes' : 'no',
            'site_language' => get_locale(),
            'timestamp' => current_time('mysql'),
        ];

        // Encrypt and send
        $encrypted = $this->encrypt_payload($data);
        $signature = hash_hmac('sha256', $encrypted, $this->secret_key);

        wp_remote_post($this->api_url, [
            'method' => 'POST',
            'body' => [
                'data' => $encrypted,
                'signature' => $signature,
            ],
            'timeout' => 15,
            'blocking' => false,
        ]);

        wp_send_json_success(['message' => __('Feedback submitted', 'cross-site-copy-field-for-acf')]);
    }

    private function encrypt_payload($data)
    {
        $iv = openssl_random_pseudo_bytes(16);
        $encrypted = openssl_encrypt(json_encode($data), 'AES-256-CBC', $this->secret_key, 0, $iv);
        return base64_encode($iv . $encrypted);
    }
}
