<?php

defined('ABSPATH') || exit;

class InsightPress_Event_Tracker
{
    public static function init()
    {
        add_action('admin_init', [__CLASS__, 'check_for_update']);
        add_action('delete_plugin', [__CLASS__, 'track_delete'], 10, 1);
    }

    public static function track_install()
    {
        if (get_option('insightpress_install_tracked') === INSIGHTPRESS_ADVANCED_ANALYTICS_FOR_WOOCOMMERCE_VERSION) {
            return;
        }

        if (self::send_event('install')) {
            update_option('insightpress_install_tracked', INSIGHTPRESS_ADVANCED_ANALYTICS_FOR_WOOCOMMERCE_VERSION);
            update_option('insightpress_version', INSIGHTPRESS_ADVANCED_ANALYTICS_FOR_WOOCOMMERCE_VERSION);
        }
    }

    public static function track_activation()
    {
        self::send_event('activate');
    }

    public static function track_deactivation()
    {
        self::send_event('deactivate');
    }

    public static function track_delete($plugin_file)
    {
        if (strpos($plugin_file, 'insightpress-advanced-analytics-for-woocommerce.php') !== false) {
            self::send_event('delete');
        }
    }

    public static function check_for_update()
    {
        $stored_version = get_option('insightpress_version');
        $current_version = INSIGHTPRESS_ADVANCED_ANALYTICS_FOR_WOOCOMMERCE_VERSION;

        if ($stored_version && version_compare($stored_version, $current_version, '<')) {
            if (self::send_event('update')) {
                update_option('insightpress_version', $current_version);
            }
        } elseif (!$stored_version) {
            update_option('insightpress_version', $current_version);
        }
    }

    public static function send_event($event_type, $extra_meta = [])
    {
        // Don't even process if tracking is disabled
        if (class_exists('InsightPress_Settings_API') && !InsightPress_Settings_API::is_feature_enabled('usage_tracking')) {
            return false;
        }

        $theme = wp_get_theme();

        $meta = [
            'theme' => $theme->get('Name'),
            'is_tracking_enabled' => class_exists('InsightPress_Settings_API') ? InsightPress_Settings_API::is_feature_enabled('usage_tracking') : true
        ];

        if (!empty($extra_meta)) {
            $meta = array_merge($meta, $extra_meta);
        }

        $body = [
            'site_url' => get_site_url(),
            'date' => current_time('mysql'),
            'plugin_slug' => 'insightpress',
            'plugin_version' => INSIGHTPRESS_ADVANCED_ANALYTICS_FOR_WOOCOMMERCE_VERSION,
            'event_type' => $event_type,
            'wp_version' => get_bloginfo('version'),
            'country' => get_option('woocommerce_default_country', ''),
            'meta' => $meta
        ];

        $response = InsightPress_Remote_API::post('events', $body);
        return !is_wp_error($response) && wp_remote_retrieve_response_code($response) < 400;
    }

}
