<?php
// api/test-api.php - Teste básico

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

try {
    // Teste 1: PHP básico
    $info = [
        'status' => 'OK',
        'php_version' => PHP_VERSION,
        'timestamp' => date('Y-m-d H:i:s'),
        'method' => $_SERVER['REQUEST_METHOD'],
        'base_path' => dirname(dirname(__FILE__))
    ];
    
    // Teste 2: Verificar arquivos includes
    $basePath = dirname(dirname(__FILE__));
    $files = [
        'config' => $basePath . '/includes/config.php',
        'db' => $basePath . '/includes/db.php',
        'functions' => $basePath . '/includes/functions.php'
    ];
    
    foreach ($files as $name => $path) {
        $info['files'][$name] = file_exists($path) ? 'EXISTS' : 'NOT_FOUND';
    }
    
    // Teste 3: Se for POST, mostrar dados recebidos
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = file_get_contents('php://input');
        $info['post_data'] = $input;
        $info['json_decoded'] = json_decode($input, true);
        $info['json_error'] = json_last_error_msg();
    }
    
    // Teste 4: Tentar incluir arquivos e testar banco
    if ($info['files']['config'] === 'EXISTS' && 
        $info['files']['db'] === 'EXISTS' && 
        $info['files']['functions'] === 'EXISTS') {
        
        try {
            require_once $files['config'];
            require_once $files['db'];
            require_once $files['functions'];
            
            $info['includes'] = 'SUCCESS';
            
            // Testar banco
            global $db;
            if (isset($db)) {
                $db->query("SELECT COUNT(*) as total FROM pages");
                $result = $db->single();
                $info['database'] = 'CONNECTED';
                $info['total_pages'] = $result['total'];
            } else {
                $info['database'] = 'NO_DB_OBJECT';
            }
            
        } catch (Exception $e) {
            $info['includes'] = 'ERROR: ' . $e->getMessage();
        }
    }
    
    echo json_encode($info, JSON_PRETTY_PRINT);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error' => $e->getMessage(),
        'file' => __FILE__,
        'line' => $e->getLine()
    ]);
}
?>