Files
MVE/app/controllers/registro.php

165 lines
6.5 KiB
PHP

<?php
require_once __DIR__ . '/../../vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../helpers/session.php';
require_once __DIR__ . '/../helpers/env.php';
require_once __DIR__ . '/../helpers/crypto.php';
loadEnv();
function index() {
include __DIR__ . '/../../views/registro/form.php';
}
function enviar() {
// Validar reCAPTCHA
$captchaResponse = $_POST['g-recaptcha-response'] ?? '';
if (!$captchaResponse) {
die("❌ Debes completar el reCAPTCHA.");
}
$secretKey = $_ENV['RECAPTCHA_SECRET'];
$verifyUrl = "https://www.google.com/recaptcha/api/siteverify";
$data = [
'secret' => $secretKey,
'response' => $captchaResponse
];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($verifyUrl, false, $context);
$response = json_decode($result);
if (!$response->success) {
die("❌ Error de verificación reCAPTCHA.");
}
$conn = getConnection();
$empresa = encrypt(trim($_POST['company_name'] ?? ''));
$rfc = strtoupper(encrypt(trim($_POST['rfc'] ?? '')));
$email = trim($_POST['email'] ?? '');
$telefono = trim($_POST['phone'] ?? '');
$archivo = $_FILES['opinion_file'];
// Validar RFC (12 o 13 caracteres con formato correcto)
if (!preg_match('/^[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}$/', strtoupper($_POST['rfc'] ?? ''))) {
die("❌ El RFC no tiene un formato válido.");
}
// Validar email (solo minúsculas, sin caracteres especiales fuera del estándar)
if (!preg_match('/^[a-z0-9._+-]+@[a-z0-9.-]+\.[a-z]{2,}$/', $email)) {
die("❌ No es una dirección de correo válida.");
}
// Validar teléfono (formato nacional: 3 dígitos + espacio + 7 dígitos)
if (!preg_match('/^\d{3}\s\d{7}$/', $telefono)) {
die("❌ El número de teléfono no tiene un formato válido. Ejemplo: 123 4567890");
}
// Validar archivo
if ($archivo['error'] !== 0 || pathinfo($archivo['name'], PATHINFO_EXTENSION) !== 'pdf') {
die("❌ Archivo inválido. Solo se permiten PDFs.");
}
// Guardar archivo
$nombreArchivo = uniqid() . '_' . basename($archivo['name']);
$rutaDestino = __DIR__ . '/../../storage/opiniones/' . $nombreArchivo;
move_uploaded_file($archivo['tmp_name'], $rutaDestino);
// Insertar en la base de datos
$sql = "INSERT INTO solicitudes_importadores
(company_name, rfc, email, phone, opinion_file, request_status, request_date)
VALUES (?, ?, ?, ?, ?, 'pending', GETDATE())";
$params = [$empresa, $rfc, $email, $telefono, $nombreArchivo];
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
$mail = new PHPMailer(true);
try {
// Configuración SMTP
$mail->isSMTP();
$mail->Host = 'secure.emailsrvr.com';
$mail->SMTPAuth = true;
$mail->Username = 'noreply@aduanasoft.com.mx';
$mail->Password = $_ENV['SMTP_PASS']; // desde el .env
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
// Correo remitente y destinatario
$mail->setFrom('noreply@aduanasoft.com.mx', 'SIIH | AduanaSoft');
$mail->addAddress($email); // destinatario principal
// Formato y contenido
$mail->CharSet = 'UTF-8';
$mail->isHTML(true);
$mail->Subject = 'Confirmación de solicitud de registro | SIIH';
$fechaRegistro = date('d/m/Y H:i');
// Consulta configuración institucional
$sqlConf = "SELECT TOP 1 * FROM configuracion_sistema";
$stmtConf = sqlsrv_query($conn, $sqlConf);
$conf = sqlsrv_fetch_array($stmtConf, SQLSRV_FETCH_ASSOC);
$nombrePlataforma = $conf['nombre_plataforma'] ?? 'Sistema Integral para Importadores de Hidrocarburos';
$siglas = $conf['siglas'] ?? 'SIIH';
$logoUrl = $conf['logo_url'] ?? 'assets/img/logo_siih.png';
$color1 = explode(',', $conf['colores_primarios'] ?? '#003366,#0055A5')[0];
$color2 = explode(',', $conf['colores_primarios'] ?? '#003366,#0055A5')[1];
$mail->Body = "
<div style='font-family: Segoe UI, sans-serif; background-color: #f4f6f9; padding: 40px;'>
<div style='max-width: 600px; margin: auto; background: #fff; border: 1px solid #ddd; border-radius: 10px; overflow: hidden;'>
<div style='background: linear-gradient(to right, #FFF, $color2); padding: 20px; text-align: center;'>
<img src='http://{$_SERVER['HTTP_HOST']}/IMPORTADORES/public/$logoUrl' alt='Logo $siglas' style='height: 140px;'>
<h2 style='color: #fff; margin-top: 10px;'>Confirmación de Registro</h2>
</div>
<div style='padding: 30px; color: #333;'>
<p style='font-size: 16px;'>¡Hola!</p>
<p style='font-size: 15px;'>Tu solicitud de registro ha sido recibida exitosamente en <strong>$nombrePlataforma</strong>.</p>
<hr style='margin: 20px 0;'>
<p><strong>📋 Empresa:</strong> " . htmlspecialchars($_POST['company_name']) . "</p>
<p><strong>📞 Teléfono:</strong> " . htmlspecialchars($telefono) . "</p>
<p><strong>🕓 Fecha de registro:</strong> $fechaRegistro</p>
<hr style='margin: 20px 0;'>
<p style='font-size: 14px;'>Un agente aduanal revisará tu información y te notificará por este medio cuando tu solicitud sea aprobada.</p>
<p style='font-size: 14px;'>Por favor, mantente atento a tu correo (y revisa también tu carpeta de spam o promociones).</p>
<p style='margin-top: 30px; font-size: 13px; color: #888;'>Este es un mensaje automático enviado por el sistema de registro de importadores.</p>
</div>
<div style='background: #f1f1f1; text-align: center; padding: 15px; font-size: 12px; color: #666;'>
&copy; " . date('Y') . " $siglas · Desarrollado por AduanaSoft
</div>
</div>
</div>
";
$mail->send();
} catch (Exception $e) {
error_log("Error al enviar correo: {$mail->ErrorInfo}");
}
include __DIR__ . '/../../views/registro/gracias.php';
}