<?php
/**
 * Test API - Verificar estrutura do banco de dados
 * Acesse este arquivo diretamente para diagnóstico
 */

header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Carregar configuração
require_once __DIR__ . '/../config/database.php';

$results = [];

try {
    $pdo = getDBConnection();
    $results['connection'] = 'OK';
    
    // Listar todas as tabelas
    $stmt = $pdo->query("SHOW TABLES");
    $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
    $results['tables'] = $tables;
    
    // Verificar estrutura de cada tabela relevante
    $checkTables = ['admin_users', 'admin_sessions', 'sites', 'events', 'api_tokens', 'site_user_permissions'];
    
    foreach ($checkTables as $table) {
        if (in_array($table, $tables)) {
            $stmt = $pdo->query("DESCRIBE {$table}");
            $columns = $stmt->fetchAll(PDO::FETCH_COLUMN);
            $results['schema'][$table] = $columns;
        } else {
            $results['schema'][$table] = 'TABLE NOT EXISTS';
        }
    }
    
    // Contar registros
    foreach (['admin_users', 'sites', 'events'] as $table) {
        if (in_array($table, $tables)) {
            $count = $pdo->query("SELECT COUNT(*) FROM {$table}")->fetchColumn();
            $results['counts'][$table] = $count;
        }
    }
    
    // Testar login
    $stmt = $pdo->prepare("SELECT id, username, role, site_id FROM admin_users WHERE username = ?");
    $stmt->execute(['admin']);
    $user = $stmt->fetch();
    $results['admin_user'] = $user ?: 'NOT FOUND';
    
} catch (PDOException $e) {
    $results['error'] = $e->getMessage();
}

echo json_encode($results, JSON_PRETTY_PRINT);
