0, 'errors' => ["Error al subir el archivo CSV."] ]; header('Location: /IMPORTADORES/transportes/importar'); exit; } $tmp = $_FILES['csv']['tmp_name']; $handle = fopen($tmp, 'r'); $headers = fgetcsv($handle, 1000, ','); $conn = getConnection(); $usr = $_SESSION['usuario_id']; $imported = 0; $errors = []; $row = 1; while (($data = fgetcsv($handle, 1000, ',')) !== false) { $row++; if (count($data) < 3) { $errors[] = "Fila $row: formato incorrecto."; continue; } list($vehiculo, $identFiscal, $idTrans) = array_map('trim', $data); // Validaciones básicas if ($vehiculo === '' || $identFiscal === '' || !is_numeric($idTrans)) { $errors[] = "Fila $row: datos incompletos o inválidos."; continue; } // Verificar que el transportista pertenezca al usuario $sqlCheck = "SELECT COUNT(*) AS cnt FROM dbo.transportistas WHERE id_transportista = ? AND id_usuario = ?"; $stmtCheck = sqlsrv_query($conn, $sqlCheck, [$idTrans, $usr]); $rCheck = sqlsrv_fetch_array($stmtCheck, SQLSRV_FETCH_ASSOC); if ($rCheck['cnt'] == 0) { $errors[] = "Fila $row: transportista $idTrans no válido."; continue; } // Insertar sin foto $sql = "INSERT INTO dbo.transportes (vehiculo, identificador_fiscal, foto_url, status, id_transportista) VALUES (?, ?, NULL, 1, ?)"; $stmt = sqlsrv_query($conn, $sql, [$vehiculo, $identFiscal, $idTrans]); if ($stmt === false) { $errors[] = "Fila $row: error al insertar."; continue; } $imported++; } fclose($handle); // Guardar resultado en sesión y redirigir de vuelta al formulario $_SESSION['import_result'] = [ 'imported' => $imported, 'errors' => $errors ]; header('Location: /IMPORTADORES/transportes/masivo'); exit; }