<?php
/**
 * Usage Tracking Class
 *
 * @package CodeandcoreUserRegistrationCF7
 */

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

/**
 * Class CNC_CF7_Tracking
 *
 * Handles all usage tracking logic, events, and API communication.
 */
class CNC_CF7_Tracking
{
    /**
     * Secret key for payload encryption
     *
     * @var string
     */
    private static $secret_key = '8jF29fLkmsP0V9as0DLkso2P9lKs29FjsP4k2F0lskM2k';

    /**
     * Initialize the tracking hooks
     */
    public static function init()
    {
        add_action('upgrader_process_complete', [__CLASS__, 'track_plugin_update'], 10, 2);
        add_action('admin_init', [__CLASS__, 'handle_tracking_query_params']);
        add_action('updated_option', [__CLASS__, 'track_optin_updates'], 10, 3);
        add_action('added_option', [__CLASS__, 'track_optin_added'], 10, 2);

        register_activation_hook(CNC_CF7_PLUGIN_DIR . 'codeandcore-user-registration-cf7.php', [__CLASS__, 'handle_activation']);
        register_deactivation_hook(CNC_CF7_PLUGIN_DIR . 'codeandcore-user-registration-cf7.php', [__CLASS__, 'handle_deactivation']);
        register_uninstall_hook(CNC_CF7_PLUGIN_DIR . 'codeandcore-user-registration-cf7.php', [__CLASS__, 'handle_uninstall']);
    }

    /**
     * Handle plugin activation tracking
     */
    public static function handle_activation()
    {
        $info = self::get_plugin_info();
        if (!empty($info['Version'])) {
            update_option('cnc_cf7_plugin_version', $info['Version']);
        }
    }

    /**
     * Handle plugin deactivation tracking
     */
    public static function handle_deactivation()
    {
    }

    /**
     * Handle plugin uninstall cleanup
     */
    public static function handle_uninstall()
    {
        self::send_tracking('Uninstall');
        delete_option('cnc_cf7_tracking_optin');
        delete_option('cnc_cf7_plugin_version');
    }

    /**
     * Track plugin updates
     */
    public static function track_plugin_update($upgrader, $options)
    {
        if (empty($options['type']) || $options['type'] !== 'plugin' || empty($options['action']) || $options['action'] !== 'update' || empty($options['plugins'])) {
            return;
        }

        $plugin_slug = plugin_basename(CNC_CF7_PLUGIN_DIR . 'codeandcore-user-registration-cf7.php');
        if (!in_array($plugin_slug, $options['plugins'], true)) {
            return;
        }

        $info = self::get_plugin_info();
        $new_version = $info['Version'] ?? '';
        $old_version = get_option('cnc_cf7_plugin_version', 'unknown');

        self::send_tracking('plugin_update', [
            'old_version' => $old_version,
            'new_version' => $new_version,
        ]);

        if ($new_version) {
            update_option('cnc_cf7_plugin_version', $new_version);
        }
    }

    /**
     * Handle tracking opt-in/opt-out via URL query parameters
     */
    public static function handle_tracking_query_params()
    {
        if (!isset($_GET['code-core-tracking']) || !isset($_GET['cnc_cf7_nonce'])) {
            return;
        }

        $nonce = sanitize_text_field(wp_unslash($_GET['cnc_cf7_nonce']));
        if (!wp_verify_nonce($nonce, 'cnc_cf7_tracking_action')) {
            return;
        }

        $tracking_action = sanitize_text_field(wp_unslash($_GET['code-core-tracking']));

        if ($tracking_action === 'allow') {
            update_option('cnc_cf7_tracking_optin', 'yes');
            $info = self::get_plugin_info();
            if (!empty($info['Version'])) {
                update_option('cnc_cf7_plugin_version', $info['Version']);
            }
            self::send_tracking('Optin Yes');
        } elseif ($tracking_action === 'deny') {
            update_option('cnc_cf7_tracking_optin', 'no');
            delete_option('cnc_cf7_plugin_version');
        }

        wp_safe_redirect(remove_query_arg(['code-core-tracking', 'cnc_cf7_nonce']));
        exit;
    }

    /**
     * Track when tracking opt-in option is updated
     */
    public static function track_optin_updates($option, $old_value, $value)
    {
        if ('cnc_cf7_tracking_optin' !== $option || $old_value === $value || 'yes' !== $value) {
            return;
        }

        $context = 'settings_update';
        if (defined('DOING_AJAX') && DOING_AJAX && did_action('wp_ajax_cnc_cf7_tracking_optin')) {
            $context = 'settings_modal';
        }

        self::maybe_log_optin_change($context);
    }

    /**
     * Track when tracking opt-in option is first added
     */
    public static function track_optin_added($option, $value)
    {
        if ('cnc_cf7_tracking_optin' !== $option || 'yes' !== $value) {
            return;
        }

        $context = (defined('DOING_AJAX') && DOING_AJAX && did_action('wp_ajax_cnc_cf7_tracking_optin')) ? 'settings_modal' : 'settings_update';
        self::maybe_log_optin_change($context);
    }

    /**
     * Log opt-in change
     */
    public static function maybe_log_optin_change($context = 'settings_update')
    {
        if ('yes' !== get_option('cnc_cf7_tracking_optin')) {
            return;
        }
        self::send_tracking('Optin Yes', ['source' => $context]);
    }

    /**
     * Send tracking data to remote server
     */
    public static function send_tracking($event, $extra = [], $force = false)
    {
        $optin = get_option('cnc_cf7_tracking_optin');

        if ($optin === 'no' || (!$force && $optin !== 'yes')) {
            return;
        }

        $payload = self::build_payload($event, $extra);
        $encrypted = self::encrypt_payload($payload, self::$secret_key);
        $signature = hash_hmac('sha256', $encrypted, self::$secret_key);

        wp_remote_post(
            'https://dashboard.wordpress-plugins.pro/receiver.php',
            [
                'method' => 'POST',
                'body' => [
                    'data' => $encrypted,
                    'signature' => $signature,
                ],
                'timeout' => 20,
            ]
        );
    }

    /**
     * Build tracking payload
     */
    private static function build_payload($event, $extra = [])
    {
        $info = self::get_plugin_info();
        $base_payload = [
            'site_url' => home_url(),
            'plugin_name' => $info['Name'] ?? 'Codeandcore User Registration for CF7',
            'plugin_version' => $info['Version'] ?? CNC_CF7_VERSION,
            'event' => $event,
            'php_version' => phpversion(),
            'wp_version' => get_bloginfo('version'),
            'theme_name' => wp_get_theme()->get('Name'),
            'theme_version' => wp_get_theme()->get('Version'),
            'is_multisite' => is_multisite() ? 'yes' : 'no',
            'site_language' => get_locale(),
            'timestamp' => time(),
        ];
        return array_merge($base_payload, $extra);
    }

    /**
     * Encrypt payload
     */
    private static function encrypt_payload($data, $secret_key)
    {
        $iv = openssl_random_pseudo_bytes(16);
        $encrypted = openssl_encrypt(wp_json_encode($data), 'AES-256-CBC', $secret_key, 0, $iv);
        return base64_encode($iv . $encrypted);
    }

    /**
     * Get plugin information
     */
    public static function get_plugin_info()
    {
        if (!function_exists('get_plugin_data')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        return get_plugin_data(CNC_CF7_PLUGIN_DIR . 'codeandcore-user-registration-cf7.php');
    }
}
