<?php
// api_debug.php - VERIFICAR PINGS EM TEMPO REAL
date_default_timezone_set('America/Sao_Paulo');

$log_file = __DIR__ . '/ping_debug.log';

// Capturar TODOS os dados recebidos
$raw_post = file_get_contents('php://input');
$post_data = $_POST;
$get_data = $_GET;
$headers = getallheaders();

// Log detalhado
$log_entry = "=== PING RECEBIDO [" . date('Y-m-d H:i:s') . "] ===\n";
$log_entry .= "📡 RAW POST: " . $raw_post . "\n";
$log_entry .= "📡 POST Data: " . print_r($post_data, true) . "\n";
$log_entry .= "📡 GET Data: " . print_r($get_data, true) . "\n";
$log_entry .= "📡 Headers: " . print_r($headers, true) . "\n";
$log_entry .= "📡 IP Cliente: " . $_SERVER['REMOTE_ADDR'] . "\n";
$log_entry .= "📡 User-Agent: " . ($_SERVER['HTTP_USER_AGENT'] ?? 'N/A') . "\n";
$log_entry .= "=== FIM DO PING ===\n\n";

file_put_contents($log_file, $log_entry, FILE_APPEND);

// Tentar decodificar JSON se existir
if (!empty($raw_post)) {
    $json_data = json_decode($raw_post, true);
    if (json_last_error() === JSON_ERROR_NONE) {
        $log_entry_json = "=== JSON DECODIFICADO ===\n";
        $log_entry_json .= print_r($json_data, true) . "\n";
        $log_entry_json .= "=== FIM JSON ===\n\n";
        file_put_contents($log_file, $log_entry_json, FILE_APPEND);
        
        // Extrair MAC se existir
        if (isset($json_data['app_device_id'])) {
            $mac_encoded = $json_data['app_device_id'];
            $mac_decoded = base64_decode($mac_encoded);
            $log_entry_mac = "=== MAC EXTRACTED ===\n";
            $log_entry_mac .= "Encoded: $mac_encoded\n";
            $log_entry_mac .= "Decoded: $mac_decoded\n";
            $log_entry_mac .= "=== FIM MAC ===\n\n";
            file_put_contents($log_file, $log_entry_mac, FILE_APPEND);
        }
    }
}

// Responder para o app (igual ao endpoint original)
header('Content-Type: application/json');
echo json_encode(['status' => 'ok', 'time' => date('Y-m-d H:i:s')]);

// Mostrar no navegador também (para debug)
echo "<h1>✅ PING RECEBIDO E LOGADO!</h1>";
echo "<p>Verifique o arquivo: ping_debug.log</p>";
echo "<pre>" . htmlspecialchars($log_entry) . "</pre>";
?>