228 lines
8.6 KiB
PHP
228 lines
8.6 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../helpers/session.php';
|
|
require_once __DIR__ . '/../../config/database.php';
|
|
require_once __DIR__ . '/../helpers/crypto.php';
|
|
|
|
function index()
|
|
{
|
|
$conn = getConnection();
|
|
|
|
$id_usuario = $_SESSION['usuario_id'] ?? null;
|
|
|
|
if (!$id_usuario) {
|
|
die("ID de usuario no disponible en la sesión.");
|
|
}
|
|
|
|
// Primero obtenemos la información básica del usuario
|
|
$sql_usuario = "SELECT tipo_usuario, nombre, email FROM usuarios_sistema WHERE id_usuario = ?";
|
|
$stmt_usuario = sqlsrv_query($conn, $sql_usuario, [$id_usuario]);
|
|
|
|
if ($stmt_usuario === false) {
|
|
die(print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
$usuario = sqlsrv_fetch_array($stmt_usuario, SQLSRV_FETCH_ASSOC);
|
|
|
|
if (!$usuario) {
|
|
die("Usuario no encontrado.");
|
|
}
|
|
|
|
$datos = [
|
|
'tipo_usuario' => trim($usuario['tipo_usuario']),
|
|
'nombre' => $usuario['nombre'],
|
|
'correo' => $usuario['email']
|
|
];
|
|
|
|
// Dependiendo del tipo de usuario, obtenemos información adicional
|
|
switch (trim($usuario['tipo_usuario'])) { // Agregué trim() por si hay espacios
|
|
case 'importador':
|
|
$sql_importador = "SELECT * FROM informacion_general WHERE id_usuario = ?";
|
|
$stmt_importador = sqlsrv_query($conn, $sql_importador, [$id_usuario]);
|
|
|
|
if ($stmt_importador !== false) {
|
|
$info_importador = sqlsrv_fetch_array($stmt_importador, SQLSRV_FETCH_ASSOC);
|
|
if ($info_importador) {
|
|
$datos = array_merge($datos, $info_importador);
|
|
}
|
|
}
|
|
break;
|
|
|
|
case 'admin_agencia':
|
|
case 'agente_aduanal':
|
|
$sql_agencia = "SELECT
|
|
aa.id_agencia, aa.nombre_agencia, aa.rfc_agencia,
|
|
aa.direccion AS direccion_agencia, aa.telefono AS telefono_agencia,
|
|
aa.email AS email_agencia, aga.fecha_asignacion
|
|
FROM agente_agencia aga
|
|
INNER JOIN agencias_aduanales aa
|
|
ON aga.id_agencia = aa.id_agencia
|
|
WHERE aga.id_agente = ?
|
|
AND aga.activo = 1
|
|
AND aa.activo = 1
|
|
";
|
|
$stmt_agencia = sqlsrv_query($conn, $sql_agencia, [$id_usuario]);
|
|
|
|
if ($stmt_agencia !== false) {
|
|
$info_agencia = sqlsrv_fetch_array($stmt_agencia, SQLSRV_FETCH_ASSOC);
|
|
if ($info_agencia) {
|
|
$datos = array_merge($datos, $info_agencia);
|
|
}
|
|
}
|
|
break;
|
|
|
|
case 'super_admin':
|
|
// Para super_admin, solo necesitamos la información básica que ya tenemos
|
|
$datos['es_super_admin'] = true; // Flag para identificar en la vista
|
|
break;
|
|
|
|
default:
|
|
break;
|
|
}
|
|
|
|
// Comentar la siguiente línea para ver el debug
|
|
// exit;
|
|
|
|
if (!isset($datos) || !is_array($datos)) {
|
|
$datos = [];
|
|
}
|
|
|
|
include __DIR__ . '/../../views/configuracion/dashboard_configuracion.php';
|
|
}
|
|
|
|
function editar()
|
|
{
|
|
$conn = getConnection();
|
|
|
|
$id_usuario = $_SESSION['usuario_id'] ?? null;
|
|
|
|
if (!$id_usuario) {
|
|
die("ID de usuario no disponible en la sesión.");
|
|
}
|
|
|
|
// Traer los datos existentes del usuario
|
|
$sql = "SELECT * FROM informacion_general WHERE id_usuario = ?";
|
|
$params = [$id_usuario];
|
|
$stmt = sqlsrv_query($conn, $sql, $params);
|
|
|
|
if ($stmt === false) {
|
|
die(print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
$datos = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
|
|
|
include __DIR__ . '/../../views/configuracion/editar.php';
|
|
}
|
|
|
|
function guardar()
|
|
{
|
|
$conn = getConnection();
|
|
|
|
$id_usuario = $_SESSION['usuario_id'] ?? null;
|
|
|
|
if (!$id_usuario) {
|
|
die("ID de usuario no disponible en la sesión.");
|
|
}
|
|
|
|
// Captura los datos del formulario
|
|
$campos = [
|
|
'clave', 'tipo_identificador', 'curp', 'calle', 'num_exterior', 'num_interior',
|
|
'ciudad', 'colonia', 'pais', 'codigo_postal', 'municipio', 'estado', 'telefono', 'fax', 'observaciones'
|
|
];
|
|
$sql_parts = [];
|
|
$params = [];
|
|
|
|
foreach ($campos as $campo) {
|
|
if (isset($_POST[$campo]) && $_POST[$campo] !== '') {
|
|
$sql_parts[] = "$campo = ?";
|
|
$params[] = $_POST[$campo];
|
|
}
|
|
}
|
|
|
|
if (empty($sql_parts)) {
|
|
header("Location: /IMPORTADORES/configuracion");
|
|
exit;
|
|
}
|
|
|
|
// Iniciar transacción para asegurar consistencia
|
|
sqlsrv_begin_transaction($conn);
|
|
|
|
try {
|
|
// 1. Actualiza la tabla informacion_general
|
|
$sql = "UPDATE informacion_general SET " . implode(", ", $sql_parts) . " WHERE id_usuario = ?";
|
|
$params[] = $id_usuario;
|
|
$stmt = sqlsrv_query($conn, $sql, $params);
|
|
|
|
if ($stmt === false) {
|
|
throw new Exception(print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
// 2. Actualiza el teléfono en solicitudes_importadores usando company_name encriptado
|
|
if (isset($_POST['telefono']) && $_POST['telefono'] !== '') {
|
|
$telefono = $_POST['telefono'];
|
|
|
|
// Primero obtenemos el nombre de la empresa de informacion_general
|
|
$sql_get_name = "SELECT nombre FROM informacion_general WHERE id_usuario = ?";
|
|
$params_get_name = [$id_usuario];
|
|
$stmt_get_name = sqlsrv_query($conn, $sql_get_name, $params_get_name);
|
|
|
|
if ($stmt_get_name === false) {
|
|
throw new Exception("Error al obtener nombre de empresa: " . print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
$empresa_data = sqlsrv_fetch_array($stmt_get_name, SQLSRV_FETCH_ASSOC);
|
|
|
|
if ($empresa_data && !empty($empresa_data['nombre'])) {
|
|
$nombre_empresa = $empresa_data['nombre'];
|
|
|
|
// Encriptar el nombre de la empresa para comparar
|
|
$nombre_encriptado = encrypt($nombre_empresa);
|
|
|
|
// Actualizar solicitudes_importadores usando el company_name encriptado
|
|
$sql_solicitud = "UPDATE solicitudes_importadores SET phone = ? WHERE company_name = ?";
|
|
$params_solicitud = [$telefono, $nombre_encriptado];
|
|
$stmt_solicitud = sqlsrv_query($conn, $sql_solicitud, $params_solicitud);
|
|
|
|
if ($stmt_solicitud === false) {
|
|
throw new Exception("Error al actualizar teléfono en solicitudes: " . print_r(sqlsrv_errors(), true));
|
|
}
|
|
|
|
// Verificar si se actualizó algún registro
|
|
$rows_affected = sqlsrv_rows_affected($stmt_solicitud);
|
|
if ($rows_affected === false || $rows_affected == 0) {
|
|
// Log para debugging
|
|
error_log("No se encontró registro en solicitudes_importadores para actualizar teléfono. Empresa: " . $nombre_empresa);
|
|
|
|
// Opcional: Buscar por RFC como fallback
|
|
$sql_rfc = "SELECT rfc FROM informacion_general WHERE id_usuario = ?";
|
|
$stmt_rfc = sqlsrv_query($conn, $sql_rfc, [$id_usuario]);
|
|
|
|
if ($stmt_rfc) {
|
|
$rfc_data = sqlsrv_fetch_array($stmt_rfc, SQLSRV_FETCH_ASSOC);
|
|
if ($rfc_data && !empty($rfc_data['rfc'])) {
|
|
$sql_solicitud_rfc = "UPDATE solicitudes_importadores SET phone = ? WHERE rfc = ?";
|
|
$params_solicitud_rfc = [$telefono, $rfc_data['rfc']];
|
|
$stmt_solicitud_rfc = sqlsrv_query($conn, $sql_solicitud_rfc, $params_solicitud_rfc);
|
|
|
|
if ($stmt_solicitud_rfc === false) {
|
|
error_log("Error al actualizar por RFC: " . print_r(sqlsrv_errors(), true));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
error_log("No se pudo obtener el nombre de la empresa para el usuario: " . $id_usuario);
|
|
}
|
|
}
|
|
|
|
// Confirmar transacción
|
|
sqlsrv_commit($conn);
|
|
|
|
header("Location: /IMPORTADORES/configuracion/index?updated=ok");
|
|
exit;
|
|
|
|
} catch (Exception $e) {
|
|
// Revertir transacción en caso de error
|
|
sqlsrv_rollback($conn);
|
|
die("Error al actualizar datos: " . $e->getMessage());
|
|
}
|
|
} |