<?php
session_start();

// 🔐 Protección con contraseña
if (!isset($_SESSION['autorizado'])) {

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {

        if ($_POST['clave'] === 'MONTEROAMP') {
            $_SESSION['autorizado'] = true;
            header("Location: " . $_SERVER['REQUEST_URI']);
            exit;
        } else {
            $error = "Clave incorrecta";
        }

    } else {
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
        </head>
        <body class="bg-light">

        <div class="container">
            <div class="card shadow p-4" style="max-width:400px;margin:120px auto;">
                <div class="text-center mb-4">
                    <i class="bi bi-shield-lock-fill text-primary" style="font-size: 3rem;"></i>
                    <h5 class="mt-2">Acceso Restringido</h5>
                </div>

                <?php if(isset($error)) echo "<div class='alert alert-danger'>$error</div>"; ?>

                <form method="POST">
                    <input type="password" name="clave" class="form-control mb-3" placeholder="Ingrese contraseña" required>
                    <button class="btn btn-primary w-100">Ingresar</button>
                </form>
            </div>
        </div>

        </body>
        </html>
        <?php
        exit;
    }
}

require_once 'conexion/conexion.php';

if (!isset($_GET['telefono'])) {
    die("Teléfono requerido.");
}

$telefono = $_GET['telefono'];

// Validación básica seguridad
if (!preg_match('/^[67]\d{8}$/', $telefono)) {
    die("Formato de teléfono inválido.");
}

// Buscar último registro de ese teléfono
$stmt = $pdo->prepare("
    SELECT *
    FROM registros
    WHERE telefono = ?
    ORDER BY fecha_hora DESC
    LIMIT 1
");

$stmt->execute([$telefono]);
$data = $stmt->fetch();

if (!$data) {
    die("No se encontró registro.");
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <title>Documento de Aceptación de Datos</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .document-card {
            border: none;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .document-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            position: relative;
        }
        
        .logo-container {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        
        .logo-icon {
            background: white;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #667eea;
            font-size: 2rem;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .company-info h1 {
            margin: 0;
            font-size: 1.8rem;
            font-weight: 600;
        }
        
        .company-info p {
            margin: 0;
            opacity: 0.9;
            font-size: 0.9rem;
        }
        
        .watermark {
            position: absolute;
            bottom: 10px;
            right: 20px;
            opacity: 0.1;
            font-size: 3rem;
            transform: rotate(-15deg);
            pointer-events: none;
        }
        
        .document-body {
            padding: 2rem;
            background: white;
        }
        
        .info-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            border-left: 4px solid #667eea;
        }
        
        .section-title {
            color: #495057;
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .section-title i {
            color: #667eea;
            font-size: 1.3rem;
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
        }
        
        .info-item {
            padding: 0.5rem;
            border-radius: 8px;
            transition: background 0.3s;
        }
        
        .info-item:hover {
            background: white;
        }
        
        .info-label {
            font-size: 0.85rem;
            color: #6c757d;
            margin-bottom: 0.2rem;
        }
        
        .info-value {
            font-size: 1rem;
            font-weight: 500;
            color: #212529;
        }
        
        .consent-badge {
            display: inline-block;
            padding: 0.35rem 1rem;
            border-radius: 50px;
            font-weight: 500;
            font-size: 0.9rem;
        }
        
        .consent-yes {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .consent-no {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .tech-details {
            background: #e9ecef;
            border-radius: 8px;
            padding: 1rem;
            font-size: 0.9rem;
        }
        
        .footer-note {
            margin-top: 2rem;
            padding-top: 1rem;
            border-top: 2px dashed #dee2e6;
            text-align: center;
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .btn-print {
            position: fixed;
            bottom: 20px;
            right: 20px;
            border-radius: 50px;
            padding: 0.75rem 1.5rem;
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        @media print {
            body {
                background: white;
            }
            .btn-print {
                display: none;
            }
            .document-header {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="document-card">
        <!-- Header con logo -->
        <div class="document-header">
            <div class="logo-container">
                <div class="logo-icon">
                    <i class="bi bi-shield-check"></i>
                </div>
                <div class="company-info">
                    <h1>DataProtect S.L.</h1>
                    <p>Protección de Datos y Cumplimiento RGPD</p>
                </div>
            </div>
            <div class="watermark">
                <i class="bi bi-file-earmark-text"></i>
            </div>
        </div>
        
        <!-- Cuerpo del documento -->
        <div class="document-body">
            <div class="text-center mb-4">
                <h4 class="text-primary">Documento de Aceptación de Datos</h4>
                <p class="text-muted">Registro de consentimiento informado</p>
            </div>
            
            <!-- Información personal -->
            <div class="info-section">
                <div class="section-title">
                    <i class="bi bi-person-badge"></i>
                    <span>Información Personal</span>
                </div>
                <div class="info-grid">
                    <div class="info-item">
                        <div class="info-label">Nombre completo</div>
                        <div class="info-value"><?= htmlspecialchars($data['nombre']) ?> <?= htmlspecialchars($data['apellido']) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Teléfono</div>
                        <div class="info-value"><?= htmlspecialchars($data['telefono']) ?></div>
                    </div>
                    <div class="info-item">
                        <div class="info-label">Correo electrónico</div>
                        <div class="info-value"><?= htmlspecialchars($data['correo']) ?></div>
                    </div>
                </div>
            </div>
            
            <!-- Consentimientos -->
            <div class="info-section">
                <div class="section-title">
                    <i class="bi bi-check-circle"></i>
                    <span>Consentimientos</span>
                </div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <div class="info-label mb-2">Tratamiento de datos personales</div>
                        <span class="consent-badge <?= $data['acepta_datos'] ? 'consent-yes' : 'consent-no' ?>">
                            <i class="bi <?= $data['acepta_datos'] ? 'bi-check-circle' : 'bi-x-circle' ?> me-1"></i>
                            <?= $data['acepta_datos'] ? 'Aceptado' : 'No aceptado' ?>
                        </span>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="info-label mb-2">Comunicaciones comerciales</div>
                        <span class="consent-badge <?= $data['acepta_comerciales'] ? 'consent-yes' : 'consent-no' ?>">
                            <i class="bi <?= $data['acepta_comerciales'] ? 'bi-check-circle' : 'bi-x-circle' ?> me-1"></i>
                            <?= $data['acepta_comerciales'] ? 'Aceptado' : 'No aceptado' ?>
                        </span>
                    </div>
                </div>
            </div>
            
            <!-- Información técnica -->
            <div class="info-section">
                <div class="section-title">
                    <i class="bi bi-shield-lock"></i>
                    <span>Información Técnica del Registro</span>
                </div>
                
                <div class="tech-details">
                    <div class="row">
                        <div class="col-md-6">
                            <p class="mb-2"><i class="bi bi-hdd-network text-primary me-2"></i> <strong>IP:</strong> <?= $data['ip_usuario'] ?></p>
                            <p class="mb-2"><i class="bi bi-calendar-check text-primary me-2"></i> <strong>Fecha y hora:</strong> <?= date('d/m/Y H:i:s', strtotime($data['fecha_hora'])) ?></p>
                            <p class="mb-2"><i class="bi bi-globe text-primary me-2"></i> <strong>País:</strong> <?= $data['pais'] ?></p>
                        </div>
                        <div class="col-md-6">
                            <p class="mb-2"><i class="bi bi-geo-alt text-primary me-2"></i> <strong>Provincia:</strong> <?= $data['provincia'] ?></p>
                            <!--<p class="mb-2"><i class="bi bi-wifi text-primary me-2"></i> <strong>Proveedor:</strong> <?= $data['proveedor'] ?></p>-->
                            <p class="mb-2">
                                <i class="bi <?= $data['vpn_detectado'] ? 'bi-exclamation-triangle text-warning' : 'bi-check-circle text-success' ?> me-2"></i> 
                                <strong>VPN detectado:</strong> 
                                <span class="badge bg-<?= $data['vpn_detectado'] ? 'warning' : 'success' ?>">
                                    <?= $data['vpn_detectado'] ? 'Sí' : 'No' ?>
                                </span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Firma digital y fecha -->
            <div class="info-section">
                <div class="section-title">
                    <i class="bi bi-pencil-square"></i>
                    <span>Firma Digital</span>
                </div>
                <div class="row">
                    <div class="col-md-6">
                        <p class="mb-1"><strong>Registro realizado el:</strong></p>
                        <p><?= date('d \d\e F \d\e Y \a \l\a\s H:i', strtotime($data['fecha_hora'])) ?></p>
                    </div>
                    <div class="col-md-6">
                        <p class="mb-1"><strong>Identificador único:</strong></p>
                        <p class="text-monospace"><?= md5($data['telefono'] . $data['fecha_hora']) ?></p>
                    </div>
                </div>
            </div>
            
            <div class="footer-note">
                <i class="bi bi-shield-check text-primary me-2"></i>
                Este documento certifica el consentimiento informado del usuario según el RGPD y la LOPDGDD.
                <br>
                <small>Documento generado electrónicamente - Válido sin firma manuscrita</small>
            </div>
        </div>
    </div>
</div>

<!-- Botón para imprimir -->
<button class="btn btn-primary btn-print" onclick="window.print()">
    <i class="bi bi-printer me-2"></i>Imprimir / Guardar PDF
</button>

</body>
</html>