Vinculaciones multi-agencia
This commit is contained in:
@@ -1,32 +1,32 @@
|
||||
<?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';
|
||||
|
||||
use PHPMailer\PHPMailer\PHPMailer;
|
||||
use PHPMailer\PHPMailer\Exception;
|
||||
|
||||
loadEnv();
|
||||
|
||||
function index() {
|
||||
function index()
|
||||
{
|
||||
include __DIR__ . '/../../views/registro/form.php';
|
||||
}
|
||||
|
||||
function enviar() {
|
||||
// Validar reCAPTCHA
|
||||
$captchaResponse = $_POST['g-recaptcha-response'] ?? '';
|
||||
|
||||
// Función auxiliar para validar reCAPTCHA
|
||||
function validarRecaptcha($captchaResponse)
|
||||
{
|
||||
if (!$captchaResponse) {
|
||||
die("❌ Debes completar el reCAPTCHA.");
|
||||
}
|
||||
|
||||
$secretKey = $_ENV['RECAPTCHA_SECRET'];
|
||||
|
||||
$verifyUrl = "https://www.google.com/recaptcha/api/siteverify";
|
||||
|
||||
$data = [
|
||||
'secret' => $secretKey,
|
||||
'secret' => $secretKey,
|
||||
'response' => $captchaResponse
|
||||
];
|
||||
|
||||
@@ -39,58 +39,98 @@ function enviar() {
|
||||
];
|
||||
|
||||
$context = stream_context_create($options);
|
||||
$result = file_get_contents($verifyUrl, false, $context);
|
||||
$result = file_get_contents($verifyUrl, false, $context);
|
||||
$response = json_decode($result);
|
||||
|
||||
if (!$response->success) {
|
||||
die("❌ Error de verificación reCAPTCHA.");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
$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'] ?? ''))) {
|
||||
// Función auxiliar para validaciones
|
||||
function validarDatos($rfc, $email, $telefono)
|
||||
{
|
||||
// Validar RFC
|
||||
if (!preg_match('/^[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}$/', strtoupper($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)) {
|
||||
// Validar email
|
||||
if (!preg_match('/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', strtolower($email))) {
|
||||
die("❌ No es una dirección de correo válida.");
|
||||
}
|
||||
|
||||
// Validar teléfono (formato nacional: 3 dígitos + espacio + 7 dígitos)
|
||||
// Validar teléfono
|
||||
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.");
|
||||
// Función auxiliar para manejar archivos
|
||||
function procesarArchivo($archivo)
|
||||
{
|
||||
if ($archivo['error'] !== UPLOAD_ERR_OK) {
|
||||
die("❌ Error al subir el archivo.");
|
||||
}
|
||||
|
||||
// Validar tipo MIME real del archivo
|
||||
$finfo = finfo_open(FILEINFO_MIME_TYPE);
|
||||
$mimeType = finfo_file($finfo, $archivo['tmp_name']);
|
||||
finfo_close($finfo);
|
||||
|
||||
if ($mimeType !== 'application/pdf') {
|
||||
die("❌ El archivo debe ser un PDF válido.");
|
||||
}
|
||||
|
||||
// Validar extensión
|
||||
if (pathinfo($archivo['name'], PATHINFO_EXTENSION) !== 'pdf') {
|
||||
die("❌ Solo se permiten archivos PDF.");
|
||||
}
|
||||
|
||||
// Validar tamaño (5MB máximo)
|
||||
if ($archivo['size'] > 5 * 1024 * 1024) {
|
||||
die("❌ El archivo no debe exceder 5MB.");
|
||||
}
|
||||
|
||||
// Guardar archivo
|
||||
// Guardar archivo con nombre único
|
||||
$nombreArchivo = uniqid() . '_' . basename($archivo['name']);
|
||||
$rutaDestino = __DIR__ . '/../../storage/opiniones/' . $nombreArchivo;
|
||||
move_uploaded_file($archivo['tmp_name'], $rutaDestino);
|
||||
$rutaDestino = __DIR__ . '/../../storage/opiniones/' . $nombreArchivo;
|
||||
|
||||
if (!move_uploaded_file($archivo['tmp_name'], $rutaDestino)) {
|
||||
die("❌ Error al guardar el archivo.");
|
||||
}
|
||||
|
||||
return $nombreArchivo;
|
||||
}
|
||||
|
||||
// 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));
|
||||
}
|
||||
// Función auxiliar para obtener configuración
|
||||
function obtenerConfiguracion($conn)
|
||||
{
|
||||
$sqlConf = "SELECT TOP 1 * FROM configuracion_sistema";
|
||||
$stmtConf = sqlsrv_query($conn, $sqlConf);
|
||||
|
||||
if ($stmtConf === false) {
|
||||
error_log("Error al obtener configuración: " . print_r(sqlsrv_errors(), true));
|
||||
return [
|
||||
'nombre_plataforma' => 'Sistema Integral para Importadores de Hidrocarburos',
|
||||
'siglas' => 'SIIH',
|
||||
'logo_url' => 'assets/img/logo_siih.png',
|
||||
'colores_primarios' => '#003366,#0055A5'
|
||||
];
|
||||
}
|
||||
|
||||
return sqlsrv_fetch_array($stmtConf, SQLSRV_FETCH_ASSOC) ?: [
|
||||
'nombre_plataforma' => 'Sistema Integral para Importadores de Hidrocarburos',
|
||||
'siglas' => 'SIIH',
|
||||
'logo_url' => 'assets/img/logo_siih.png',
|
||||
'colores_primarios' => '#003366,#0055A5'
|
||||
];
|
||||
}
|
||||
|
||||
// Función auxiliar para enviar email
|
||||
function enviarEmailConfirmacion($destinatario, $datosEmpresa, $esAgencia = false)
|
||||
{
|
||||
$mail = new PHPMailer(true);
|
||||
|
||||
try {
|
||||
@@ -99,31 +139,31 @@ function enviar() {
|
||||
$mail->Host = 'secure.emailsrvr.com';
|
||||
$mail->SMTPAuth = true;
|
||||
$mail->Username = 'noreply@aduanasoft.com.mx';
|
||||
$mail->Password = $_ENV['SMTP_PASS']; // desde el .env
|
||||
$mail->Password = $_ENV['SMTP_PASS'];
|
||||
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
|
||||
$mail->Port = 587;
|
||||
|
||||
// Correo remitente y destinatario
|
||||
// Configurar remitente y destinatario
|
||||
$mail->setFrom('noreply@aduanasoft.com.mx', 'SIIH | AduanaSoft');
|
||||
$mail->addAddress($email); // destinatario principal
|
||||
$mail->addAddress($destinatario);
|
||||
|
||||
// Formato y contenido
|
||||
// Obtener configuración
|
||||
$conn = getConnection();
|
||||
$conf = obtenerConfiguracion($conn);
|
||||
|
||||
$nombrePlataforma = $conf['nombre_plataforma'];
|
||||
$siglas = $conf['siglas'];
|
||||
$logoUrl = $conf['logo_url'];
|
||||
$color2 = explode(',', $conf['colores_primarios'])[1];
|
||||
|
||||
// Contenido del email
|
||||
$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];
|
||||
$tipoRegistro = $esAgencia ? 'Agencia' : 'Empresa';
|
||||
$nombreEntidad = $esAgencia ? $datosEmpresa['agencia'] : $datosEmpresa['empresa'];
|
||||
|
||||
$mail->Body = "
|
||||
<div style='font-family: Segoe UI, sans-serif; background-color: #f4f6f9; padding: 40px;'>
|
||||
@@ -138,28 +178,141 @@ function enviar() {
|
||||
|
||||
<hr style='margin: 20px 0;'>
|
||||
|
||||
<p><strong>📋 Empresa:</strong> " . htmlspecialchars($_POST['company_name']) . "</p>
|
||||
<p><strong>📞 Teléfono:</strong> " . htmlspecialchars($telefono) . "</p>
|
||||
<p><strong>📋 $tipoRegistro:</strong> " . htmlspecialchars($nombreEntidad) . "</p>
|
||||
<p><strong>📞 Teléfono:</strong> " . htmlspecialchars($datosEmpresa['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;'>Un administrador 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;'>
|
||||
© " . date('Y') . " $siglas · Desarrollado por AduanaSoft
|
||||
© " . date('Y') . " $siglas · $nombrePlataforma
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
";
|
||||
</div>";
|
||||
|
||||
$mail->send();
|
||||
return true;
|
||||
} catch (Exception $e) {
|
||||
error_log("Error al enviar correo: {$mail->ErrorInfo}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
include __DIR__ . '/../../views/registro/gracias.php';
|
||||
}
|
||||
function enviarSoliImportador()
|
||||
{
|
||||
try {
|
||||
// Validar reCAPTCHA
|
||||
validarRecaptcha($_POST['g-recaptcha-response'] ?? '');
|
||||
|
||||
$conn = getConnection();
|
||||
|
||||
// Sanitizar y obtener datos
|
||||
$empresa = trim($_POST['company_name'] ?? '');
|
||||
$rfc = trim($_POST['rfc'] ?? '');
|
||||
$email = trim($_POST['email'] ?? '');
|
||||
$telefono = trim($_POST['phone'] ?? '');
|
||||
|
||||
// Validar datos
|
||||
validarDatos($rfc, $email, $telefono);
|
||||
|
||||
// Procesar archivo
|
||||
$nombreArchivo = procesarArchivo($_FILES['opinion_file']);
|
||||
|
||||
// Encriptar datos sensibles
|
||||
$empresaEncriptada = encrypt($empresa);
|
||||
$rfcEncriptado = encrypt(strtoupper($rfc));
|
||||
|
||||
// Insertar en base de datos
|
||||
$sql = "INSERT INTO solicitudes_importadores
|
||||
(company_name, rfc, email, phone, opinion_file, request_status, request_date)
|
||||
VALUES (?, ?, ?, ?, ?, 'pending', GETDATE())";
|
||||
|
||||
$params = [$empresaEncriptada, $rfcEncriptado, $email, $telefono, $nombreArchivo];
|
||||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||||
|
||||
if ($stmt === false) {
|
||||
error_log("Error en BD: " . print_r(sqlsrv_errors(), true));
|
||||
die("❌ Error al procesar la solicitud.");
|
||||
}
|
||||
|
||||
// Enviar email de confirmación
|
||||
$datosEmpresa = [
|
||||
'empresa' => $empresa,
|
||||
'telefono' => $telefono
|
||||
];
|
||||
enviarEmailConfirmacion($email, $datosEmpresa, false);
|
||||
|
||||
include __DIR__ . '/../../views/registro/gracias.php';
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error en enviarSoliImportador: " . $e->getMessage());
|
||||
die("❌ Error interno del servidor.");
|
||||
}
|
||||
}
|
||||
|
||||
function enviarSoliAgencia()
|
||||
{
|
||||
try {
|
||||
// Validar reCAPTCHA
|
||||
validarRecaptcha($_POST['g-recaptcha-response'] ?? '');
|
||||
|
||||
$conn = getConnection();
|
||||
|
||||
// Sanitizar y obtener datos
|
||||
$agencia = trim($_POST['nombre_agencia'] ?? '');
|
||||
$rfc = trim($_POST['rfc'] ?? '');
|
||||
$correo = trim($_POST['correo'] ?? '');
|
||||
$telefono = trim($_POST['telefono'] ?? '');
|
||||
$direccion = trim($_POST['direccion'] ?? '');
|
||||
$admin = trim($_POST['nombre_admin'] ?? '');
|
||||
$admin_correo = trim($_POST['correo_admin'] ?? '');
|
||||
|
||||
// Validar datos principales
|
||||
validarDatos($rfc, $correo, $telefono);
|
||||
|
||||
// Validar correo del administrador
|
||||
if (!preg_match('/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/', strtolower($admin_correo))) {
|
||||
die("❌ El correo del administrador no es válido.");
|
||||
}
|
||||
|
||||
// Procesar archivo
|
||||
$nombreArchivo = procesarArchivo($_FILES['opinion_file']);
|
||||
|
||||
// Encriptar datos sensibles
|
||||
$agenciaEncriptada = encrypt($agencia);
|
||||
$rfcEncriptado = encrypt(strtoupper($rfc));
|
||||
$adminEncriptado = encrypt($admin);
|
||||
|
||||
// Insertar en base de datos
|
||||
$sql = "INSERT INTO solicitudes_agencias
|
||||
(agencia_name, rfc, email, phone, direccion, opinion_file, admin_name, admin_email, request_status, request_date)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', GETDATE())";
|
||||
|
||||
$params = [$agenciaEncriptada, $rfcEncriptado, $correo, $telefono, $direccion, $nombreArchivo, $adminEncriptado, $admin_correo];
|
||||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||||
|
||||
if ($stmt === false) {
|
||||
error_log("Error en BD: " . print_r(sqlsrv_errors(), true));
|
||||
die("❌ Error al procesar la solicitud.");
|
||||
}
|
||||
|
||||
// Enviar email de confirmación
|
||||
$datosAgencia = [
|
||||
'agencia' => $agencia,
|
||||
'telefono' => $telefono
|
||||
];
|
||||
enviarEmailConfirmacion($correo, $datosAgencia, true);
|
||||
|
||||
include __DIR__ . '/../../views/registro/gracias.php';
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error en enviarSoliAgencia: " . $e->getMessage());
|
||||
die("❌ Error interno del servidor.");
|
||||
}
|
||||
}
|
||||
?>
|
||||
Reference in New Issue
Block a user