<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('log_errors', '1');

echo "<!DOCTYPE html><html><body><pre>";
echo "=== TEST BÁSICO ===\n\n";

// 1. Info PHP
echo "✅ PHP Funciona!\n";
echo "PHP Version: " . phpversion() . "\n";
echo "Document Root: " . ($_SERVER['DOCUMENT_ROOT'] ?? 'unknown') . "\n";
echo "Script Path: " . __FILE__ . "\n\n";

// 2. Verificar archivos críticos
echo "=== ARCHIVOS CRÍTICOS ===\n";

$baseDir = dirname(dirname(__DIR__)); // Sube 2 niveles desde /public/admin/
echo "Base Directory: $baseDir\n\n";

$files = [
    '.env' => $baseDir . '/.env',
    'bootstrap' => $baseDir . '/config/bootstrap.php',
    'vendor autoload' => $baseDir . '/vendor/autoload.php',
];

foreach ($files as $name => $path) {
    if (file_exists($path)) {
        echo "✅ $name: existe\n";
        if ($name === '.env') {
            echo "   Tamaño: " . filesize($path) . " bytes\n";
            echo "   Permisos: " . substr(sprintf('%o', fileperms($path)), -4) . "\n";
        }
    } else {
        echo "❌ $name: NO EXISTE - $path\n";
    }
}

// 3. Test carga de .env (sin bootstrap)
echo "\n=== TEST CARGA .ENV ===\n";
try {
    if (!file_exists($baseDir . '/vendor/autoload.php')) {
        echo "❌ Composer autoload NO existe\n";
    } else {
        require_once $baseDir . '/vendor/autoload.php';
        echo "✅ Autoload cargado\n";

        if (!file_exists($baseDir . '/.env')) {
            echo "❌ Archivo .env NO existe\n";
        } else {
            $dotenv = Dotenv\Dotenv::createImmutable($baseDir);
            $dotenv->load();
            echo "✅ .env cargado\n";

            echo "\nVariables .env:\n";
            echo "  DB_HOST: " . ($_ENV['DB_HOST'] ?? 'NO DEFINIDO') . "\n";
            echo "  DB_NAME: " . ($_ENV['DB_NAME'] ?? 'NO DEFINIDO') . "\n";
            echo "  DB_USER: " . ($_ENV['DB_USER'] ?? 'NO DEFINIDO') . "\n";
            echo "  APP_URL: " . ($_ENV['APP_URL'] ?? 'NO DEFINIDO') . "\n";
        }
    }
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n";
    echo "Archivo: " . $e->getFile() . ":" . $e->getLine() . "\n";
}

// 4. Test conexión DB
echo "\n=== TEST CONEXIÓN DATABASE ===\n";
try {
    if (!isset($_ENV['DB_HOST'])) {
        echo "⚠️  Variables DB no cargadas\n";
    } else {
        $host = $_ENV['DB_HOST'];
        $dbname = $_ENV['DB_NAME'];
        $user = $_ENV['DB_USER'];
        $pass = $_ENV['DB_PASS'] ?? '';

        $dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4";
        $pdo = new PDO($dsn, $user, $pass);
        echo "✅ Conexión a DB exitosa\n";

        // Test query
        $stmt = $pdo->query("SELECT COUNT(*) as total FROM admins");
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        echo "  Admins en DB: " . $result['total'] . "\n";

        $stmt = $pdo->query("SELECT COUNT(*) as total FROM contracts");
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        echo "  Contratos en DB: " . $result['total'] . "\n";
    }
} catch (Exception $e) {
    echo "❌ Error DB: " . $e->getMessage() . "\n";
}

// 5. Verificar carpetas storage
echo "\n=== CARPETAS STORAGE ===\n";
$storagePath = $baseDir . '/storage';
$folders = [
    'storage' => $storagePath,
    'contracts' => $storagePath . '/contracts',
    'logos' => $storagePath . '/logos',
    'logs' => $storagePath . '/logs',
];

foreach ($folders as $name => $path) {
    if (!is_dir($path)) {
        echo "❌ $name: NO EXISTE - $path\n";
    } elseif (!is_writable($path)) {
        echo "⚠️  $name: NO ESCRIBIBLE - " . substr(sprintf('%o', fileperms($path)), -4) . "\n";
    } else {
        echo "✅ $name: OK\n";
    }
}

// 6. Test carga bootstrap completo
echo "\n=== TEST BOOTSTRAP COMPLETO ===\n";
try {
    require_once $baseDir . '/config/bootstrap.php';
    echo "✅ Bootstrap cargado correctamente\n";
} catch (Exception $e) {
    echo "❌ Error en bootstrap: " . $e->getMessage() . "\n";
    echo "Archivo: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "Trace: " . $e->getTraceAsString() . "\n";
}

echo "\n=== FIN DEL TEST ===\n";
echo "</pre></body></html>";
?>
