<?php
require_once __DIR__ . '/../../config/bootstrap.php';
require_once __DIR__ . '/../../includes/require-auth.php';

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

$auth = new AuthService();
$contractService = new ContractService();
$signatureService = new SignatureService();
$security = new SecurityService();

$user = requireAuth($auth);
$rol = $user['rol'] ?? 'asesor';
$esAdmin = ($rol === 'administrador');

$contractId = (int) ($_GET['id'] ?? 0);
$contract = $contractService->getById($contractId);

// Admin puede ver cualquier contrato; asesor solo los suyos
if (!$contract || (!$esAdmin && $contract['admin_id'] != $user['id'])) {
    header('Location: ' . base_url('admin/dashboard'));
    exit;
}

// Obtener firma si existe
$signature = null;
if ($contract['estado'] === 'firmado') {
    $signature = $signatureService->getByContract($contractId);
}

$signatureLink = $contractService->getSignatureLink($contract['token']);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ver Contrato - Sistema de Contratos</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        * {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "Helvetica Neue", Arial, sans-serif;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            letter-spacing: -0.011em;
        }

        /* Estilos para el contenido del contrato */
        .contract-content h1 {
            font-size: 1.875rem;
            font-weight: 700;
            margin-top: 1.5rem;
            margin-bottom: 1rem;
            color: #111827;
            line-height: 1.2;
        }

        .contract-content h2 {
            font-size: 1.5rem;
            font-weight: 600;
            margin-top: 1.25rem;
            margin-bottom: 0.75rem;
            color: #1f2937;
            line-height: 1.3;
        }

        .contract-content h3 {
            font-size: 1.25rem;
            font-weight: 600;
            margin-top: 1rem;
            margin-bottom: 0.5rem;
            color: #374151;
            line-height: 1.4;
        }

        .contract-content p {
            margin-bottom: 1rem;
            line-height: 1.7;
        }

        .contract-content ul, .contract-content ol {
            margin-left: 1.5rem;
            margin-bottom: 1rem;
            line-height: 1.7;
        }

        .contract-content ul {
            list-style-type: disc;
        }

        .contract-content ol {
            list-style-type: decimal;
        }

        .contract-content li {
            margin-bottom: 0.5rem;
        }

        .contract-content strong {
            font-weight: 600;
            color: #111827;
        }

        .contract-content em {
            font-style: italic;
        }

        .contract-content u {
            text-decoration: underline;
        }

        .contract-content a {
            color: #4f46e5;
            text-decoration: underline;
        }

        .contract-content a:hover {
            color: #4338ca;
        }

        .contract-content img {
            max-width: 100%;
            height: auto;
            margin: 1rem 0;
            border-radius: 0.5rem;
        }

        .contract-content table {
            width: 100%;
            border-collapse: collapse;
            margin: 1rem 0;
        }

        .contract-content table th,
        .contract-content table td {
            border: 1px solid #e5e7eb;
            padding: 0.5rem;
            text-align: left;
        }

        .contract-content table th {
            background-color: #f9fafb;
            font-weight: 600;
        }

        .contract-content blockquote {
            border-left: 4px solid #e5e7eb;
            padding-left: 1rem;
            margin: 1rem 0;
            font-style: italic;
            color: #6b7280;
        }

        .contract-content pre {
            background-color: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 0.375rem;
            padding: 1rem;
            overflow-x: auto;
            margin: 1rem 0;
        }

        .contract-content code {
            background-color: #f3f4f6;
            padding: 0.125rem 0.25rem;
            border-radius: 0.25rem;
            font-family: 'Courier New', monospace;
            font-size: 0.875rem;
        }
    </style>
</head>
<body class="bg-gray-50 flex flex-col min-h-screen">
    <?php include __DIR__ . '/../../includes/admin-nav.php'; ?>

    <main class="flex-1 max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8 w-full">
        <div class="mb-6">
            <a href="<?= base_url('admin/dashboard') ?>" class="text-indigo-600 hover:text-indigo-700 text-sm font-medium">
                ← Volver al Dashboard
            </a>
        </div>

        <?php if (isset($_GET['created'])): ?>
        <div class="mb-6 bg-green-50 border-l-4 border-green-500 p-4 rounded">
            <div class="flex items-center">
                <svg class="w-5 h-5 text-green-500 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                </svg>
                <div>
                    <p class="text-sm font-semibold text-green-700">¡Contrato creado exitosamente!</p>
                    <p class="text-xs text-green-600 mt-1">Puedes copiar el link de firma y enviarlo al cliente.</p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <?php if (isset($_GET['cancelled'])): ?>
        <div class="mb-6 bg-yellow-50 border-l-4 border-yellow-500 p-4 rounded">
            <div class="flex items-center">
                <svg class="w-5 h-5 text-yellow-500 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
                <p class="text-sm font-semibold text-yellow-700">Contrato cancelado correctamente.</p>
            </div>
        </div>
        <?php endif; ?>

        <?php if (isset($_GET['error'])): ?>
        <div class="mb-6 bg-red-50 border-l-4 border-red-500 p-4 rounded">
            <div class="flex items-center">
                <svg class="w-5 h-5 text-red-500 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <p class="text-sm font-semibold text-red-700"><?= htmlspecialchars($_GET['error']) ?></p>
            </div>
        </div>
        <?php endif; ?>

        <!-- Header -->
        <div class="bg-white rounded-lg shadow p-6 mb-6">
            <div class="flex items-start justify-between">
                <div class="flex-1">
                    <h1 class="text-2xl font-bold text-gray-900 mb-2"><?= htmlspecialchars($contract['titulo']) ?></h1>
                    <p class="text-sm text-gray-500">ID: #<?= str_pad($contract['id'], 6, '0', STR_PAD_LEFT) ?></p>
                    <p class="text-sm text-gray-500">Creado: <?= date('d/m/Y H:i', strtotime($contract['created_at'])) ?></p>
                </div>
                <div>
                    <?php
                    $badgeColors = [
                        'firmado' => 'bg-green-100 text-green-800',
                        'pendiente' => 'bg-yellow-100 text-yellow-800',
                        'expirado' => 'bg-red-100 text-red-800',
                        'cancelado' => 'bg-gray-100 text-gray-800'
                    ];
                    $color = $badgeColors[$contract['estado']] ?? 'bg-gray-100 text-gray-800';
                    ?>
                    <span class="px-4 py-2 inline-flex text-sm leading-5 font-semibold rounded-full <?= $color ?>">
                        <?= ucfirst($contract['estado']) ?>
                    </span>
                </div>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- Contenido Principal -->
            <div class="lg:col-span-2 space-y-6">
                <!-- Contenido del Contrato -->
                <div class="bg-white rounded-lg shadow p-6">
                    <h2 class="text-lg font-semibold mb-4">Contenido del Contrato</h2>
                    <div class="contract-content text-gray-700">
                        <?= $contract['contenido'] ?>
                    </div>
                </div>

                <!-- Evidencias de Firma -->
                <?php if ($signature): ?>
                    <div class="bg-white rounded-lg shadow p-6">
                        <h2 class="text-lg font-semibold mb-4">Evidencias de Firma</h2>

                        <div class="grid grid-cols-2 gap-4 mb-6">
                            <div>
                                <h3 class="text-sm font-medium text-gray-700 mb-2">Selfie</h3>
                                <img src="/admin/download-image?id=<?= $signature['id'] ?>&type=selfie" class="w-full rounded border">
                            </div>
                            <div>
                                <h3 class="text-sm font-medium text-gray-700 mb-2">Firma Digital</h3>
                                <img src="/admin/download-image?id=<?= $signature['id'] ?>&type=firma" class="w-full rounded border bg-white">
                            </div>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <h3 class="text-sm font-medium text-gray-700 mb-2">Documento Frontal</h3>
                                <img src="/admin/download-image?id=<?= $signature['id'] ?>&type=documento_frontal" class="w-full rounded border">
                            </div>
                            <div>
                                <h3 class="text-sm font-medium text-gray-700 mb-2">Documento Trasero</h3>
                                <img src="/admin/download-image?id=<?= $signature['id'] ?>&type=documento_trasero" class="w-full rounded border">
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Sidebar -->
            <div class="space-y-6">
                <!-- Información del Cliente -->
                <div class="bg-white rounded-lg shadow p-6">
                    <h2 class="text-lg font-semibold mb-4">Cliente</h2>
                    <dl class="space-y-3">
                        <div>
                            <dt class="text-sm text-gray-500">Nombre</dt>
                            <dd class="text-sm font-medium text-gray-900"><?= htmlspecialchars($contract['cliente_nombre']) ?></dd>
                        </div>
                        <div>
                            <dt class="text-sm text-gray-500">Email</dt>
                            <dd class="text-sm font-medium text-gray-900">
                                <?= !empty($contract['cliente_email']) ? htmlspecialchars($contract['cliente_email']) : '<span class="italic text-gray-400">No proporcionado</span>' ?>
                            </dd>
                        </div>
                        <?php if ($contract['cliente_telefono']): ?>
                            <div>
                                <dt class="text-sm text-gray-500">Teléfono</dt>
                                <dd class="text-sm font-medium text-gray-900"><?= htmlspecialchars($contract['cliente_telefono']) ?></dd>
                            </div>
                        <?php endif; ?>
                    </dl>
                </div>

                <!-- Datos del Firmante -->
                <?php if ($signature): ?>
                    <?php
                    $meta = [];
                    if (!empty($signature['metadata'])) {
                        $meta = json_decode($signature['metadata'], true) ?? [];
                    }
                    $tipoDocMap = [
                        'CC'  => 'Cédula de Ciudadanía',
                        'TI'  => 'Tarjeta de Identidad',
                        'CE'  => 'Cédula de Extranjería',
                        'PP'  => 'Pasaporte',
                        'DNI' => 'DNI',
                        'RUT' => 'RUT',
                        'PAS' => 'Pasaporte',
                    ];
                    // Compatibilidad: columnas dedicadas tienen prioridad; fallback a metadata
                    $firmante = [
                        'nombre_completo'  => $signature['nombre_completo']  ?? ($meta['nombre_completo']  ?? null),
                        'fecha_nacimiento' => $signature['fecha_nacimiento'] ?? ($meta['fecha_nacimiento'] ?? null),
                        'fecha_expedicion' => $signature['fecha_expedicion'] ?? ($meta['fecha_expedicion'] ?? null),
                        'telefono'         => $signature['telefono']         ?? ($meta['telefono']         ?? null),
                    ];
                    ?>
                    <div class="bg-white rounded-lg shadow p-6">
                        <h2 class="text-lg font-semibold mb-4">Datos del Firmante</h2>
                        <dl class="space-y-3">
                            <?php if ($firmante['nombre_completo']): ?>
                            <div>
                                <dt class="text-xs text-gray-500 uppercase tracking-wide">Nombre completo</dt>
                                <dd class="text-sm font-semibold text-gray-900 mt-0.5"><?= htmlspecialchars($firmante['nombre_completo']) ?></dd>
                            </div>
                            <?php endif; ?>

                            <?php if ($firmante['fecha_nacimiento']): ?>
                            <div>
                                <dt class="text-xs text-gray-500 uppercase tracking-wide">Fecha de nacimiento</dt>
                                <dd class="text-sm font-medium text-gray-900 mt-0.5">
                                    <?= date('d/m/Y', strtotime($firmante['fecha_nacimiento'])) ?>
                                </dd>
                            </div>
                            <?php endif; ?>

                            <?php if ($firmante['telefono']): ?>
                            <div>
                                <dt class="text-xs text-gray-500 uppercase tracking-wide">Teléfono</dt>
                                <dd class="text-sm font-medium text-gray-900 mt-0.5">
                                    <a href="tel:+<?= htmlspecialchars($firmante['telefono']) ?>" class="text-indigo-600 hover:underline">
                                        +<?= htmlspecialchars($firmante['telefono']) ?>
                                    </a>
                                </dd>
                            </div>
                            <?php endif; ?>

                            <div class="border-t border-gray-100 pt-3">
                                <dt class="text-xs text-gray-500 uppercase tracking-wide">Documento</dt>
                                <dd class="text-sm font-medium text-gray-900 mt-0.5">
                                    <span class="inline-block bg-indigo-100 text-indigo-800 text-xs font-bold px-2 py-0.5 rounded mr-1">
                                        <?= htmlspecialchars($signature['tipo_documento']) ?>
                                    </span>
                                    <?= htmlspecialchars($signature['numero_documento']) ?>
                                </dd>
                                <?php if ($firmante['fecha_expedicion']): ?>
                                <dd class="text-xs text-gray-500 mt-1">
                                    Expedición: <?= date('d/m/Y', strtotime($firmante['fecha_expedicion'])) ?>
                                </dd>
                                <?php endif; ?>
                            </div>
                        </dl>
                    </div>

                    <!-- Datos de Firma (auditoría) -->
                    <div class="bg-white rounded-lg shadow p-6">
                        <h2 class="text-lg font-semibold mb-4">Auditoría de Firma</h2>
                        <dl class="space-y-3">
                            <div>
                                <dt class="text-xs text-gray-500 uppercase tracking-wide">Fecha y hora</dt>
                                <dd class="text-sm font-medium text-gray-900 mt-0.5"><?= date('d/m/Y H:i:s', strtotime($signature['firmado_at'])) ?></dd>
                            </div>
                            <div>
                                <dt class="text-xs text-gray-500 uppercase tracking-wide">Dirección IP</dt>
                                <dd class="text-sm font-medium text-gray-900 mt-0.5 font-mono"><?= htmlspecialchars($signature['ip_address']) ?></dd>
                            </div>
                            <?php if (!empty($meta['timezone'])): ?>
                            <div>
                                <dt class="text-xs text-gray-500 uppercase tracking-wide">Zona horaria</dt>
                                <dd class="text-sm font-medium text-gray-900 mt-0.5"><?= htmlspecialchars($meta['timezone']) ?></dd>
                            </div>
                            <?php endif; ?>
                            <?php if (!empty($meta['language'])): ?>
                            <div>
                                <dt class="text-xs text-gray-500 uppercase tracking-wide">Idioma del dispositivo</dt>
                                <dd class="text-sm font-medium text-gray-900 mt-0.5"><?= htmlspecialchars($meta['language']) ?></dd>
                            </div>
                            <?php endif; ?>
                            <?php if (!empty($meta['screen_width']) && !empty($meta['screen_height'])): ?>
                            <div>
                                <dt class="text-xs text-gray-500 uppercase tracking-wide">Resolución de pantalla</dt>
                                <dd class="text-sm font-medium text-gray-900 mt-0.5"><?= (int)$meta['screen_width'] ?> × <?= (int)$meta['screen_height'] ?> px</dd>
                            </div>
                            <?php endif; ?>
                            <?php if ($signature['ubicacion_lat'] && $signature['ubicacion_lng']): ?>
                            <div>
                                <dt class="text-xs text-gray-500 uppercase tracking-wide">Ubicación GPS</dt>
                                <dd class="text-sm font-medium text-gray-900 mt-0.5">
                                    <?= number_format((float)$signature['ubicacion_lat'], 6) ?>,
                                    <?= number_format((float)$signature['ubicacion_lng'], 6) ?>
                                    <?php if ($signature['ubicacion_precision']): ?>
                                    <span class="text-xs text-gray-400 ml-1">(±<?= (int)$signature['ubicacion_precision'] ?>m)</span>
                                    <?php endif; ?>
                                </dd>
                                <dd class="mt-1">
                                    <a href="https://maps.google.com/?q=<?= $signature['ubicacion_lat'] ?>,<?= $signature['ubicacion_lng'] ?>"
                                       target="_blank" rel="noopener"
                                       class="text-xs text-indigo-600 hover:underline">
                                        Ver en Google Maps →
                                    </a>
                                </dd>
                            </div>
                            <?php endif; ?>
                            <?php if (!empty($signature['user_agent'])): ?>
                            <div class="border-t border-gray-100 pt-3">
                                <dt class="text-xs text-gray-500 uppercase tracking-wide">User-Agent</dt>
                                <dd class="text-xs text-gray-600 mt-0.5 break-all leading-relaxed"><?= htmlspecialchars($signature['user_agent']) ?></dd>
                            </div>
                            <?php endif; ?>
                        </dl>
                    </div>
                <?php endif; ?>

                <!-- Acciones -->
                <div class="bg-white rounded-lg shadow p-6">
                    <h2 class="text-lg font-semibold mb-4">Acciones</h2>
                    <div class="space-y-3">
                        <?php if ($contract['estado'] === 'pendiente'): ?>
                            <div>
                                <label class="text-sm text-gray-700 mb-1 block">Link de Firma</label>
                                <div class="flex gap-2">
                                    <input
                                        type="text"
                                        readonly
                                        value="<?= htmlspecialchars($signatureLink) ?>"
                                        id="signature-link"
                                        class="flex-1 px-3 py-2 text-xs border rounded"
                                    >
                                    <button onclick="copyLink()" class="px-3 py-2 bg-indigo-600 text-white text-xs rounded hover:bg-indigo-700">
                                        Copiar
                                    </button>
                                </div>
                            </div>
                        <?php endif; ?>

                        <?php if ($signature && $signature['pdf_path']): ?>
                            <a href="<?= base_url('admin/download-pdf?id=' . $signature['id']) ?>" target="_blank" class="block w-full px-4 py-2 bg-green-600 text-white text-center rounded hover:bg-green-700">
                                Ver PDF
                            </a>
                        <?php endif; ?>

                        <?php if ($contract['estado'] === 'pendiente' && $esAdmin): ?>
                            <button onclick="cancelContract()" class="w-full px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700">
                                Cancelar Contrato
                            </button>
                        <?php elseif ($contract['estado'] === 'pendiente' && !$esAdmin): ?>
                            <p class="text-xs text-gray-400 text-center">Solo el administrador puede cancelar contratos.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <script>
        function copyLink() {
            const input = document.getElementById('signature-link');
            input.select();
            document.execCommand('copy');
            alert('Link copiado al portapapeles');
        }

        function cancelContract() {
            if (confirm('¿Está seguro de cancelar este contrato?')) {
                window.location.href = '<?= base_url('admin/cancel-contract') ?>?id=<?= $contractId ?>';
            }
        }
    </script>

    <?php include __DIR__ . '/../../includes/admin-footer.php'; ?>
</body>
</html>
