<?php

/**
 * Test de Creación de Contrato - Para Debug en Hosting
 */
error_reporting(E_ALL);
ini_set('display_errors', '1');

// Cargar bootstrap primero
require_once __DIR__ . '/../../config/bootstrap.php';
require_once __DIR__ . '/../../includes/get-fallback-user.php';

use App\Services\AuthService;
use App\Services\ContractService;
use App\Services\SecurityService;

echo "<h1>Test de Creación de Contrato</h1>";
echo "<pre>";

echo "=== INFORMACIÓN DEL SERVIDOR ===\n";
echo "PHP Version: " . phpversion() . "\n";
echo "Server Software: " . ($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown') . "\n";
echo "Document Root: " . $_SERVER['DOCUMENT_ROOT'] . "\n\n";

echo "=== ARCHIVOS Y RUTAS ===\n";
$requiredFiles = [
    __DIR__ . '/../../config/bootstrap.php',
    __DIR__ . '/../../src/Services/AuthService.php',
    __DIR__ . '/../../src/Services/ContractService.php',
    __DIR__ . '/../../src/Services/SecurityService.php',
];

foreach ($requiredFiles as $file) {
    echo ($file . ": " . (file_exists($file) ? "✅ Existe" : "❌ NO EXISTE") . "\n");
}

echo "\n=== VERIFICANDO .ENV ===\n";
echo "DB_HOST: " . ($_ENV['DB_HOST'] ?? 'NO CONFIGURADO') . "\n";
echo "DB_NAME: " . ($_ENV['DB_NAME'] ?? 'NO CONFIGURADO') . "\n";
echo "DB_USER: " . ($_ENV['DB_USER'] ?? 'NO CONFIGURADO') . "\n";
echo "APP_URL: " . ($_ENV['APP_URL'] ?? 'NO CONFIGURADO') . "\n";
echo "MAIL_ENABLED: " . ($_ENV['MAIL_ENABLED'] ?? 'NO CONFIGURADO') . "\n";

echo "\n=== VERIFICANDO SERVICIOS ===\n";
try {

    $auth = new AuthService();
    echo "✅ AuthService creado\n";

    $contractService = new ContractService();
    echo "✅ ContractService creado\n";

    $security = new SecurityService();
    echo "✅ SecurityService creado\n";
} catch (Exception $e) {
    echo "❌ Error creando servicios: " . $e->getMessage() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
    die();
}

echo "\n=== VERIFICANDO USUARIO ===\n";
try {
    $user = $auth->user();
    if ($user) {
        echo "Usuario ID: " . $user['id'] . "\n";
        echo "Usuario Nombre: " . $user['nombre'] . "\n";
        echo "Usuario Rol: " . ($user['rol'] ?? 'asesor') . "\n";
    } else {
        echo "⚠️ No hay sesión activa - requiere login\n";
        // En modo development, intentar getFallbackUser para testing
        if (($_ENV['APP_ENV'] ?? 'production') === 'development') {
            $user = getFallbackUser();
            echo "📝 Usando fallback user (solo development):\n";
            echo "   ID: " . $user['id'] . "\n";
            echo "   Nombre: " . $user['nombre'] . "\n";
            echo "   Rol: " . ($user['rol'] ?? 'asesor') . "\n";
        }
    }
} catch (Exception $e) {
    echo "❌ Error obteniendo usuario: " . $e->getMessage() . "\n";
}

echo "\n=== VERIFICANDO PERMISOS DE CARPETAS ===\n";
$folders = [
    storage_path('contracts'),
    storage_path('logos'),
    storage_path('logs'),
    storage_path('signatures'),
];

foreach ($folders as $folder) {
    if (!is_dir($folder)) {
        echo "❌ NO EXISTE: $folder\n";
    } elseif (!is_writable($folder)) {
        echo "⚠️  NO ESCRIBIBLE: $folder\n";
    } else {
        echo "✅ OK: $folder\n";
    }
}

echo "\n=== TEST DE CREACIÓN DE CONTRATO ===\n";
try {
    $testData = [
        'admin_id' => $user['id'],
        'titulo' => 'TEST - Contrato de Prueba',
        'contenido' => '<p>Este es un contrato de prueba</p>',
        'cliente_nombre' => 'Cliente Test',
        'cliente_email' => 'test@ejemplo.com',
        'cliente_telefono' => '1234567890',
        'expiration_hours' => 24
    ];

    echo "Intentando crear contrato con datos:\n";
    print_r($testData);

    $result = $contractService->create($testData);

    echo "\nResultado:\n";
    print_r($result);

    if ($result['success']) {
        echo "\n✅ ¡CONTRATO CREADO EXITOSAMENTE!\n";
        echo "ID del contrato: " . $result['contract_id'] . "\n";
    } else {
        echo "\n❌ ERROR AL CREAR CONTRATO\n";
        echo "Mensaje: " . $result['message'] . "\n";
    }
} catch (Exception $e) {
    echo "❌ EXCEPCIÓN AL CREAR CONTRATO:\n";
    echo "Mensaje: " . $e->getMessage() . "\n";
    echo "Archivo: " . $e->getFile() . ":" . $e->getLine() . "\n";
    echo "Stack trace:\n" . $e->getTraceAsString() . "\n";
}

echo "</pre>";
echo "<hr>";
echo "<p><a href='crear-contrato.php'>← Volver a Crear Contrato</a></p>";
