219 lines
9.1 KiB
PHP
219 lines
9.1 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../../vendor/autoload.php';
|
|
|
|
require_once __DIR__ . '/../helpers/session.php';
|
|
require_once __DIR__ . '/../../config/database.php';
|
|
require_once __DIR__ . '/../helpers/crypto.php';
|
|
require_once __DIR__ . '/../helpers/bitacoras.php';
|
|
require_once __DIR__ . '/../helpers/env.php';
|
|
|
|
use PHPMailer\PHPMailer\PHPMailer;
|
|
use PHPMailer\PHPMailer\Exception;
|
|
|
|
loadEnv();
|
|
|
|
function dashboard()
|
|
{
|
|
if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'admin_agencia') {
|
|
header("Location: /IMPORTADORES/login");
|
|
exit;
|
|
}
|
|
|
|
include __DIR__ . '/../../views/agencias/dashboard_agencias.php';
|
|
}
|
|
|
|
function solicitudesVinculacion()
|
|
{
|
|
include __DIR__ . '/../../views/agencias/solicitudes_vinculacion.php';
|
|
}
|
|
|
|
function alta()
|
|
{
|
|
if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'admin_agencia') {
|
|
header('Location: /IMPORTADORES/login');
|
|
exit;
|
|
}
|
|
|
|
include __DIR__ . '/../../views/agencias/alta_agentes.php';
|
|
}
|
|
|
|
function guardarAgente()
|
|
{
|
|
if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'admin_agencia') {
|
|
header("Location: /IMPORTADORES/agencias/alta?error=unauthorized");
|
|
exit;
|
|
}
|
|
|
|
$conn = getConnection();
|
|
|
|
try {
|
|
if (!sqlsrv_begin_transaction($conn)) {
|
|
error_log("ERROR: No se pudo iniciar la transacción");
|
|
throw new Exception("Error al iniciar transacción");
|
|
}
|
|
|
|
error_log("Transacción iniciada correctamente");
|
|
|
|
// 1. Capturar y validar datos
|
|
$nombre = trim($_POST['nombre'] ?? '');
|
|
$email = trim($_POST['email'] ?? '');
|
|
$password = $_POST['password'] ?? '';
|
|
$tipo = $_POST['tipo_usuario'] ?? '';
|
|
|
|
if (empty($nombre) || empty($email) || empty($password) || empty($tipo)) {
|
|
header("Location: /IMPORTADORES/agencias/alta?error=invalid_data");
|
|
exit;
|
|
}
|
|
|
|
if ($tipo !== 'agente_aduanal') {
|
|
error_log("DEBUG 5: Tipo de usuario inválido: $tipo");
|
|
header("Location: /IMPORTADORES/agencias/alta?error=invalid_user_type");
|
|
exit;
|
|
}
|
|
|
|
// 2. Encriptar datos sensibles
|
|
$nombre_encrypted = encrypt($nombre);
|
|
$email_encrypted = encrypt($email);
|
|
$password_hash = password_hash($password, PASSWORD_DEFAULT);
|
|
|
|
// 3. Validar duplicado por email encriptado
|
|
$sqlCheck = "SELECT COUNT(*) AS total FROM usuarios_sistema WHERE email = ?";
|
|
$stmtCheck = sqlsrv_query($conn, $sqlCheck, [$email_encrypted]);
|
|
$rowCheck = sqlsrv_fetch_array($stmtCheck, SQLSRV_FETCH_ASSOC);
|
|
if ($rowCheck['total'] > 0) {
|
|
header("Location: /IMPORTADORES/agencias/alta?error=email_exists");
|
|
exit;
|
|
}
|
|
|
|
// 4. Insertar usuario
|
|
$sqlInsert = "
|
|
INSERT INTO usuarios_sistema (nombre, email, password_hash, tipo_usuario, activo, creado_en, dos_factores, creado_por)
|
|
OUTPUT INSERTED.id_usuario
|
|
VALUES (?, ?, ?, ?, 1, GETDATE(), 0, ?)";
|
|
$params = [$nombre_encrypted, $email_encrypted, $password_hash, $tipo, $_SESSION['usuario_id']];
|
|
$stmtInsert = sqlsrv_query($conn, $sqlInsert, $params);
|
|
|
|
if ($stmtInsert === false) {
|
|
error_log("ERROR: Fallo al insertar usuario");
|
|
error_log(print_r(sqlsrv_errors(), true));
|
|
throw new Exception("Error al insertar usuario");
|
|
}
|
|
|
|
$idUsuarioRow = sqlsrv_fetch_array($stmtInsert, SQLSRV_FETCH_ASSOC);
|
|
$id_usuario = $idUsuarioRow['id_usuario'] ?? null;
|
|
|
|
if (!$id_usuario) {
|
|
error_log("ERROR: No se obtuvo id_usuario tras el insert");
|
|
throw new Exception("Error al obtener ID del nuevo usuario");
|
|
}
|
|
|
|
// 6. Obtener la agencia del administrador actual
|
|
$sqlAgencia = "SELECT id_agencia FROM agencias_aduanales WHERE id_administrador = ?";
|
|
$stmtAgencia = sqlsrv_query($conn, $sqlAgencia, [$_SESSION['usuario_id']]);
|
|
$agenciaRow = sqlsrv_fetch_array($stmtAgencia, SQLSRV_FETCH_ASSOC);
|
|
$id_agencia = $agenciaRow['id_agencia'] ?? null;
|
|
|
|
if (!$id_agencia) {
|
|
error_log("ERROR: No se encontró agencia para el admin_agencia con id_usuario=" . $_SESSION['usuario_id']);
|
|
throw new Exception("No se encontró agencia asociada al administrador");
|
|
}
|
|
|
|
// 7. Crear la relación agente-agencia
|
|
$sqlRelacion = "INSERT INTO agente_agencia (id_agente, id_agencia, fecha_asignacion, activo, asignado_por)
|
|
VALUES (?, ?, GETDATE(), 1, ?)";
|
|
$paramsRelacion = [$id_usuario, $id_agencia, $_SESSION['usuario_id']];
|
|
$stmtRelacion = sqlsrv_query($conn, $sqlRelacion, $paramsRelacion);
|
|
|
|
if ($stmtRelacion === false) {
|
|
error_log("ERROR: No se pudo insertar la relación agente-agencia");
|
|
error_log(print_r(sqlsrv_errors(), true));
|
|
throw new Exception("Error al guardar relación agente-agencia");
|
|
}
|
|
|
|
// 8. CONFIRMAR TRANSACCIÓN ✅
|
|
if (!sqlsrv_commit($conn)) {
|
|
error_log("ERROR: No se pudo confirmar la transacción");
|
|
throw new Exception("Error al confirmar transacción");
|
|
}
|
|
|
|
// 9. Enviar correo de bienvenida
|
|
if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
|
|
$mail = new PHPMailer(true);
|
|
try {
|
|
$mail->isSMTP();
|
|
$mail->Host = 'secure.emailsrvr.com';
|
|
$mail->SMTPAuth = true;
|
|
$mail->Username = 'noreply@aduanasoft.com.mx';
|
|
$mail->Password = $_ENV['SMTP_PASS'] ?? '';
|
|
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
|
|
$mail->Port = 587;
|
|
|
|
$mail->setFrom('noreply@aduanasoft.com.mx', 'SIIH | Sistema Integral para Importadores de Hidrocarburos');
|
|
$mail->addAddress($email); // Email sin encriptar para el envío
|
|
$mail->CharSet = 'UTF-8';
|
|
$mail->isHTML(true);
|
|
$mail->Subject = 'Tu acceso a la plataforma SIIH ha sido creado';
|
|
|
|
// Determinar el tipo de usuario para el mensaje
|
|
$tipoUsuarioTexto = match($tipo) {
|
|
'agente_aduanal' => 'agente aduanal',
|
|
default => 'usuario'
|
|
};
|
|
|
|
$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, #003366, #0055A5); padding: 20px; text-align: center;'>
|
|
<h2 style='color: white;'>¡Bienvenido a SIIH!</h2>
|
|
</div>
|
|
<div style='padding: 30px; color: #333; font-size: 16px;'>
|
|
<p>Hola <strong>$nombre</strong>,</p>
|
|
<p>Se ha creado tu cuenta en la plataforma SIIH con el rol de <strong>$tipoUsuarioTexto</strong>.</p>
|
|
<p>Aquí tienes tus credenciales de acceso:</p>
|
|
<div style='background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 20px 0;'>
|
|
<p><strong>Correo:</strong> $email</p>
|
|
<p><strong>Contraseña:</strong> $password</p>
|
|
</div>
|
|
<p>📌 <strong>Importante:</strong> Te recomendamos cambiar tu contraseña una vez que ingreses al sistema por primera vez.</p>
|
|
<p style='text-align: center; margin-top: 30px;'>
|
|
<a href='http://siih.aduanasoft.com/IMPORTADORES/login'
|
|
style='background: #0055A5; color: white; padding: 12px 25px; text-decoration: none; border-radius: 5px; display: inline-block;'>
|
|
Acceder al Sistema
|
|
</a>
|
|
</p>
|
|
</div>
|
|
<div style='background: #e9ecef; text-align: center; padding: 15px; font-size: 13px; color: #666;'>
|
|
© " . date('Y') . " SIIH · Sistema Integral para Importadores de Hidrocarburos
|
|
</div>
|
|
</div>
|
|
</div>";
|
|
|
|
$mail->send();
|
|
|
|
} catch (Exception $e) {
|
|
error_log("Error al enviar correo: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
// 10. Redirigir con mensaje de éxito
|
|
header("Location: /IMPORTADORES/agencias/alta?success=created");
|
|
exit;
|
|
|
|
} catch (Exception $e) {
|
|
error_log("ERROR CAPTURADO: " . $e->getMessage());
|
|
if (!sqlsrv_rollback($conn)) {
|
|
error_log("ERROR: No se pudo revertir la transacción");
|
|
} else {
|
|
error_log("Transacción revertida exitosamente");
|
|
}
|
|
|
|
error_log("=== FIN CON ERROR guardar_agencia ===");
|
|
header("Location: /IMPORTADORES/agencias/alta?error=save_failed");
|
|
exit;
|
|
} finally {
|
|
if ($conn) {
|
|
sqlsrv_close($conn);
|
|
error_log("Conexión cerrada");
|
|
}
|
|
}
|
|
} |