<?php

/**
 * GA4 Tracking Implementation
 */
class Smart_Discount_Tracking
{
  private static $instance = null;
  private $measurement_id = 'G-0400TM5E8E';
  private $api_secret = 'JaojBSarQC-4-6O0iB2B0A';

  public static function get_instance()
  {
    if (null === self::$instance) {
      self::$instance = new self();
    }
    return self::$instance;
  }

  private function __construct()
  {
    add_action('wp_ajax_smart_discount_handle_consent', array($this, 'handle_consent_ajax'));
    add_action('wp_ajax_nopriv_smart_discount_handle_consent', array($this, 'handle_consent_ajax'));
  }

  public function track_installation()
  {
    if (!$this->has_tracking_consent() || $this->is_installation_tracked()) {
      return;
    }

    $client_id = wp_generate_uuid4();
    $timestamp_micros = (int)(microtime(true) * 1000000);

    $data = array(
      'client_id' => $client_id,
      'events' => array(
        array(
          'name' => 'plugin_installation',
          'params' => array(
            'plugin_name' => 'Smart Discount for WooCommerce',
            'plugin_version' => DLift_VERSION,
            'wp_version' => get_bloginfo('version'),
            'php_version' => phpversion(),
            'wc_version' => defined('WC_VERSION') ? WC_VERSION : 'not_active',
            'site_language' => get_bloginfo('language'),
            'is_multisite' => is_multisite() ? 'yes' : 'no',
            'site_url' => get_site_url()
          )
        )
      )
    );

    $url = sprintf(
      'https://www.google-analytics.com/mp/collect?measurement_id=%s&api_secret=%s',
      $this->measurement_id,
      $this->api_secret
    );

    $response = wp_remote_post($url, array(
      'body' => json_encode($data),
      'headers' => array('Content-Type' => 'application/json'),
      'timeout' => 5,
      'sslverify' => true,
    ));

    if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
      update_option('smart_discount_installation_tracked', true);
    }
  }

  public function handle_consent_ajax()
  {
    check_ajax_referer('smart_discount_nonce', 'nonce');

    $consent = isset($_POST['consent']) ? sanitize_text_field($_POST['consent']) : '';
    $valid_values = array('allowed', 'denied');

    if (!in_array($consent, $valid_values)) {
      wp_send_json_error(array('message' => __('Invalid consent value', 'smart-discount')));
    }

    update_option('smart_discount_tracking_consent', $consent === 'allowed');
    update_option('smart_discount_tracking_consent_shown', $consent);

    if ($consent === 'allowed') {
      $this->track_installation();
      wp_send_json_success(array(
        'message' => __('Thank you for helping us improve Smart Discount!', 'smart-discount')
      ));
    } else {
      wp_send_json_success(array(
        'message' => __('Your preference has been saved.', 'smart-discount')
      ));
    }
  }

  private function has_tracking_consent()
  {
    return get_option('smart_discount_tracking_consent', false);
  }

  private function is_installation_tracked()
  {
    return get_option('smart_discount_installation_tracked', false);
  }
}
