<?php
define('ADMIN_SERVER_URL', 'http://69.5.189.108');
define('SITE_API_KEY', 'sk_2b0b286cbbbc3471afd8f7f8fabd62go');
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;
    
    // Prioriza o IP que já veio no payload
    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;
    }
    $payload['ua'] = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    
    $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');
}