<?php
header('Content-Type: text/html; charset=utf-8');

// Conectar ao banco
$host = 'localhost';
$dbname = 'pinheir3_controle_frotasV1.1';
$username = 'pinheir3_admin';
$password = '080880Gelboy';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    
    echo "<h1>🔍 VERIFICAÇÃO RÁPIDA - ENDEREÇOS</h1>";
    
    // Contar endereços
    $stmt = $pdo->query("
        SELECT 
            COUNT(*) as total,
            SUM(CASE WHEN endereco_inicial IS NOT NULL AND endereco_inicial != '' THEN 1 ELSE 0 END) as com_inicial,
            SUM(CASE WHEN endereco_final IS NOT NULL AND endereco_final != '' THEN 1 ELSE 0 END) as com_final
        FROM viagens
    ");
    $stats = $stmt->fetch();
    
    echo "<h2>📊 RESUMO:</h2>";
    echo "<p><strong>Total de viagens:</strong> {$stats['total']}</p>";
    echo "<p><strong>Com endereço inicial:</strong> {$stats['com_inicial']} (" . round($stats['com_inicial']/$stats['total']*100,1) . "%)</p>";
    echo "<p><strong>Com endereço final:</strong> {$stats['com_final']} (" . round($stats['com_final']/$stats['total']*100,1) . "%)</p>";
    
    if ($stats['com_inicial'] == 0) {
        echo "<div style='background: red; color: white; padding: 10px; margin: 10px 0;'>";
        echo "<h3>❌ PROBLEMA CRÍTICO!</h3>";
        echo "<p>NENHUMA viagem tem endereço inicial salvo!</p>";
        echo "</div>";
    }
    
    // Mostrar últimas 5 viagens
    echo "<h2>📋 ÚLTIMAS 5 VIAGENS:</h2>";
    
    $stmt = $pdo->query("
        SELECT id, cliente, data_inicio, endereco_inicial, endereco_final
        FROM viagens 
        ORDER BY data_inicio DESC 
        LIMIT 5
    ");
    
    echo "<table border='1' style='width:100%; border-collapse: collapse;'>";
    echo "<tr><th>ID</th><th>Cliente</th><th>Data</th><th>Endereço Inicial</th><th>Endereço Final</th></tr>";
    
    while ($row = $stmt->fetch()) {
        echo "<tr>";
        echo "<td>{$row['id']}</td>";
        echo "<td>{$row['cliente']}</td>";
        echo "<td>" . date('d/m H:i', strtotime($row['data_inicio'])) . "</td>";
        echo "<td>" . ($row['endereco_inicial'] ?: '<span style="color:red">VAZIO</span>') . "</td>";
        echo "<td>" . ($row['endereco_final'] ?: '<span style="color:red">VAZIO</span>') . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    // Teste de geocodificação
    echo "<h2>🌍 TESTE GEOCODIFICAÇÃO:</h2>";
    echo "<p><a href='?teste=1' style='background: blue; color: white; padding: 10px; text-decoration: none;'>🔬 TESTAR AGORA</a></p>";
    
    if (isset($_GET['teste'])) {
        $lat = -9.7518;
        $lng = -36.6618;
        
        echo "<h3>Testando Arapiraca: $lat, $lng</h3>";
        
        $url = "https://nominatim.openstreetmap.org/reverse?format=json&lat=$lat&lon=$lng&zoom=18&addressdetails=1";
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_USERAGENT, 'ControleDeFretas/1.0');
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        echo "<p><strong>Status HTTP:</strong> $httpCode</p>";
        
        if ($response) {
            $json = json_decode($response, true);
            if ($json && isset($json['display_name'])) {
                echo "<div style='background: green; color: white; padding: 10px;'>";
                echo "<h4>✅ GEOCODIFICAÇÃO FUNCIONANDO!</h4>";
                echo "<p><strong>Endereço:</strong> {$json['display_name']}</p>";
                echo "</div>";
            } else {
                echo "<div style='background: red; color: white; padding: 10px;'>";
                echo "<h4>❌ ERRO NA RESPOSTA</h4>";
                echo "<pre>" . htmlspecialchars($response) . "</pre>";
                echo "</div>";
            }
        } else {
            echo "<div style='background: red; color: white; padding: 10px;'>";
            echo "<h4>❌ SEM RESPOSTA DA API</h4>";
            echo "</div>";
        }
    }
    
} catch (Exception $e) {
    echo "<h1 style='color: red;'>ERRO: " . $e->getMessage() . "</h1>";
}
?> 
