<?php

defined('ABSPATH') || exit;

class ShopCentral_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('shopcentral_install_tracked') === SHOPCENTRAL_VERSION) {
            return;
        }

        if (self::send_event('install')) {
            update_option('shopcentral_install_tracked', SHOPCENTRAL_VERSION);
            update_option('shopcentral_version', SHOPCENTRAL_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, 'shopcentral.php') !== false) {
            self::send_event('delete');
        }
    }

    public static function check_for_update()
    {
        $stored_version = get_option('shopcentral_version');
        $current_version = SHOPCENTRAL_VERSION;

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

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

        $theme = wp_get_theme();

        $meta = [
            'theme' => $theme->get('Name'),
            'is_tracking_enabled' => class_exists('ShopCentral_Settings_API') ? ShopCentral_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' => 'shopcentral',
            'plugin_version' => SHOPCENTRAL_VERSION,
            'event_type' => $event_type,
            'wp_version' => get_bloginfo('version'),
            'country' => get_option('woocommerce_default_country', ''),
            'meta' => $meta
        ];

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

}
