<?php
/**
 * Debug PDF Path - Diagnosticar problema de PDF no encontrado
 */
error_reporting(E_ALL);
ini_set('display_errors', '1');

require_once __DIR__ . '/config/bootstrap.php';

use App\Services\Database;

$db = Database::getInstance();
$contractId = $_GET['id'] ?? null;

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Debug PDF Path</title>
    <style>
        body { font-family: monospace; padding: 20px; background: #1e1e1e; color: #d4d4d4; }
        .success { color: #4ec9b0; }
        .error { color: #f48771; }
        .warning { color: #dcdcaa; }
        .info { color: #4fc1ff; }
        pre { background: #252526; padding: 15px; border-radius: 6px; overflow-x: auto; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        th, td { padding: 10px; text-align: left; border-bottom: 1px solid #3e3e42; }
        th { color: #4ec9b0; background: #2d2d30; }
        .section { margin: 30px 0; padding: 20px; background: #252526; border-radius: 8px; }
    </style>
</head>
<body>

<h1>🔍 Debug PDF Path</h1>

<?php
// Obtener contratos firmados
$signatures = $db->query("
    SELECT
        c.id,
        c.titulo,
        c.cliente_nombre,
        s.firmado_at,
        s.pdf_path,
        s.pdf_hash
    FROM signatures s
    INNER JOIN contracts c ON s.contract_id = c.id
    ORDER BY s.firmado_at DESC
    LIMIT 10
");

if (empty($signatures)) {
    echo '<p class="error">❌ No hay contratos firmados</p>';
    exit;
}

echo '<div class="section">';
echo '<h2>Contratos Firmados con PDF</h2>';
echo '<table>';
echo '<tr><th>ID</th><th>Título</th><th>PDF Path (BD)</th><th>Existe?</th><th>Debug</th></tr>';

foreach ($signatures as $sig) {
    $pdfPath = $sig['pdf_path'];

    // Intentar diferentes formas de construir el path
    $attempts = [
        'path_db' => $pdfPath,
        'path_absolute' => __DIR__ . '/' . $pdfPath,
        'path_storage' => __DIR__ . '/storage/' . basename($pdfPath),
        'path_public_storage' => __DIR__ . '/public/storage/' . basename($pdfPath),
    ];

    $found = false;
    $foundPath = null;

    foreach ($attempts as $key => $path) {
        if (file_exists($path)) {
            $found = true;
            $foundPath = $path;
            break;
        }
    }

    echo '<tr>';
    echo '<td>' . $sig['id'] . '</td>';
    echo '<td>' . htmlspecialchars(substr($sig['titulo'], 0, 30)) . '</td>';
    echo '<td style="font-size:10px;">' . htmlspecialchars($pdfPath ?? 'NULL') . '</td>';
    echo '<td>' . ($found ? '<span class="success">✅ SÍ</span>' : '<span class="error">❌ NO</span>') . '</td>';
    echo '<td><a href="?id=' . $sig['id'] . '" style="color:#4fc1ff;">Ver detalles</a></td>';
    echo '</tr>';
}

echo '</table>';
echo '</div>';

// Si hay un ID seleccionado, mostrar detalles
if ($contractId) {
    $signature = $db->fetchOne("
        SELECT
            c.*,
            s.pdf_path,
            s.pdf_hash,
            s.firmado_at
        FROM signatures s
        INNER JOIN contracts c ON s.contract_id = c.id
        WHERE c.id = :id
    ", [':id' => $contractId]);

    if ($signature) {
        echo '<div class="section">';
        echo '<h2>Detalles del Contrato #' . $contractId . '</h2>';

        echo '<h3>Información en BD:</h3>';
        echo '<pre>';
        echo 'ID: ' . $signature['id'] . "\n";
        echo 'Título: ' . $signature['titulo'] . "\n";
        echo 'PDF Path (BD): ' . ($signature['pdf_path'] ?? 'NULL') . "\n";
        echo 'PDF Hash: ' . ($signature['pdf_hash'] ?? 'NULL') . "\n";
        echo 'Firmado: ' . $signature['firmado_at'] . "\n";
        echo '</pre>';

        echo '<h3>Verificación de Rutas:</h3>';
        echo '<table>';
        echo '<tr><th>Método</th><th>Path</th><th>Existe?</th><th>Tamaño</th></tr>';

        $pdfPath = $signature['pdf_path'];

        $attempts = [
            'DB Value' => $pdfPath,
            'Absolute (__DIR__ + path)' => __DIR__ . '/' . $pdfPath,
            'Storage + basename' => __DIR__ . '/storage/' . basename($pdfPath),
            'Public storage + basename' => __DIR__ . '/public/storage/' . basename($pdfPath),
            'Storage/pdfs + basename' => __DIR__ . '/storage/pdfs/' . basename($pdfPath),
        ];

        foreach ($attempts as $method => $path) {
            $exists = file_exists($path);
            $size = $exists ? filesize($path) : 0;

            echo '<tr>';
            echo '<td><strong>' . $method . '</strong></td>';
            echo '<td style="font-size:10px;max-width:400px;word-break:break-all;">' . htmlspecialchars($path) . '</td>';
            echo '<td>' . ($exists ? '<span class="success">✅ SÍ</span>' : '<span class="error">❌ NO</span>') . '</td>';
            echo '<td>' . ($exists ? number_format($size / 1024, 2) . ' KB' : '-') . '</td>';
            echo '</tr>';
        }

        echo '</table>';

        // Buscar todos los PDFs en storage
        echo '<h3>PDFs en storage/pdfs/:</h3>';
        $pdfDir = __DIR__ . '/storage/pdfs/';

        if (is_dir($pdfDir)) {
            $files = glob($pdfDir . '*.pdf');

            if (empty($files)) {
                echo '<p class="warning">⚠️ No hay archivos PDF en storage/pdfs/</p>';
            } else {
                echo '<table>';
                echo '<tr><th>Archivo</th><th>Tamaño</th><th>Fecha</th></tr>';

                foreach ($files as $file) {
                    echo '<tr>';
                    echo '<td>' . basename($file) . '</td>';
                    echo '<td>' . number_format(filesize($file) / 1024, 2) . ' KB</td>';
                    echo '<td>' . date('Y-m-d H:i:s', filemtime($file)) . '</td>';
                    echo '</tr>';
                }

                echo '</table>';
            }
        } else {
            echo '<p class="error">❌ El directorio storage/pdfs/ no existe</p>';
        }

        echo '</div>';

        // Solución propuesta
        echo '<div class="section">';
        echo '<h2>💡 Solución</h2>';

        $correctPath = null;
        foreach ($attempts as $method => $path) {
            if (file_exists($path)) {
                $correctPath = $path;
                break;
            }
        }

        if ($correctPath) {
            echo '<p class="success">✅ El PDF SÍ existe en:</p>';
            echo '<pre>' . htmlspecialchars($correctPath) . '</pre>';

            echo '<p class="info">El problema está en cómo se construye el path. El path correcto debería ser:</p>';

            // Calcular path relativo desde __DIR__
            $relativePath = str_replace(__DIR__ . '/', '', $correctPath);
            echo '<pre>' . htmlspecialchars($relativePath) . '</pre>';

            echo '<p>Para arreglar, actualiza la BD:</p>';
            echo '<pre style="background:#2d2d30;color:#4fc1ff;padding:15px;">';
            echo "UPDATE signatures \n";
            echo "SET pdf_path = '" . addslashes($relativePath) . "'\n";
            echo "WHERE contract_id = " . $contractId . ";";
            echo '</pre>';

            echo '<form method="POST" style="margin-top:20px;">';
            echo '<input type="hidden" name="action" value="fix_path">';
            echo '<input type="hidden" name="contract_id" value="' . $contractId . '">';
            echo '<input type="hidden" name="new_path" value="' . htmlspecialchars($relativePath) . '">';
            echo '<button type="submit" style="background:#4ec9b0;color:#000;padding:10px 20px;border:none;border-radius:6px;cursor:pointer;font-weight:bold;">
                    🔧 Corregir Path en BD
                  </button>';
            echo '</form>';

        } else {
            echo '<p class="error">❌ El PDF NO existe en ninguna ubicación conocida</p>';
            echo '<p>Opciones:</p>';
            echo '<ol>';
            echo '<li>Regenera el PDF del contrato</li>';
            echo '<li>Verifica que el proceso de firma complete correctamente</li>';
            echo '<li>Revisa los permisos del directorio storage/pdfs/</li>';
            echo '</ol>';
        }

        echo '</div>';
    }
}

// Procesar corrección de path
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['action'] === 'fix_path') {
    $contractId = (int)$_POST['contract_id'];
    $newPath = $_POST['new_path'];

    try {
        $db->query("UPDATE signatures SET pdf_path = :path WHERE contract_id = :id", [
            ':path' => $newPath,
            ':id' => $contractId
        ]);

        echo '<div class="section">';
        echo '<p class="success">✅ Path actualizado correctamente</p>';
        echo '<p><a href="test-email-pdf.php" style="color:#4fc1ff;">→ Ir a test-email-pdf.php para probar</a></p>';
        echo '</div>';
    } catch (Exception $e) {
        echo '<div class="section">';
        echo '<p class="error">❌ Error: ' . htmlspecialchars($e->getMessage()) . '</p>';
        echo '</div>';
    }
}
?>

<div class="section">
    <h2>📁 Información del Sistema</h2>
    <pre>
__DIR__: <?= __DIR__ ?>

Directorios importantes:
- storage/pdfs/: <?= is_dir(__DIR__ . '/storage/pdfs/') ? '✅ Existe' : '❌ No existe' ?>

- public/storage/: <?= is_dir(__DIR__ . '/public/storage/') ? '✅ Existe' : '❌ No existe' ?>

    </pre>
</div>

<p><a href="test-email-pdf.php" style="color:#4fc1ff;">← Volver a test-email-pdf.php</a></p>

</body>
</html>
