false, 'message' => 'Sesión expirada']); exit; } if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'Método no permitido']); exit; } $input = json_decode(file_get_contents('php://input'), true); if (json_last_error() !== JSON_ERROR_NONE) { http_response_code(400); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'JSON inválido']); exit; } $host = trim($input['host'] ?? ''); $port = intval($input['port'] ?? 80); $protocol = $input['protocol'] ?? 'https'; $usuario = trim($input['usuario'] ?? ''); $password = $input['password'] ?? ''; $sync_pedimentos = $input['sync_pedimentos'] ?? true; $sync_coves = $input['sync_coves'] ?? true; // Validaciones if (empty($host) || empty($usuario) || empty($password)) { http_response_code(400); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'Todos los campos son obligatorios']); exit; } // Encriptar contraseña $encryptedPassword = encrypt($password); // Verificar si existe configuración $sqlCheck = "SELECT id FROM winsaai_config WHERE id_usuario = ?"; $stmtCheck = sqlsrv_query($conn, $sqlCheck, [$userId]); if ($stmtCheck === false) { http_response_code(500); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'Error en base de datos']); exit; } $existingConfig = sqlsrv_fetch_array($stmtCheck, SQLSRV_FETCH_ASSOC); sqlsrv_free_stmt($stmtCheck); if ($existingConfig) { // Actualizar $sql = "UPDATE winsaai_config SET host = ?, port = ?, protocol = ?, usuario = ?, password = ?, sync_pedimentos = ?, sync_coves = ?, updated_at = GETDATE() WHERE id_usuario = ?"; $params = [$host, $port, $protocol, $usuario, $encryptedPassword, $sync_pedimentos ? 1 : 0, $sync_coves ? 1 : 0, $userId]; } else { // Insertar $sql = "INSERT INTO winsaai_config (id_usuario, host, port, protocol, usuario, password, sync_pedimentos, sync_coves) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; $params = [$userId, $host, $port, $protocol, $usuario, $encryptedPassword, $sync_pedimentos ? 1 : 0, $sync_coves ? 1 : 0]; } $stmt = sqlsrv_query($conn, $sql, $params); if ($stmt === false) { http_response_code(500); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'Error al guardar configuración']); exit; } sqlsrv_free_stmt($stmt); header('Content-Type: application/json'); echo json_encode(['success' => true, 'message' => 'Configuración guardada correctamente']); } function get_config() { $conn = getConnection(); $userId = $_SESSION['usuario_id'] ?? null; if (!$userId) { http_response_code(401); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'Sesión expirada']); exit; } $sql = "SELECT * FROM winsaai_config WHERE id_usuario = ?"; $stmt = sqlsrv_query($conn, $sql, [$userId]); if ($stmt === false) { http_response_code(500); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'Error en base de datos']); exit; } $config = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC); sqlsrv_free_stmt($stmt); if ($config) { // No enviar contraseña por seguridad unset($config['password']); // Convertir BIT a boolean $config['sync_pedimentos'] = (bool)$config['sync_pedimentos']; $config['sync_coves'] = (bool)$config['sync_coves']; header('Content-Type: application/json'); echo json_encode(['success' => true, 'data' => $config]); } else { header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'No hay configuración']); } } function test_connection() { $conn = getConnection(); $userId = $_SESSION['usuario_id'] ?? null; if (!$userId) { http_response_code(401); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'Sesión expirada']); exit; } $input = json_decode(file_get_contents('php://input'), true); $host = trim($input['host'] ?? ''); $port = intval($input['port'] ?? 80); $protocol = $input['protocol'] ?? 'https'; $usuario = trim($input['usuario'] ?? ''); $password = $input['password'] ?? ''; if (empty($host) || empty($usuario) || empty($password)) { http_response_code(400); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'Faltan datos para probar conexión']); exit; } $url = "{$protocol}://{$host}:{$port}/api/test"; // Simular prueba de conexión (aquí pondrías la lógica real) header('Content-Type: application/json'); echo json_encode(['success' => true, 'message' => "Conexión exitosa con {$protocol}://{$host}:{$port}"]); } function sync_data() { $conn = getConnection(); $userId = $_SESSION['usuario_id'] ?? null; if (!$userId) { http_response_code(401); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'Sesión expirada']); exit; } // Obtener configuración del usuario $sql = "SELECT * FROM winsaai_config WHERE id_usuario = ?"; $stmt = sqlsrv_query($conn, $sql, [$userId]); if ($stmt === false) { http_response_code(500); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'Error en base de datos']); exit; } $config = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC); sqlsrv_free_stmt($stmt); if (!$config) { http_response_code(400); header('Content-Type: application/json'); echo json_encode(['success' => false, 'message' => 'No hay configuración de WINSAAI']); exit; } $input = json_decode(file_get_contents('php://input'), true); $syncType = $input['sync_type'] ?? 'both'; // Simular sincronización $results = []; if ($syncType === 'pedimentos' || $syncType === 'both') { $results['pedimentos'] = ['total' => 10, 'processed' => 10]; } if ($syncType === 'coves' || $syncType === 'both') { $results['coves'] = ['total' => 5, 'processed' => 5]; } // Actualizar última sincronización $sqlUpdate = "UPDATE winsaai_config SET last_sync = GETDATE() WHERE id_usuario = ?"; sqlsrv_query($conn, $sqlUpdate, [$userId]); header('Content-Type: application/json'); echo json_encode(['success' => true, 'message' => 'Sincronización completada', 'data' => $results]); } function index() { header('Content-Type: application/json'); echo json_encode([ 'success' => true, 'message' => 'API WINSAAI disponible', 'endpoints' => [ 'save_config' => '/IMPORTADORES/winsaai/save_config', 'test_connection' => '/IMPORTADORES/winsaai/test_connection', 'sync_data' => '/IMPORTADORES/winsaai/sync_data', 'get_config' => '/IMPORTADORES/winsaai/get_config' ] ]); } ?>