<?php
/**
 * DIAGNÓSTICO COMPLETO: Sistema de Boleto Mercado Pago
 * 
 * Este arquivo faz um diagnóstico completo do sistema de boleto,
 * testando a estrutura do payload e mostrando logs detalhados
 */

declare(strict_types=1);

// Permitir acesso direto
header('Content-Type: text/html; charset=utf-8');

// Autoload do Composer
require __DIR__ . '/../vendor/autoload.php';

// Conexão com o banco de dados
require __DIR__ . '/../config/config_db.php';

// Importa o arquivo com o access token
require __DIR__ . '/../config/token.php';

// Imports do SDK v3.5+
use MercadoPago\Client\Payment\PaymentClient;
use MercadoPago\Client\Common\RequestOptions;
use MercadoPago\MercadoPagoConfig;
use MercadoPago\Exceptions\MPApiException;

?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🔍 Diagnóstico Boleto - Mercado Pago</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #0d1117;
            color: #c9d1d9;
            padding: 20px;
            line-height: 1.6;
        }
        .container {
            max-width: 1400px;
            margin: 0 auto;
        }
        h1 {
            color: #58a6ff;
            border-bottom: 2px solid #30363d;
            padding-bottom: 15px;
            margin-bottom: 30px;
        }
        h2 {
            color: #f0883e;
            margin: 25px 0 15px 0;
            font-size: 1.3em;
        }
        .section {
            background: #161b22;
            border: 1px solid #30363d;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .success { border-left: 4px solid #3fb950; }
        .error { border-left: 4px solid #f85149; background: #2a1f1f; }
        .warning { border-left: 4px solid #d29922; background: #2a251f; }
        .info { border-left: 4px solid #58a6ff; background: #1a2332; }
        pre {
            background: #0d1117;
            border: 1px solid #30363d;
            border-radius: 5px;
            padding: 15px;
            overflow-x: auto;
            font-size: 13px;
            color: #c9d1d9;
        }
        code {
            color: #79c0ff;
        }
        .badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
            margin-left: 10px;
        }
        .badge-success { background: #238636; color: #fff; }
        .badge-error { background: #da3633; color: #fff; }
        .badge-warning { background: #9e6a03; color: #fff; }
        ul { margin-left: 20px; margin-top: 10px; }
        li { margin: 5px 0; }
        .test-button {
            background: #238636;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            margin: 10px 5px;
        }
        .test-button:hover { background: #2ea043; }
        .test-button.danger { background: #da3633; }
        .test-button.danger:hover { background: #f85149; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 Diagnóstico Completo: Sistema de Boleto Mercado Pago</h1>
        
        <?php
        // ============================================================
        // 1. VERIFICAÇÃO DE CONFIGURAÇÃO
        // ============================================================
        echo '<div class="section info">';
        echo '<h2>1️⃣ Configuração do SDK</h2>';
        
        try {
            MercadoPagoConfig::setAccessToken(ACCESS_TOKEN);
            MercadoPagoConfig::setRuntimeEnviroment(MercadoPagoConfig::LOCAL);
            
            $tokenPreview = defined('ACCESS_TOKEN') && !empty(ACCESS_TOKEN) 
                ? substr(ACCESS_TOKEN, 0, 15) . '***' 
                : 'NÃO DEFINIDO';
            
            echo '<p><strong>Status:</strong> <span class="badge badge-success">OK</span></p>';
            echo '<p><strong>Token (preview):</strong> <code>' . htmlspecialchars($tokenPreview) . '</code></p>';
            echo '<p><strong>Ambiente:</strong> <code>LOCAL</code></p>';
        } catch (Exception $e) {
            echo '<p><strong>Status:</strong> <span class="badge badge-error">ERRO</span></p>';
            echo '<p class="error-text">' . htmlspecialchars($e->getMessage()) . '</p>';
        }
        echo '</div>';
        
        // ============================================================
        // 2. ESTRUTURA DO PAYLOAD (igual ao PIX que funciona)
        // ============================================================
        echo '<div class="section">';
        echo '<h2>2️⃣ Estrutura do Payload de Teste</h2>';
        echo '<p>Este é o payload mínimo que deve funcionar (igual ao PIX):</p>';
        
        $testPayload = [
            'transaction_amount' => 100.00,
            'description' => 'Teste de Boleto',
            'payment_method_id' => 'bolbradesco',
            'external_reference' => 'test_' . time(),
            'notification_url' => 'https://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . '/backend/webhook.php',
            'date_of_expiration' => date('Y-m-d\TH:i:s.000-03:00', strtotime('+3 days')),
            'payer' => [
                'email' => 'test@example.com',
                'first_name' => 'Teste',
                'last_name' => 'Diagnóstico',
                'identification' => [
                    'type' => 'CPF',
                    'number' => '12345678909'
                ],
                'phone' => [
                    'area_code' => '11',
                    'number' => '987654321'
                ]
            ],
            'additional_info' => [
                'items' => [
                    [
                        'id' => '1',
                        'title' => 'Teste de Boleto',
                        'quantity' => 1,
                        'unit_price' => 100.00
                    ]
                ]
            ]
        ];
        
        echo '<pre>' . json_encode($testPayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</pre>';
        echo '</div>';
        
        // ============================================================
        // 3. TESTE DIRETO DA API
        // ============================================================
        echo '<div class="section">';
        echo '<h2>3️⃣ Teste Direto da API</h2>';
        
        if (isset($_GET['test'])) {
            try {
                $client = new PaymentClient();
                
                $requestOptions = new RequestOptions();
                $idempotencyKey = 'diagnostico_' . time();
                $requestOptions->setCustomHeaders(["X-Idempotency-Key: {$idempotencyKey}"]);
                
                echo '<p class="info">🔄 Enviando requisição para a API...</p>';
                
                $payment = $client->create($testPayload, $requestOptions);
                
                echo '<div class="success" style="padding: 15px; border-radius: 5px; margin-top: 15px;">';
                echo '<h3 style="color: #3fb950;">✅ SUCESSO!</h3>';
                echo '<p><strong>Payment ID:</strong> <code>' . htmlspecialchars($payment->id ?? 'N/A') . '</code></p>';
                echo '<p><strong>Status:</strong> <code>' . htmlspecialchars($payment->status ?? 'N/A') . '</code></p>';
                
                if (isset($payment->transaction_details->external_resource_url)) {
                    echo '<p><strong>URL do Boleto:</strong> <a href="' . htmlspecialchars($payment->transaction_details->external_resource_url) . '" target="_blank" style="color: #58a6ff;">Abrir boleto</a></p>';
                }
                
                echo '<h4 style="margin-top: 15px;">Resposta Completa da API:</h4>';
                echo '<pre style="max-height: 400px; overflow-y: auto;">' . json_encode($payment, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</pre>';
                echo '</div>';
                
            } catch (MPApiException $e) {
                echo '<div class="error" style="padding: 15px; border-radius: 5px; margin-top: 15px;">';
                echo '<h3 style="color: #f85149;">❌ ERRO DA API</h3>';
                echo '<p><strong>Mensagem:</strong> <code>' . htmlspecialchars($e->getMessage()) . '</code></p>';
                echo '<p><strong>Status Code:</strong> <code>' . ($e->getStatusCode() ?? 'N/A') . '</code></p>';
                echo '<p><strong>Código:</strong> <code>' . ($e->getCode() ?? 'N/A') . '</code></p>';
                
                // Tentar todos os métodos possíveis para extrair a resposta
                $apiResponse = null;
                $methodsTried = [];
                
                // Método 1: getContent()
                if (method_exists($e, 'getContent')) {
                    try {
                        $apiResponse = $e->getContent();
                        $methodsTried[] = 'getContent()';
                    } catch (Exception $ex) {
                        $methodsTried[] = 'getContent() - ERRO: ' . $ex->getMessage();
                    }
                }
                
                // Método 2: getApiResponse()
                if (empty($apiResponse) && method_exists($e, 'getApiResponse')) {
                    try {
                        $apiResponse = $e->getApiResponse();
                        $methodsTried[] = 'getApiResponse()';
                    } catch (Exception $ex) {
                        $methodsTried[] = 'getApiResponse() - ERRO: ' . $ex->getMessage();
                    }
                }
                
                // Método 3: Tentar acessar propriedades diretamente
                if (empty($apiResponse) && isset($e->content)) {
                    $apiResponse = $e->content;
                    $methodsTried[] = 'propriedade $e->content';
                }
                
                echo '<h4 style="margin-top: 15px;">Métodos Tentados:</h4>';
                echo '<ul>';
                foreach ($methodsTried as $method) {
                    echo '<li><code>' . htmlspecialchars($method) . '</code></li>';
                }
                echo '</ul>';
                
                if (!empty($apiResponse)) {
                    echo '<h4 style="margin-top: 15px;">Resposta Completa da API:</h4>';
                    echo '<pre style="max-height: 400px; overflow-y: auto;">' . json_encode($apiResponse, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . '</pre>';
                    
                    // Tentar extrair mensagens específicas
                    if (is_array($apiResponse)) {
                        if (isset($apiResponse['cause']) && is_array($apiResponse['cause'])) {
                            echo '<h4 style="margin-top: 15px;">Causas do Erro:</h4>';
                            echo '<ul>';
                            foreach ($apiResponse['cause'] as $cause) {
                                if (isset($cause['description'])) {
                                    echo '<li><code>' . htmlspecialchars($cause['description']) . '</code></li>';
                                }
                                if (isset($cause['code'])) {
                                    echo '<li><code>Código: ' . htmlspecialchars($cause['code']) . '</code></li>';
                                }
                            }
                            echo '</ul>';
                        }
                        
                        if (isset($apiResponse['errors']) && is_array($apiResponse['errors'])) {
                            echo '<h4 style="margin-top: 15px;">Erros de Validação:</h4>';
                            echo '<ul>';
                            foreach ($apiResponse['errors'] as $error) {
                                if (isset($error['message'])) {
                                    echo '<li><code>' . htmlspecialchars($error['message']) . '</code></li>';
                                }
                            }
                            echo '</ul>';
                        }
                    }
                } else {
                    echo '<p class="warning">⚠️ Não foi possível extrair a resposta completa da API. Verifique os logs do servidor.</p>';
                }
                
                echo '</div>';
                
            } catch (Exception $e) {
                echo '<div class="error" style="padding: 15px; border-radius: 5px; margin-top: 15px;">';
                echo '<h3 style="color: #f85149;">❌ ERRO GERAL</h3>';
                echo '<p><strong>Mensagem:</strong> <code>' . htmlspecialchars($e->getMessage()) . '</code></p>';
                echo '<p><strong>Arquivo:</strong> <code>' . htmlspecialchars($e->getFile()) . '</code></p>';
                echo '<p><strong>Linha:</strong> <code>' . $e->getLine() . '</code></p>';
                echo '<h4>Stack Trace:</h4>';
                echo '<pre style="max-height: 300px; overflow-y: auto;">' . htmlspecialchars($e->getTraceAsString()) . '</pre>';
                echo '</div>';
            }
        } else {
            echo '<p>Clique no botão abaixo para testar a criação de um boleto:</p>';
            echo '<a href="?test=1" class="test-button">▶️ Executar Teste</a>';
        }
        echo '</div>';
        
        // ============================================================
        // 4. COMPARAÇÃO COM PIX
        // ============================================================
        echo '<div class="section info">';
        echo '<h2>4️⃣ Comparação: Boleto vs PIX</h2>';
        echo '<p>O PIX funciona perfeitamente. Vamos comparar as estruturas:</p>';
        
        echo '<h3 style="margin-top: 15px;">PIX (funciona):</h3>';
        $pixPayload = [
            'transaction_amount' => 100.00,
            'description' => 'Teste',
            'payment_method_id' => 'pix',
            'payer' => [
                'email' => 'test@example.com',
                'first_name' => 'Teste',
                'last_name' => 'Teste',
                'identification' => [
                    'type' => 'CPF',
                    'number' => '12345678909'
                ]
            ],
            'additional_info' => [
                'items' => [
                    [
                        'id' => '1',
                        'title' => 'Teste',
                        'quantity' => 1,
                        'unit_price' => 100.00
                    ]
                ]
            ]
        ];
        echo '<pre style="background: #0d4220; border-color: #3fb950;">' . json_encode($pixPayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . '</pre>';
        
        echo '<h3 style="margin-top: 15px;">BOLETO (teste atual):</h3>';
        $boletoPayloadCompare = [
            'transaction_amount' => 100.00,
            'description' => 'Teste',
            'payment_method_id' => 'bolbradesco',
            'payer' => [
                'email' => 'test@example.com',
                'first_name' => 'Teste',
                'last_name' => 'Teste',
                'identification' => [
                    'type' => 'CPF',
                    'number' => '12345678909'
                ]
            ],
            'additional_info' => [
                'items' => [
                    [
                        'id' => '1',
                        'title' => 'Teste',
                        'quantity' => 1,
                        'unit_price' => 100.00
                    ]
                ]
            ]
        ];
        echo '<pre style="background: #1a1a2e; border-color: #58a6ff;">' . json_encode($boletoPayloadCompare, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . '</pre>';
        
        echo '<p style="margin-top: 15px;"><strong>✅ Estrutura IDÊNTICA (apenas payment_method_id muda)</strong></p>';
        echo '</div>';
        
        // ============================================================
        // 5. VERIFICAÇÃO DE LOGS
        // ============================================================
        echo '<div class="section warning">';
        echo '<h2>5️⃣ Verificação de Logs</h2>';
        
        $logFile = __DIR__ . '/erro_php_bruto.log';
        if (file_exists($logFile)) {
            $logContent = file_get_contents($logFile);
            $logLines = explode("\n", $logContent);
            $recentLines = array_slice($logLines, -50); // Últimas 50 linhas
            
            echo '<p><strong>Arquivo de log:</strong> <code>' . htmlspecialchars($logFile) . '</code></p>';
            echo '<p><strong>Últimas 50 linhas:</strong></p>';
            echo '<pre style="max-height: 400px; overflow-y: auto; font-size: 11px;">' . htmlspecialchars(implode("\n", $recentLines)) . '</pre>';
        } else {
            echo '<p>⚠️ Arquivo de log não encontrado: <code>' . htmlspecialchars($logFile) . '</code></p>';
        }
        echo '</div>';
        
        // ============================================================
        // 6. INFORMAÇÕES DO AMBIENTE
        // ============================================================
        echo '<div class="section">';
        echo '<h2>6️⃣ Informações do Ambiente</h2>';
        echo '<ul>';
        echo '<li><strong>PHP Version:</strong> <code>' . phpversion() . '</code></li>';
        echo '<li><strong>Servidor:</strong> <code>' . ($_SERVER['SERVER_SOFTWARE'] ?? 'N/A') . '</code></li>';
        echo '<li><strong>Host:</strong> <code>' . ($_SERVER['HTTP_HOST'] ?? 'N/A') . '</code></li>';
        echo '<li><strong>Data/Hora:</strong> <code>' . date('Y-m-d H:i:s') . '</code></li>';
        
        // Verificar se o SDK está carregado
        if (class_exists('MercadoPago\Client\Payment\PaymentClient')) {
            echo '<li><strong>SDK Mercado Pago:</strong> <span class="badge badge-success">Carregado</span></li>';
        } else {
            echo '<li><strong>SDK Mercado Pago:</strong> <span class="badge badge-error">Não encontrado</span></li>';
        }
        
        echo '</ul>';
        echo '</div>';
        ?>
        
        <div class="section info">
            <h2>📋 Próximos Passos</h2>
            <ol style="margin-left: 20px;">
                <li>Execute o teste acima clicando no botão "Executar Teste"</li>
                <li>Verifique a resposta completa da API (erros específicos)</li>
                <li>Compare a estrutura do payload com a documentação oficial</li>
                <li>Verifique se o token está correto e a conta está habilitada para boleto</li>
                <li>Se o teste acima funcionar, o problema está na estrutura do payload real do sistema</li>
            </ol>
        </div>
    </div>
</body>
</html>

