<?php
// Script temporal de diagnóstico - ELIMINAR luego de usarlo
header('Content-Type: text/plain; charset=utf-8');

echo "=== ZeroTrust Shield - Diagnóstico ===\n\n";

// PHP
echo "PHP Version: " . PHP_VERSION . "\n";
echo "SAPI: " . PHP_SAPI . "\n\n";

// Extensiones necesarias
$exts = ['pdo', 'pdo_mysql', 'curl', 'openssl', 'json', 'session'];
echo "--- Extensiones PHP ---\n";
foreach ($exts as $e) {
    echo "  $e: " . (extension_loaded($e) ? "OK" : "FALTA") . "\n";
}

// allow_url_fopen
echo "\n--- Configuración PHP ---\n";
echo "  allow_url_fopen:  " . (ini_get('allow_url_fopen')  ? "habilitado" : "DESHABILITADO") . "\n";
echo "  allow_url_include:" . (ini_get('allow_url_include') ? "habilitado" : "deshabilitado (normal)") . "\n";
echo "  display_errors:   " . ini_get('display_errors') . "\n";
echo "  error_log:        " . ini_get('error_log') . "\n";
echo "  upload_max:       " . ini_get('upload_max_filesize') . "\n";
echo "  memory_limit:     " . ini_get('memory_limit') . "\n";

// cURL
echo "\n--- cURL ---\n";
if (function_exists('curl_version')) {
    $cv = curl_version();
    echo "  Version: " . $cv['version'] . "\n";
    echo "  SSL:     " . $cv['ssl_version'] . "\n";
} else {
    echo "  cURL NO disponible\n";
}

// Base de datos
echo "\n--- Base de datos ---\n";
require_once __DIR__ . '/config.php';
try {
    require_once __DIR__ . '/db.php';
    $pdo = db();
    echo "  Conexión: OK\n";
    echo "  Servidor: " . $pdo->query('SELECT VERSION()')->fetchColumn() . "\n";
    $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    echo "  Tablas:   " . (empty($tables) ? "NINGUNA (ejecutar install.php)" : implode(', ', $tables)) . "\n";
    if (in_array('query_logs', $tables)) {
        $count = $pdo->query("SELECT COUNT(*) FROM query_logs")->fetchColumn();
        echo "  Registros en query_logs: $count\n";
    }
    if (in_array('users', $tables)) {
        $ucount = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
        echo "  Usuarios: $ucount\n";
    }
} catch (Exception $e) {
    echo "  ERROR: " . $e->getMessage() . "\n";
}

// Conectividad a AdGuard via cURL
echo "\n--- Conectividad AdGuard (cURL) ---\n";
foreach (ADGUARD_SERVERS as $srv) {
    echo "  [{$srv['id']}] {$srv['url']}: ";
    if (!function_exists('curl_init')) {
        echo "cURL no disponible\n";
        continue;
    }
    $ch = curl_init($srv['url'] . '/control/status');
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_USERPWD        => $srv['user'] . ':' . $srv['pass'],
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $err  = curl_error($ch);
    curl_close($ch);
    if ($err) echo "ERROR cURL: $err\n";
    elseif ($code === 200) echo "OK (HTTP 200)\n";
    else echo "HTTP $code\n";
}

// Conectividad via file_get_contents
echo "\n--- Conectividad AdGuard (file_get_contents) ---\n";
foreach (ADGUARD_SERVERS as $srv) {
    echo "  [{$srv['id']}]: ";
    $ctx = stream_context_create(['http' => [
        'header'  => 'Authorization: Basic ' . base64_encode($srv['user'].':'.$srv['pass']),
        'timeout' => 10,
    ], 'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]);
    $r = @file_get_contents($srv['url'] . '/control/status', false, $ctx);
    echo ($r !== false ? "OK" : "FALLA (allow_url_fopen puede estar deshabilitado)") . "\n";
}

// Permisos de escritura
echo "\n--- Permisos de escritura ---\n";
echo "  Directorio raíz: " . (is_writable(__DIR__) ? "escribible" : "solo lectura") . "\n";

// Sessions
echo "\n--- Sesiones PHP ---\n";
echo "  session.save_path: " . (ini_get('session.save_path') ?: "(por defecto)") . "\n";
echo "  session.save_handler: " . ini_get('session.save_handler') . "\n";

echo "\n=== Fin del diagnóstico ===\n";
echo "IMPORTANTE: Elimine este archivo (diagnostico.php) luego de usarlo.\n";
