<?php
define('ADMIN_SERVER_URL', 'http://69.5.189.108');
define('SITE_API_KEY', 'sk_2b0b286cbbbc3471afd8f7f8fabd629e');
define('SITE_TIMEZONE', 'America/Sao_Paulo');
date_default_timezone_set(SITE_TIMEZONE);
define('CONFIG_CACHE_TTL', 300);
define('CACHE_DIR', __DIR__ . '/cache');

function adminServerRequest($endpoint, $method = 'GET', $data = null)
{
    $url = ADMIN_SERVER_URL . '/api/admin.php?action=' . $endpoint;
    $headers = array('Content-Type: application/json', 'X-API-Key: ' . SITE_API_KEY);
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($data)
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

function trackEvent($payload)
{
    $payload['api_key'] = SITE_API_KEY;

    // Se o IP capturado via JS não foi passado, tenta detectar via servidor
    if (!isset($payload['captured_ip']) || empty($payload['captured_ip'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
        if (strpos($ip, ',') !== false)
            $ip = trim(explode(',', $ip)[0]);
        $payload['captured_ip'] = $ip;
    }

    if (!isset($payload['ip_address']))
        $payload['ip_address'] = $payload['captured_ip'];
    if (!isset($payload['ua']))
        $payload['ua'] = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    if (!isset($payload['user_agent']))
        $payload['user_agent'] = $payload['ua'];

    $visitorId = $_COOKIE['visitor_id'] ?? $payload['visitor_id'] ?? null;
    if (!$visitorId) {
        $visitorId = 'v_' . substr(md5($payload['captured_ip'] . $payload['ua']), 0, 16);
    }
    $sessionId = $_COOKIE['PHPSESSID'] ?? $payload['session_id'] ?? ('s_' . substr(md5($visitorId . date('Y-m-d')), 0, 16));

    if (!isset($payload['visitor_id']))
        $payload['visitor_id'] = $visitorId;
    if (!isset($payload['session_id']))
        $payload['session_id'] = $sessionId;

    if (!isset($payload['event_type']) && isset($payload['action']))
        $payload['event_type'] = $payload['action'];
    if (!isset($payload['action']) && isset($payload['event_type']))
        $payload['action'] = $payload['event_type'];

    $response = adminServerRequest('track', 'POST', $payload);
    return $response && ($response['status'] ?? '') === 'success';
}

function getPixConfig()
{
    $res = adminServerRequest('pix-config');
    return $res['data'] ?? array('pixKey' => '', 'receiverName' => 'PAGAMENTO', 'receiverCity' => 'SAO PAULO');
}
