352 lines
15 KiB
PHP
352 lines
15 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 alta()
|
|
{
|
|
if (!isset($_SESSION['usuario_id']) || $_SESSION['tipo_usuario'] !== 'admin_agencia') {
|
|
header('Location: /IMPORTADORES/login');
|
|
exit;
|
|
}
|
|
|
|
$conn = getConnection();
|
|
|
|
// DEBUG: Verificar conexión
|
|
if (!$conn) {
|
|
die("Error de conexión: " . print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
// Obtener la agencia del administrador actual
|
|
$sqlAgencia = "SELECT id_agencia FROM agencias_aduanales WHERE id_administrador = ?";
|
|
$stmtAgencia = sqlsrv_query($conn, $sqlAgencia, [$_SESSION['usuario_id']]);
|
|
|
|
// DEBUG: Verificar query de agencia
|
|
if ($stmtAgencia === false) {
|
|
die("Error en consulta de agencia: " . print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
$rowAgencia = sqlsrv_fetch_array($stmtAgencia, SQLSRV_FETCH_ASSOC);
|
|
|
|
// DEBUG: Verificar si se encontró la agencia
|
|
if (!$rowAgencia) {
|
|
die("No se encontró agencia para el administrador ID: " . $_SESSION['usuario_id']);
|
|
}
|
|
|
|
$id_agencia = $rowAgencia['id_agencia'];
|
|
|
|
// === CONSULTA DE AGENTES ADUANALES ===
|
|
// Verificar si hay registros en la tabla agente_agencia
|
|
$sqlCount = "SELECT COUNT(*) as total FROM agente_agencia WHERE id_agencia = ?";
|
|
$stmtCount = sqlsrv_query($conn, $sqlCount, [$id_agencia]);
|
|
$rowCount = sqlsrv_fetch_array($stmtCount, SQLSRV_FETCH_ASSOC);
|
|
|
|
// Verificar registros activos
|
|
$sqlCountActive = "SELECT COUNT(*) as total FROM agente_agencia WHERE id_agencia = ? AND activo = 1";
|
|
$stmtCountActive = sqlsrv_query($conn, $sqlCountActive, [$id_agencia]);
|
|
$rowCountActive = sqlsrv_fetch_array($stmtCountActive, SQLSRV_FETCH_ASSOC);
|
|
|
|
// Consulta de agentes vinculados ACTIVOS a MI agencia
|
|
$sql = "SELECT
|
|
u.id_usuario, u.nombre, u.email, u.tipo_usuario as tipo_usuario_sistema, u.activo,
|
|
u.creado_en, u.creado_por, creador.nombre as nombre_creador,
|
|
aa.fecha_asignacion as fecha_vinculacion, aa.id_relacion, 'agente' as tipo_vinculacion
|
|
FROM agente_agencia aa
|
|
INNER JOIN usuarios_sistema u
|
|
ON aa.id_agente = u.id_usuario
|
|
LEFT JOIN usuarios_sistema creador
|
|
ON u.creado_por = creador.id_usuario
|
|
WHERE aa.id_agencia = ?
|
|
AND aa.activo = 1
|
|
AND u.activo = 1
|
|
ORDER BY aa.fecha_asignacion DESC
|
|
";
|
|
$stmt = sqlsrv_query($conn, $sql, [$id_agencia]);
|
|
|
|
// DEBUG: Verificar query de agentes
|
|
if ($stmt === false) {
|
|
die("Error en consulta de agentes: " . print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
$agentes = [];
|
|
if ($stmt !== false) {
|
|
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
|
$agentes[] = $row;
|
|
}
|
|
}
|
|
|
|
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 {
|
|
// === AGREGADO: LOG DE DEPURACIÓN ===
|
|
error_log("=== INICIO DEBUG guardarAgente ===");
|
|
error_log("POST data: " . print_r($_POST, true));
|
|
error_log("SESSION usuario_id: " . $_SESSION['usuario_id']);
|
|
error_log("SESSION tipo_usuario: " . $_SESSION['tipo_usuario']);
|
|
|
|
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'] ?? '';
|
|
|
|
// === AGREGADO: VALIDACIÓN DETALLADA ===
|
|
error_log("Datos capturados:");
|
|
error_log("nombre: '$nombre'");
|
|
error_log("email: '$email'");
|
|
error_log("password: " . (empty($password) ? 'VACÍO' : 'NO VACÍO'));
|
|
error_log("tipo: '$tipo'");
|
|
|
|
if (empty($nombre) || empty($email) || empty($password) || empty($tipo)) {
|
|
error_log("ERROR: Datos incompletos");
|
|
error_log("nombre vacío: " . (empty($nombre) ? 'SÍ' : 'NO'));
|
|
error_log("email vacío: " . (empty($email) ? 'SÍ' : 'NO'));
|
|
error_log("password vacío: " . (empty($password) ? 'SÍ' : 'NO'));
|
|
error_log("tipo vacío: " . (empty($tipo) ? 'SÍ' : 'NO'));
|
|
header("Location: /IMPORTADORES/agencias/alta?error=invalid_data");
|
|
exit;
|
|
}
|
|
|
|
if ($tipo !== 'agente_aduanal') {
|
|
error_log("ERROR: 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);
|
|
|
|
error_log("Datos encriptados exitosamente");
|
|
|
|
// 3. Validar duplicado por email encriptado
|
|
$sqlCheck = "SELECT COUNT(*) AS total FROM usuarios_sistema WHERE email = ?";
|
|
$stmtCheck = sqlsrv_query($conn, $sqlCheck, [$email_encrypted]);
|
|
|
|
if ($stmtCheck === false) {
|
|
error_log("ERROR: Fallo en consulta de duplicado");
|
|
error_log(print_r(sqlsrv_errors(), true));
|
|
throw new Exception("Error al verificar duplicado");
|
|
}
|
|
|
|
$rowCheck = sqlsrv_fetch_array($stmtCheck, SQLSRV_FETCH_ASSOC);
|
|
if ($rowCheck['total'] > 0) {
|
|
error_log("ERROR: Email ya existe");
|
|
header("Location: /IMPORTADORES/agencias/alta?error=email_exists");
|
|
exit;
|
|
}
|
|
|
|
error_log("Validación de duplicado pasada");
|
|
|
|
// 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']];
|
|
|
|
error_log("Parámetros para INSERT:");
|
|
error_log("nombre_encrypted: " . (empty($nombre_encrypted) ? 'VACÍO' : 'OK'));
|
|
error_log("email_encrypted: " . (empty($email_encrypted) ? 'VACÍO' : 'OK'));
|
|
error_log("password_hash: " . (empty($password_hash) ? 'VACÍO' : 'OK'));
|
|
error_log("tipo: '$tipo'");
|
|
error_log("creado_por: " . $_SESSION['usuario_id']);
|
|
|
|
$stmtInsert = sqlsrv_query($conn, $sqlInsert, $params);
|
|
|
|
if ($stmtInsert === false) {
|
|
error_log("ERROR: Fallo al insertar usuario");
|
|
error_log("SQL: $sqlInsert");
|
|
error_log("Errores SQL Server:");
|
|
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");
|
|
error_log("idUsuarioRow: " . print_r($idUsuarioRow, true));
|
|
throw new Exception("Error al obtener ID del nuevo usuario");
|
|
}
|
|
|
|
error_log("Usuario insertado exitosamente con ID: $id_usuario");
|
|
|
|
// 5. Obtener la agencia del administrador actual
|
|
$sqlAgencia = "SELECT id_agencia FROM agencias_aduanales WHERE id_administrador = ?";
|
|
$stmtAgencia = sqlsrv_query($conn, $sqlAgencia, [$_SESSION['usuario_id']]);
|
|
|
|
if ($stmtAgencia === false) {
|
|
error_log("ERROR: Fallo al consultar agencia");
|
|
error_log(print_r(sqlsrv_errors(), true));
|
|
throw new Exception("Error al consultar agencia");
|
|
}
|
|
|
|
$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']);
|
|
error_log("agenciaRow: " . print_r($agenciaRow, true));
|
|
throw new Exception("No se encontró agencia asociada al administrador");
|
|
}
|
|
|
|
error_log("Agencia encontrada con ID: $id_agencia");
|
|
|
|
// 6. 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']];
|
|
|
|
error_log("Parámetros para relación agente-agencia:");
|
|
error_log("id_agente: $id_usuario");
|
|
error_log("id_agencia: $id_agencia");
|
|
error_log("asignado_por: " . $_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("SQL: $sqlRelacion");
|
|
error_log("Errores SQL Server:");
|
|
error_log(print_r(sqlsrv_errors(), true));
|
|
throw new Exception("Error al guardar relación agente-agencia");
|
|
}
|
|
|
|
error_log("Relación agente-agencia creada exitosamente");
|
|
|
|
// 7. CONFIRMAR TRANSACCIÓN ✅
|
|
if (!sqlsrv_commit($conn)) {
|
|
error_log("ERROR: No se pudo confirmar la transacción");
|
|
error_log(print_r(sqlsrv_errors(), true));
|
|
throw new Exception("Error al confirmar transacción");
|
|
}
|
|
|
|
error_log("Transacción confirmada exitosamente");
|
|
|
|
// 8. 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();
|
|
error_log("Correo enviado exitosamente");
|
|
|
|
} catch (Exception $e) {
|
|
error_log("Error al enviar correo: " . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
error_log("=== FIN EXITOSO guardarAgente ===");
|
|
// 9. Redirigir con mensaje de éxito
|
|
header("Location: /IMPORTADORES/agencias/alta?success=created");
|
|
exit;
|
|
|
|
} catch (Exception $e) {
|
|
error_log("ERROR CAPTURADO: " . $e->getMessage());
|
|
error_log("Stack trace: " . $e->getTraceAsString());
|
|
|
|
if (!sqlsrv_rollback($conn)) {
|
|
error_log("ERROR: No se pudo revertir la transacción");
|
|
error_log(print_r(sqlsrv_errors(), true));
|
|
} else {
|
|
error_log("Transacción revertida exitosamente");
|
|
}
|
|
|
|
error_log("=== FIN CON ERROR guardarAgente ===");
|
|
header("Location: /IMPORTADORES/agencias/alta?error=save_failed");
|
|
exit;
|
|
} finally {
|
|
if ($conn) {
|
|
sqlsrv_close($conn);
|
|
error_log("Conexión cerrada");
|
|
}
|
|
}
|
|
} |