<?php
/**
 * GA4MeasurementProtocolClient.php
 *
 * 一个用于通过GA4 Measurement Protocol发送事件的PHP类。
 */

class GA4MeasurementProtocolClient
{
    private $measurement_id;
    private $api_secret;
    private $firebase_app_id;
    private $endpoint = 'https://www.google-analytics.com/mp/collect';

    /**
     * 构造函数
     *
     * @param string $measurement_id GA4的测量ID (G-XXXXXXX)
     * @param string $api_secret API秘密
     * @param string|null $firebase_app_id Firebase应用ID (可选)
     */
    public function __construct($measurement_id, $api_secret, $firebase_app_id = null)
    {
        $this->measurement_id = $measurement_id;
        $this->api_secret = $api_secret;
        $this->firebase_app_id = $firebase_app_id;
    }

    /**
     * 发送事件到GA4
     *
     * @param string $client_id 客户端ID (通常是UUID)
     * @param string $event_name 事件名称
     * @param array $event_params 事件参数（键值对）
     * @param int|null $timestamp_ms 自定义时间戳（可选）
     *
     * @return bool 返回true表示发送成功，false表示失败
     */
    public function sendEvent($client_id, $event_name, $event_params = [], $timestamp_ms = null)
    {
        $payload = [
            'client_id' => $client_id,
            'events' => [
                [
                    'name' => $event_name,
                    'params' => $event_params
                ]
            ]
        ];

        if ($timestamp_ms) {
            $payload['events'][0]['timestamp_micros'] = $timestamp_ms * 1000; // 转换为微秒
        }

        $url = $this->endpoint . '?measurement_id=' . $this->measurement_id . '&api_secret=' . $this->api_secret;

        $response = $this->postRequest($url, $payload);

        if ($response !== false) {
            // GA4的响应状态码
            $http_code = $response['http_code'];
            return in_array($http_code, [200, 204]);
        }

        return false;
    }

    /**
     * 发送POST请求
     *
     * @param string $url 请求URL
     * @param array $data 请求数据
     *
     * @return array|false 返回包含响应的数组，或者false失败
     */
    private function postRequest($url, $data)
    {
        $ch = curl_init($url);

        $payload = json_encode($data);

        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($payload)
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // 确保SSL安全

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($response === false) {
            error_log('cURL error: ' . curl_error($ch));
            curl_close($ch);
            return false;
        }

        curl_close($ch);

        return [
            'body' => $response,
            'http_code' => $http_code
        ];
    }
}
